QuestionForm
QuestionForm mostra come modulo la domanda più recente ancora senza risposta fra quelle non inviate dalla persona (!message.fromMe). Invia poi la risposta della persona con message.answer(values). Una domanda è un messaggio con un form che chiede alla persona un valore come la direzione di una mossa in un gioco o il numero di posti in una prenotazione. Senza una domanda aperta il componente non mostra niente.
import { useId, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/** What the form says when an answer did not go, by the reason. */
const PROBLEMS = {
failed: 'The answer did not go: try again.',
'not-allowed': 'You cannot answer now.',
};
/** Gives the options of a field as `{ value, label }` (a world can give plain strings). */
function optionsOf(field) {
return (field.options || []).map((option) => (typeof option === 'string' ? { value: option, label: option } : option));
}
/** The values a form starts with: the first option of a choice, nothing elsewhere. */
function startValues(fields) {
const values = {};
for (const field of fields) values[field.name] = field.type === 'select' ? optionsOf(field)[0]?.value ?? '' : '';
return values;
}
/** One open question, as a form. It is drawn again from the start for each new question. */
function OpenQuestion({ question, submitText }) {
const id = useId();
const fields = question.form.fields;
const [values, setValues] = useState(() => startValues(fields));
const [isSending, setIsSending] = useState(false);
const [problem, setProblem] = useState(null);
const submit = async (event) => {
event.preventDefault();
// A number field gives a number, not the text of the field.
const answer = {};
for (const field of fields) {
const value = values[field.name];
answer[field.name] = field.type === 'number' && value !== '' ? Number(value) : value;
}
setIsSending(true);
setProblem(null);
try {
// Answers the question. Once it is answered, the world no longer shows it as open.
const result = await question.answer(answer);
if (result !== 'sent') setProblem(PROBLEMS[result]);
} catch (error) {
setProblem(PROBLEMS[error.code] ?? 'The answer did not go.');
} finally {
setIsSending(false);
}
};
const inputStyle = { padding: '8px 12px', borderRadius: 12, border: '1px solid rgba(127, 127, 127, 0.45)', background: 'transparent', color: 'inherit', font: 'inherit' };
return (
<form onSubmit={submit} aria-labelledby={`${id}-question`}
style={{ display: 'grid', gap: 12, padding: 16, borderRadius: 14, border: '1px solid rgba(42, 84, 196, 0.5)', background: 'rgba(42, 84, 196, 0.06)' }}>
<p id={`${id}-question`} style={{ margin: 0, fontWeight: 600 }}>{question.text}</p>
{fields.map((field) => {
const fieldId = `${id}-${field.name}`;
const change = (event) => setValues({ ...values, [field.name]: event.target.value });
return (
<div key={field.name} style={{ display: 'grid', gap: 4 }}>
<label htmlFor={fieldId} style={{ fontSize: 13, fontWeight: 600 }}>{field.label || field.name}</label>
{field.type === 'select' ? (
<select id={fieldId} value={values[field.name]} onChange={change} style={inputStyle}>
{optionsOf(field).map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select>
) : (
<input id={fieldId} type={field.type === 'number' ? 'number' : 'text'} value={values[field.name]} onChange={change} style={inputStyle} />
)}
</div>
);
})}
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<button type="submit" disabled={isSending}
style={{ padding: '8px 18px', borderRadius: 10, border: 0, background: '#2A54C4', color: '#fff', font: 'inherit', fontWeight: 600, cursor: 'pointer', opacity: isSending ? 0.5 : 1 }}>
{isSending ? 'Sending…' : submitText}
</button>
<span role="status" style={{ fontSize: 13, opacity: 0.8 }}>{problem ?? ''}</span>
</div>
</form>
);
}
/**
* QuestionForm: the newest question of the world that the person has not
* answered yet, as a form with a field for each thing it asks. It shows
* nothing when there is no open question.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} [props.submitText='Answer'] - The words on the button.
*/
export function QuestionForm({ world, submitText = 'Answer' }) {
// A question is a message with a form. Its `isAnswered` turns true once it is answered.
const question = world.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
if (!question) return null;
return <OpenQuestion key={question.id} question={question} submitText={submitText} />;
}
// Using it, on a fake world.
// A fake world to build with: it asks a question, then replies to the answer.
const maze = {
name: 'Maze',
now: { text: 'You stand at a crossroads.' },
onMessage: (message) => {
// An answered question arrives as a message with `values`.
if (message.values) return `You walk ${message.values.direction}, ${message.values.steps} steps.`;
return {
text: 'Which way?',
form: {
fields: [
{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right', 'straight on'] },
{ name: 'steps', label: 'Steps', type: 'number' },
],
},
};
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: maze } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
const said = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<div style={{ display: 'grid', gap: 12, maxWidth: 420 }}>
<h2 style={{ margin: 0 }}>{world.name}</h2>
<p style={{ margin: 0 }}>{said ? said.text : world.now?.text}</p>
<button type="button" disabled={!world.canSend} onClick={() => world.send('start')} style={{ justifySelf: 'start' }}>Start</button>
<QuestionForm world={world} />
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/** What the form says when an answer did not go, by the reason. */
const PROBLEMS = {
failed: 'The answer did not go: try again.',
'not-allowed': 'You cannot answer now.',
};
/** Gives the options of a field as `{ value, label }` (a world can give plain strings). */
function optionsOf(field) {
return (field.options || []).map((option) => (typeof option === 'string' ? { value: option, label: option } : option));
}
/** A number for the ids of the fields in the forms (a label points to its field by id). */
let formCount = 0;
/**
* Makes the form of one open question, with a field for each thing it asks.
* @param {object} question - A message with a `form`.
* @param {string} submitText - The words on the button.
* @returns {HTMLFormElement} The form.
*/
function questionElement(question, submitText) {
formCount += 1;
const id = `question-${formCount}`;
const inputStyle = { padding: '8px 12px', borderRadius: '12px', border: '1px solid rgba(127, 127, 127, 0.45)', background: 'transparent', color: 'inherit', font: 'inherit' };
const form = document.createElement('form');
form.setAttribute('aria-labelledby', `${id}-question`);
Object.assign(form.style, { display: 'grid', gap: '12px', padding: '16px', borderRadius: '14px', border: '1px solid rgba(42, 84, 196, 0.5)', background: 'rgba(42, 84, 196, 0.06)' });
const text = document.createElement('p');
text.id = `${id}-question`;
text.textContent = question.text ?? '';
Object.assign(text.style, { margin: '0', fontWeight: '600' });
form.append(text);
// One field per thing the question asks: a choice, a number or some text.
const controls = {};
for (const field of question.form.fields) {
const wrap = document.createElement('div');
Object.assign(wrap.style, { display: 'grid', gap: '4px' });
const label = document.createElement('label');
label.htmlFor = `${id}-${field.name}`;
label.textContent = field.label || field.name;
Object.assign(label.style, { fontSize: '13px', fontWeight: '600' });
let control;
if (field.type === 'select') {
control = document.createElement('select');
for (const option of optionsOf(field)) control.append(new Option(option.label, option.value));
} else {
control = document.createElement('input');
control.type = field.type === 'number' ? 'number' : 'text';
}
control.id = `${id}-${field.name}`;
Object.assign(control.style, inputStyle);
controls[field.name] = control;
wrap.append(label, control);
form.append(wrap);
}
const bottom = document.createElement('div');
Object.assign(bottom.style, { display: 'flex', alignItems: 'center', gap: '12px' });
const button = document.createElement('button');
button.type = 'submit';
button.textContent = submitText;
Object.assign(button.style, { padding: '8px 18px', borderRadius: '10px', border: '0', background: '#2A54C4', color: '#fff', font: 'inherit', fontWeight: '600', cursor: 'pointer' });
const status = document.createElement('span');
status.setAttribute('role', 'status');
Object.assign(status.style, { fontSize: '13px', opacity: '0.8' });
bottom.append(button, status);
form.append(bottom);
form.onsubmit = async (event) => {
event.preventDefault();
// A number field gives a number, not the text of the field.
const answer = {};
for (const field of question.form.fields) {
const value = controls[field.name].value;
answer[field.name] = field.type === 'number' && value !== '' ? Number(value) : value;
}
button.disabled = true;
button.textContent = 'Sending…';
status.textContent = '';
try {
// Answers the question. Once it is answered, the world no longer shows it as open.
const result = await question.answer(answer);
if (result !== 'sent') status.textContent = PROBLEMS[result];
} catch (error) {
status.textContent = PROBLEMS[error.code] ?? 'The answer did not go.';
} finally {
button.disabled = false;
button.textContent = submitText;
}
};
return form;
}
/**
* Draws into `container` the newest question of the world that the person
* has not answered yet, as a form. It draws nothing when there is no open question.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world, from connectToHost.
* @param {{submitText?: string}} [options] - The words on the button.
* @returns {() => void} Stops following the world and removes what it drew.
*/
export function questionForm(container, world, { submitText = 'Answer' } = {}) {
let shownId = null;
let form = null;
// Called at once, then after every change of the world.
const stop = world.subscribe((node) => {
// A question is a message with a form. Its `isAnswered` turns true once it is answered.
const question = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
// The same question: keep its form as it is, with what the person chose.
if ((question?.id ?? null) === shownId) return;
form?.remove();
form = question ? questionElement(question, submitText) : null;
shownId = question?.id ?? null;
if (form) container.append(form);
});
return () => {
stop();
form?.remove();
};
}
// Using it, on a fake world.
// A fake world to build with: it asks a question, then replies to the answer.
const maze = {
name: 'Maze',
now: { text: 'You stand at a crossroads.' },
onMessage: (message) => {
// An answered question arrives as a message with `values`.
if (message.values) return `You walk ${message.values.direction}, ${message.values.steps} steps.`;
return {
text: 'Which way?',
form: {
fields: [
{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right', 'straight on'] },
{ name: 'steps', label: 'Steps', type: 'number' },
],
},
};
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: maze } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', maxWidth: '420px' });
const title = document.createElement('h2');
title.style.margin = '0';
const said = document.createElement('p');
said.style.margin = '0';
const start = document.createElement('button');
start.textContent = 'Start';
start.style.justifySelf = 'start';
start.onclick = () => world.send('start');
const place = document.createElement('div');
page.append(title, said, start, place);
document.body.append(page);
questionForm(place, world);
world.subscribe((node) => {
const last = node.messages.filter((message) => !message.fromMe).at(-1);
title.textContent = node.name;
said.textContent = last ? last.text : node.now?.text ?? '';
start.disabled = !node.canSend;
});Start fa chiedere al mondo finto "Which way?" con un modulo che sparisce appena rispondi.
message.form.fields elenca i campi della domanda (FormSpec), ognuno con un name, un type e una label facoltativa che se manca viene sostituita da name. Un campo 'select' diventa un <select> con le sue options (oggetti { value, label } o stringhe semplici), un campo 'number' un input numerico e ogni altro tipo un input di testo.
All'invio il componente costruisce values indicizzato per nome del campo e converte con Number() il valore di un campo 'number'. Un risultato 'failed' o 'not-allowed' e un rifiuto della Promise mostrano un messaggio in una regione di stato accanto al pulsante. Dopo una risposta riuscita la domanda ha isAnswered: true e il mondo riceve un messaggio con quei values (Messaggi e domande).
Il modulo viene ricostruito solo quando cambia la domanda aperta. Quello che la persona ha inserito sopravvive quindi a ogni altro cambiamento del mondo (un nuovo punteggio, uno scatto dell'orologio).
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo (o l'agente), da useWorld. |
submitText | 'Answer' | L'etichetta del pulsante di invio. |
Parametri
questionForm(container, world, options) si iscrive al mondo e sostituisce il suo modulo in container con uno nuovo ogni volta che la domanda aperta diventa un'altra.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo (o l'agente), da connectToHost. |
options.submitText | L'etichetta del pulsante di invio. Predefinito 'Answer'. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove il modulo.
Modificalo
- Altri tipi di campo: aggiungi un ramo per un altro
type(un checkbox per un campo sì o no oppure dei radio button per una scelta fra poche opzioni). - Tutte le domande aperte: invece della sola più recente mostra un modulo per ogni messaggio che ha un
formsenzafromMenéisAnswered. - Dentro la conversazione: in una
MessageListmostra questo modulo al posto del messaggio che porta ilform. - Fare tu una domanda:
world.send({ text, form })invia una domanda della persona con un modulo della stessa forma (send› Fare una domanda con un modulo).
Vedi anche
- Rispondi a una domanda con un modulo: la stessa idea in poche righe.
message.answer: i suoi parametri e il suo risultato.ActionButtons: le azioni offerte dalle regole al posto di una domanda.