Skip to content

Mostra una risposta accanto alla sua domanda ​

Quando la persona risponde a una domanda, la risposta arriva come un messaggio a sé e occupa un suo posto nella conversazione. Un quiz o un sondaggio, invece, si legge meglio con la risposta dentro la sua domanda ("Quale colore? La tua risposta: blu"). Ogni risposta porta in answers l'id della sua domanda. Con quell'id la tua vista può mostrare la risposta dentro la domanda e lasciarla fuori dalla lista. Avvia il quiz dell'esempio e rispondi alle sue due domande.

jsx
import { useWorld } from './useWorld.js';

// A fake quiz to build with. It answers each message of the person, an answer too,
// with the next question, and with a goodbye once the questions are over.
const QUESTIONS = [
	{ text: 'Which colour?', form: { fields: [{ name: 'colour', type: 'select', options: ['red', 'blue', 'green'] }] } },
	{ text: 'Which animal?', form: { fields: [{ name: 'animal', type: 'select', options: ['cat', 'dog'] }] } },
];
let asked = 0;
const quiz = {
	name: 'Quiz',
	onMessage: () => {
		asked += 1;
		return QUESTIONS[asked - 1] ?? 'Thanks, that is all.';
	},
};

// The options of a field can be plain strings or { value, label }.
const optionOf = (option) => (typeof option === 'string' ? { value: option, label: option } : option);

// One question shows its words and, below them, the person's answer or a button for each option.
function Question({ question, answer }) {
	const field = question.form.fields[0];
	let below;
	if (answer) {
		// The `values` of an answer hold what the person chose, by field name.
		below = `Your answer: ${Object.values(answer.values ?? {}).join(', ')}`;
	} else if (question.isAnswered) {
		below = 'Answered.';
	} else {
		// Since each question here has one choice, the button of an option answers it at once.
		below = field.options.map(optionOf).map((option) => (
			<span key={option.value}><button onClick={() => question.answer({ [field.name]: option.value })}>{option.label}</button> </span>
		));
	}
	return (
		<div style={{ border: '1px solid #8888', borderRadius: 8, padding: 8, margin: '8px 0' }}>
			<div>{question.text}</div>
			<div>{below}</div>
		</div>
	);
}

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: quiz } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	// Keep the answers by the id of the question they answer (`answers`, missing with an older webapp).
	const answerOf = new Map();
	for (const message of world.messages) {
		if (message.answers) answerOf.set(message.answers, message);
	}
	return (
		<>
			{/* Leave the answers out of the list, because each one appears inside its question. */}
			{world.messages.filter((message) => !message.answers).map((message) => (message.form
				? <Question key={message.id} question={message} answer={answerOf.get(message.id)} />
				: <div key={message.id}>{message.fromMe ? 'You' : message.from}: {message.text}</div>
			))}
			<button onClick={() => world.send('Start the quiz')} disabled={!world.canSend}>Start the quiz</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake quiz to build with. It answers each message of the person, an answer too,
// with the next question, and with a goodbye once the questions are over.
const QUESTIONS = [
	{ text: 'Which colour?', form: { fields: [{ name: 'colour', type: 'select', options: ['red', 'blue', 'green'] }] } },
	{ text: 'Which animal?', form: { fields: [{ name: 'animal', type: 'select', options: ['cat', 'dog'] }] } },
];
let asked = 0;
const quiz = {
	name: 'Quiz',
	onMessage: () => {
		asked += 1;
		return QUESTIONS[asked - 1] ?? 'Thanks, that is all.';
	},
};

// The options of a field can be plain strings or { value, label }.
const optionOf = (option) => (typeof option === 'string' ? { value: option, label: option } : option);

// One question shows its words and, below them, the person's answer or a button for each option.
function questionView(question, answer) {
	const card = document.createElement('div');
	card.style.cssText = 'border: 1px solid #8888; border-radius: 8px; padding: 8px; margin: 8px 0;';
	const words = document.createElement('div');
	words.textContent = question.text ?? '';
	card.append(words);
	const below = document.createElement('div');
	if (answer) {
		// The `values` of an answer hold what the person chose, by field name.
		below.textContent = `Your answer: ${Object.values(answer.values ?? {}).join(', ')}`;
	} else if (question.isAnswered) {
		below.textContent = 'Answered.';
	} else {
		// Since each question here has one choice, the button of an option answers it at once.
		const field = question.form.fields[0];
		for (const option of field.options.map(optionOf)) {
			const button = document.createElement('button');
			button.textContent = option.label;
			button.onclick = () => question.answer({ [field.name]: option.value });
			below.append(button, ' ');
		}
	}
	card.append(below);
	return card;
}

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: quiz } });

const list = document.createElement('div');
const start = document.createElement('button');
start.textContent = 'Start the quiz';
start.onclick = () => world.send('Start the quiz');
document.body.append(list, start);

world.subscribe((node) => {
	start.disabled = !node.canSend;
	// Keep the answers by the id of the question they answer (`answers`, missing with an older webapp).
	const answerOf = new Map();
	for (const message of node.messages) {
		if (message.answers) answerOf.set(message.answers, message);
	}
	// Leave the answers out of the list, because each one appears inside its question.
	list.replaceChildren(...node.messages.filter((message) => !message.answers).map((message) => {
		if (message.form) return questionView(message, answerOf.get(message.id));
		const line = document.createElement('div');
		line.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
		return line;
	}));
});
Live, on a fake world
Open

Come funziona ​

Una risposta è un messaggio della persona che ha in più values con i valori scelti indicizzati per nome del campo e answers con l'id del messaggio che contiene la domanda. La vista raccoglie le risposte in una Map che ha quell'id come chiave, mostra ogni domanda insieme alla sua risposta e salta le risposte quando disegna la lista.

  • Ogni domanda dell'esempio ha una sola scelta e finché non ha risposta mostra un pulsante per ogni opzione. Rispondi a una domanda con un modulo gestisce qualsiasi modulo.
  • L'id in answers indica la domanda giusta anche quando fra la domanda e la sua risposta arrivano altri messaggi (una nota delle regole, un messaggio di un altro membro).
  • Con una webapp più vecchia answers manca. In quel caso le risposte restano nella lista come messaggi a sé e ogni domanda che ha avuto risposta (isAnswered) mostra "Answered." sotto il suo testo.

Vedi anche ​

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