QuestionForm
QuestionForm takes the newest unanswered question that the person did not send (!message.fromMe) and renders it as a form. It sends the answer of the person with message.answer(values). A question is a message with a form that asks the person for a value such as the direction of a move in a game or the number of seats in a booking. Without an open question the component renders nothing.
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 makes the fake world ask "Which way?" with a form that disappears once you answer it.
message.form.fields lists the fields of the question (FormSpec), each with a name, a type and an optional label that falls back on name. A 'select' field becomes a <select> with its options ({ value, label } objects or plain strings), a 'number' field a number input and any other type a text input.
On submit the component builds values keyed by field name and converts the value of a 'number' field with Number(). A 'failed' or 'not-allowed' result and a rejection of the promise show a message in a status region next to the button. After a successful answer the question has isAnswered: true and the world receives a message with those values (Messages and questions).
The form is built again only when the open question changes. Input typed by the person therefore survives every other change of the world (a new score, a clock tick).
Props
| Prop | Default | What it is |
|---|---|---|
world | (required) | The world (or agent), from useWorld. |
submitText | 'Answer' | The label of the submit button. |
Parameters
questionForm(container, world, options) subscribes to the world and replaces its form in container with a new one whenever a different question becomes the open one.
| Parameter | What it is |
|---|---|
container | The element to draw into. |
world | The world (or agent), from connectToHost. |
options.submitText | The label of the submit button. Default 'Answer'. |
It returns a function that unsubscribes from the world and removes the form.
Change it
- More field types: add a branch for another
type(a checkbox for a yes-or-no field or radio buttons for a choice with few options). - Every open question: render one form per message that has a
form, nofromMeand noisAnsweredinstead of only the newest. - Inside the conversation: in a
MessageList, render this form in place of the message that carries theform. - Ask a question yourself:
world.send({ text, form })sends a question of the person with a form of the same shape (send› Ask a question with a form).
See also
- Answer a question with a form: the same idea in a few lines.
message.answer: its parameters and its result.ActionButtons: the actions offered by the rules in place of a question.