Skip to content

Rispondi a una domanda con un modulo ​

Un mondo o un agente fa una domanda alla persona (una taglia da scegliere, un nome da scrivere) inviando un messaggio con un form. La tua vista disegna un input per ogni campo del modulo e invia con message.answer(values) quello che la persona ha compilato. Nell'esempio ordina un caffè e rispondi alla domanda del 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;
	}));
});
Live, on a fake world
Open

Come funziona ​

  1. message.form.fields elenca i campi della domanda. Ogni campo ha un name, un type ('select', 'text', 'number', …) e una label facoltativa. Un campo a scelta elenca anche le sue options. In un messaggio ogni opzione arriva come oggetto { value, label }. Le stringhe semplici sono accettate solo in un modulo che scrivi tu (per esempio in un mondo finto) e la funzione optionOf dell'esempio trasforma anche queste in oggetti { value, label }.
  2. message.answer(values) prende i valori indicizzati per nome del campo ({ size: 'large', name: 'Ada' }) e si risolve con gli stessi risultati di send.
  3. Una domanda accetta una sola risposta. Dopo quella risposta ha isAnswered: true e l'esempio smette di mostrarne il modulo.
  4. La risposta compare nella conversazione come un messaggio della persona con i valori inviati nel campo values. Un mondo o un agente finto riceve lo stesso oggetto in onMessage e ne legge i valori da message.values.

In JavaScript semplice la vista costruisce ogni modulo una volta sola e ne conserva gli elementi mentre la persona scrive. La lista dei messaggi viene disegnata di nuovo solo quando cambia l'id di un messaggio o il suo isAnswered e mai mentre la persona compila il modulo.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.