Answer a question with a form
A world or an agent asks the person a question (a size to choose, a name to write) by sending a message with a form. Your view draws an input for each field of that form and sends what the person filled in with message.answer(values). In the example, order a coffee and answer the question of the barista.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// While you build, a fake barista asks a question with a form and replies to the answer.
const barista = {
name: 'Barista',
onMessage: (message) => {
// An answered question comes back as a message with `values`, by field name.
if (message.values) return `A ${message.values.size} coffee for ${message.values.name}, coming up!`;
return {
text: 'Which size, and whose name on the cup?',
form: { fields: [
{ name: 'size', type: 'select', options: ['small', 'medium', 'large'] },
{ name: 'name', type: 'text', label: 'Name on the cup' },
] },
};
},
};
// The options of a field can be plain strings or { value, label }.
const optionOf = (option) => (typeof option === 'string' ? { value: option, label: option } : option);
// The form of one question has an input for each of its fields and a button to answer.
function QuestionForm({ message }) {
const [values, setValues] = useState(() => Object.fromEntries(message.form.fields.map((field) => (
[field.name, field.type === 'select' ? optionOf(field.options[0]).value : '']
))));
function handleSubmit(event) {
event.preventDefault();
// answer() sends the values by field name. A question can be answered only once.
message.answer(values);
}
return (
<form onSubmit={handleSubmit}>
{message.form.fields.map((field) => (
<label key={field.name} style={{ display: 'block', margin: '4px 0' }}>
{field.label ?? field.name}{' '}
{field.type === 'select' ? (
<select value={values[field.name]} onChange={(event) => setValues({ ...values, [field.name]: event.target.value })}>
{field.options.map(optionOf).map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select>
) : (
<input type={field.type === 'number' ? 'number' : 'text'} value={values[field.name]} onChange={(event) => setValues({ ...values, [field.name]: event.target.value })} />
)}
</label>
))}
<button>Answer</button>
</form>
);
}
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: barista } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!agent) return <p>Connecting…</p>;
return (
<>
{agent.messages.map((message) => (
<div key={message.id}>
<p><b>{message.fromMe ? 'You' : message.from}:</b> {message.text}</p>
{/* Show the form of a question until its `isAnswered` turns true. */}
{message.form && !message.fromMe && !message.isAnswered && <QuestionForm message={message} />}
</div>
))}
<button onClick={() => agent.send('A coffee, please')} disabled={!agent.canSend}>Order a coffee</button>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// While you build, a fake barista asks a question with a form and replies to the answer.
const barista = {
name: 'Barista',
onMessage: (message) => {
// An answered question comes back as a message with `values`, by field name.
if (message.values) return `A ${message.values.size} coffee for ${message.values.name}, coming up!`;
return {
text: 'Which size, and whose name on the cup?',
form: { fields: [
{ name: 'size', type: 'select', options: ['small', 'medium', 'large'] },
{ name: 'name', type: 'text', label: 'Name on the cup' },
] },
};
},
};
// The options of a field can be plain strings or { value, label }.
const optionOf = (option) => (typeof option === 'string' ? { value: option, label: option } : option);
// The form of one question has an input for each of its fields and a button to answer.
function questionForm(message) {
const form = document.createElement('form');
const inputs = {};
for (const field of message.form.fields) {
const label = document.createElement('label');
label.style.cssText = 'display: block; margin: 4px 0;';
label.append(`${field.label ?? field.name} `);
let input;
if (field.type === 'select') {
input = document.createElement('select');
for (const option of field.options.map(optionOf)) input.append(new Option(option.label, option.value));
} else {
input = document.createElement('input');
input.type = field.type === 'number' ? 'number' : 'text';
}
inputs[field.name] = input;
label.append(input);
form.append(label);
}
const button = document.createElement('button');
button.textContent = 'Answer';
form.append(button);
form.onsubmit = (event) => {
event.preventDefault();
const values = {};
for (const [name, input] of Object.entries(inputs)) values[name] = input.value;
// answer() sends the values by field name. A question can be answered only once.
message.answer(values);
};
return form;
}
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: barista } });
const list = document.createElement('div');
const orderButton = document.createElement('button');
orderButton.textContent = 'Order a coffee';
orderButton.onclick = () => agent.send('A coffee, please');
document.body.append(list, orderButton);
let shown = null; // the messages on the page, and whether each question is answered
agent.subscribe((node) => {
orderButton.disabled = !node.canSend;
// Draw again only when the messages changed, to keep from rebuilding a form that the person is filling in.
const key = node.messages.map((message) => `${message.id}:${Boolean(message.isAnswered)}`).join(' ');
if (key === shown) return;
shown = key;
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('div');
const line = document.createElement('p');
const sender = document.createElement('b');
sender.textContent = `${message.fromMe ? 'You' : message.from}:`;
line.append(sender, ` ${message.text ?? ''}`);
item.append(line);
// Show the form of a question until its `isAnswered` turns true.
if (message.form && !message.fromMe && !message.isAnswered) item.append(questionForm(message));
return item;
}));
});How it works
message.form.fieldslists the fields of the question. Each field has aname, atype('select','text','number', …) and an optionallabel. A choice also lists itsoptions. In a message every option arrives as a{ value, label }object. Plain strings are accepted only in a form you write yourself (in a fake world, for example) and theoptionOfhelper of the example turns them into{ value, label }objects too.message.answer(values)takes the values keyed by field name ({ size: 'large', name: 'Ada' }) and resolves with the same results assend.- A question accepts a single answer. Once answered it has
isAnswered: trueand the example stops rendering its form. - The answer appears in the conversation as a message from the person whose
valuesfield holds the submitted values. A fake world or agent receives the same object inonMessageand reads it frommessage.values.
In plain JavaScript the view builds each form once and keeps the same elements while the person types. It renders the message list again only when the id of a message or its isAnswered changes and never while the person fills in the form.
See also
- QuestionForm: a ready form for any question.
message.answer.FormSpec.