Show an answer next to its question
When the person answers a question, the answer arrives as a message of its own and takes its own place in the conversation. A quiz or a survey, on the other hand, reads better with the answer inside its question ("Which colour? Your answer: blue"). Every answer carries the id of its question in answers. With that id your view can render the answer inside its question and leave it out of the list. Start the quiz in the example and answer its two questions.
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>
</>
);
}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;
}));
});How it works
An answer is a message of the person with two extra fields: values holds the chosen values keyed by field name and answers holds the id of the message with the question. The view collects the answers in a Map keyed by that id, renders each question together with its answer and skips the answers when it renders the list.
- Each question of the example has a single choice and shows one button per option until it is answered. Answer a question with a form handles any form.
- The
idinanswerspoints to the right question even when other messages (a note of the rules, a message of another member) come between the question and its answer. - With an older webapp
answersis missing. In that case the answers stay in the list as messages of their own and each answered question (isAnswered) renders "Answered." below its text.