Messages and questions
world.messages is the conversation between the world and the person, sorted from the oldest message to the newest. It contains the messages of the person, of the world and of its members, the notes of its rules and the questions (messages that carry a form). Your view renders every message together with its images, files, media and charts. It also sends text, images, files, questions and answers on behalf of the person and shows the delivery status of each message.
The messages
On every change of the world, the full list sorted from the oldest message to the newest arrives in node.messages. The list below renders each message differently depending on its sender:
import { useWorld } from './useWorld.js';
// A fake world that greets the person by name.
const arena = {
name: 'Arena',
onMessage: (message, world, person) => `Hello, ${person.name}! Welcome to the ${world.name}.`,
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
{/* The whole list, oldest first, with the id of each message as its key. */}
<div>
{world.messages.length === 0 && 'No messages yet.'}
{world.messages.map((message) => <MessageItem key={message.id} message={message} />)}
</div>
<button onClick={() => world.send('hello')}>Say hello</button>
</>
);
}
// One message, drawn according to who sent it.
function MessageItem({ message }) {
const time = new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
let style = {};
let words = `${message.from}: ${message.text ?? ''}`; // someone else in the world (an agent)
if (message.fromMe) {
// The person's own message, on the right.
style = { textAlign: 'right' };
words = `You: ${message.text ?? ''}`;
} else if (message.isSystem) {
// A note from the rules of the world, in the middle and quieter.
style = { textAlign: 'center', fontStyle: 'italic' };
words = message.text ?? '';
}
return (
<p style={style} title={time}>
{words}
{message.image && <><br /><img src={message.image} alt="" style={{ maxHeight: 80 }} /></>}
</p>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that greets the person by name.
const arena = {
name: 'Arena',
onMessage: (message, world, person) => `Hello, ${person.name}! Welcome to the ${world.name}.`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const list = document.createElement('div');
const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(list, button);
// One message, drawn according to who sent it.
function messageItem(message) {
const item = document.createElement('p');
const time = new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
if (message.fromMe) {
// The person's own message, on the right.
item.style.textAlign = 'right';
item.textContent = `You: ${message.text ?? ''}`;
} else if (message.isSystem) {
// A note from the rules of the world, in the middle and quieter.
item.style.textAlign = 'center';
item.style.fontStyle = 'italic';
item.textContent = message.text ?? '';
} else {
// Someone else in the world (an agent), with their name and words.
item.textContent = `${message.from}: ${message.text ?? ''}`;
}
item.title = time;
if (message.image) {
const picture = document.createElement('img');
picture.src = message.image;
picture.alt = '';
picture.style.maxHeight = '80px';
item.append(document.createElement('br'), picture);
}
return item;
}
// Called at once, then after every change of the world, with the whole list oldest first.
world.subscribe((node) => {
if (node.messages.length === 0) {
list.textContent = 'No messages yet.';
return;
}
list.replaceChildren(...node.messages.map(messageItem));
});Every message has these fields (GuiMessage):
| Field | What it is |
|---|---|
id | Identifier that stays stable for the lifetime of the message. Use it as the React key. |
text | The text of the message. It is null for a message without text such as an image alone. |
image | URL or data URI of the first image for img.src. It is null when the message has no image. |
images | All images in order. |
files | Attached files as { name, type, url }. |
media | Videos, audio, PDFs and links. |
charts | Chart data. |
from | Display name of the sender. |
fromId | Id of the member or of the world that wrote the message. It is null for the person (People and roles). |
time | The moment of the message in milliseconds since the epoch. Date.now() uses the same unit. |
fromMe | true for the messages of the person. |
isSystem | true for the notes of the rules of the world. |
These fields exist only on some messages:
| Field | On | What it is |
|---|---|---|
status | the person's messages | 'sending', 'sent' or 'failed'. |
retry() | the person's messages | Resends a failed message. |
form | a question | The form to fill. |
isAnswered | a question | true after the question has been answered. |
answer(values) | a question | Answers it. |
values | an answer | The answered values keyed by field name. |
answers | an answer | The id of the question it answers. |
A correct list follows four rules:
- Use
idas the key and never the index.loadMoreprepends older messages and shifts every index without changing anyid. textis nullable. Read it asmessage.text ?? ''and render images, files, media and charts from their own fields (below).- Never use
innerHTML. Because the text is untrusted input, assign it totextContentor let React render it. timeis a number.new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })formats it in the locale of the person.
Pictures, files, videos and charts
Content other than text has its own fields: images, files, charts and media for videos, audio, PDFs and links. In this example a fake agent replies with one item of each kind:
import { useWorld } from './useWorld.js';
// A small picture as an inline SVG, because a picture in a message is an image source.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="teal"/></svg>')}`;
// A fake agent whose answer holds words, a picture, a file, a video and a chart.
const coach = {
name: 'Coach',
onMessage: () => ({
text: 'Here is your week',
images: [PICTURE],
files: [{ name: 'plan.txt', type: 'text/plain', url: `data:text/plain;base64,${btoa('Monday: run 5 km')}` }],
media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
}),
};
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: coach } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!agent) return <p>Connecting…</p>;
return (
<>
<button onClick={() => agent.send('My week, please')}>Show my week</button>
<div>
{agent.messages.map((message) => <MessageItem key={message.id} message={message} />)}
</div>
</>
);
}
// One message, with its words and then its pictures, files, media and charts, each in its own field.
// An older webapp does not give these fields, and `?? []` covers that case.
function MessageItem({ message }) {
return (
<div style={{ marginBottom: 12 }}>
<div>{message.fromMe ? 'You' : message.from}: {message.text ?? ''}</div>
{(message.images ?? []).map((image, index) => <img key={index} src={image} alt="" />)}
{(message.files ?? []).map((file, index) => (
// The file of an agent arrives without a name and needs words of your own.
<a key={index} href={file.url} download={file.name ?? 'file'}>Download {file.name ?? 'the file'} ({file.type})</a>
))}
{(message.media ?? []).map((media, index) => (
// A link loads nothing until the person opens it.
<div key={index}><a href={media.url} target="_blank">{media.title ?? media.alt} ({media.type})</a></div>
))}
{(message.charts ?? []).map((chart, index) => (
<div key={index}>
<div>{chart.alt} ({chart.kind} chart)</div>
{chart.series.map((series) => (
<div key={series.label}>{series.label}: {series.points.map(([x, y]) => `${x} ${y}`).join(' · ')}</div>
))}
</div>
))}
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A small picture as an inline SVG, because a picture in a message is an image source.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="teal"/></svg>')}`;
// A fake agent whose answer holds words, a picture, a file, a video and a chart.
const coach = {
name: 'Coach',
onMessage: () => ({
text: 'Here is your week',
images: [PICTURE],
files: [{ name: 'plan.txt', type: 'text/plain', url: `data:text/plain;base64,${btoa('Monday: run 5 km')}` }],
media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
}),
};
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: coach } });
const button = document.createElement('button');
button.textContent = 'Show my week';
button.onclick = () => agent.send('My week, please');
const list = document.createElement('div');
document.body.append(button, list);
// Adds a line of text to an element.
function addLine(parent, text) {
const line = document.createElement('div');
line.textContent = text;
parent.append(line);
return line;
}
// One message, with its words and then its pictures, files, media and charts, each in its own field.
// An older webapp does not give these fields, and `?? []` covers that case.
function messageItem(message) {
const item = document.createElement('div');
item.style.marginBottom = '12px';
addLine(item, `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`);
for (const image of message.images ?? []) {
const picture = document.createElement('img');
picture.src = image;
picture.alt = '';
item.append(picture);
}
for (const file of message.files ?? []) {
// The file of an agent arrives without a name and needs words of your own.
const link = document.createElement('a');
link.href = file.url;
link.download = file.name ?? 'file';
link.textContent = `Download ${file.name ?? 'the file'} (${file.type})`;
item.append(link);
}
for (const media of message.media ?? []) {
// A link loads nothing until the person opens it.
const link = document.createElement('a');
link.href = media.url;
link.target = '_blank';
link.textContent = `${media.title ?? media.alt} (${media.type})`;
addLine(item, '').append(link);
}
for (const chart of message.charts ?? []) {
addLine(item, `${chart.alt} (${chart.kind} chart)`);
for (const series of chart.series) {
addLine(item, `${series.label}: ${series.points.map(([x, y]) => `${x} ${y}`).join(' · ')}`);
}
}
return item;
}
// Called at once, then after every change.
agent.subscribe((node) => {
list.replaceChildren(...node.messages.map(messageItem));
});text does not repeat the attachments. Render the attachments from media and charts and render text unchanged. Content of a kind that the kit does not support yet arrives as plain text in text. A view that always renders text therefore never loses it.
Each of the four fields is rendered in its own way:
imagesholds URLs or data URIs that each go in an<img>of their own. The first one is also inimagefor views that render a single image per message.filesholds{ name, type, url }objects whoseurlis a data URI usable as thehrefof an<a download>. Files sent by an agent havename: nulland need a label of your own. After the webapp reloads, a file sent by the person keeps itsnamebut itsurlbecomesnull.mediaholds remote resources.urlis the address,typeis a MIME type or a provider type ('video/mp4','audio/mpeg','application/pdf','video/youtube', ...) andtitleandaltdescribe the resource in text. Render videos and audio in a<video>or<audio>withpreload="none"to load nothing before playback starts. An'image/...'type goes in an<img>and any other type, PDFs included, becomes a link.chartsholds data with akind('bar','line'or'pie'), aseriesof[x, y]points and analtdescription. Render the data with your own code or with a charting library (Chart) and usealtas the accessible label of the drawing.
// A video plays in the page; nothing loads before the person presses play.
const video = document.createElement('video');
video.src = media.url;
video.controls = true;
video.preload = 'none';
video.setAttribute('aria-label', media.alt);Pitfall
Mount a YouTube or Vimeo player ('video/youtube', 'video/vimeo') only on click. The player is an embedded page of the provider that loads its scripts and may set cookies as soon as it is mounted. Render the title and a play button as the webapp does in its own conversation and replace them with the player when the person clicks.
The four fields have existed since the webapp release of November 2026 and are missing in older webapps such as a phone app that has not been updated. Read them with defaults such as message.images ?? [] and fall back on image and text. Types › GuiMessage describes every field.
Who sent what
Messages come from three kinds of sender and a view usually renders each kind differently:
- The person (
fromMe: true).fromholds a fixed string and never the nickname of the person (that one is inworld.me). TestfromMeand render a label of your own such as "You". Only these messages have astatus. - The rules of the world (
isSystem: true), for example "Round 2 begins" or "It is your turn". Notes, whosefromis the name of the world, carry text, media, charts and questions but never images or files. Views usually render them less prominently than the conversation. In a fake world every reply ofonMessageandonActionis a note unless itsfromnames a member of the world. - Everyone else, whose name is in
from: an agent, another member of the world or the agent itself in the view of an agent.
Matching fromId against members gives the member who wrote a message. When showsSenders is false the world asks the view not to show senders (Who wrote it). The recipe Group messages by who sent them groups consecutive messages of one sender.
Sending text
world.send(text) sends text on behalf of the person. The message appears in world.messages immediately with status: 'sending' and the view must not append it itself. send then resolves with the outcome:
| Result | Meaning | What the view does |
|---|---|---|
'sent' | Delivered. | Nothing. The message already shows 'sent'. |
'failed' | Not delivered. The message stays in the list with status: 'failed'. | Nothing. The list offers a retry (below). |
'not-allowed' | The text was empty or the rules do not accept a message now, for example because it is not the turn of the person. Nothing was added to the list. | Restore the text and show the reason. |
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that answers every message.
const arena = {
name: 'Arena',
onMessage: (message) => `Got it: ${message.text}`,
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<ul>
{world.messages.map((message) => (
<li key={message.id}>
{message.fromMe ? 'You' : message.from}: {message.text}
{/* The person's messages have a status: 'sending', 'sent' or 'failed'. */}
{message.fromMe && ` (${message.status})`}
</li>
))}
</ul>
<MessageBox world={world} />
</>
);
}
function MessageBox({ world }) {
const [text, setText] = useState('');
const [notice, setNotice] = useState('');
async function handleSubmit(event) {
event.preventDefault();
const words = text.trim();
if (!words) return;
setText('');
// 'sent' and 'failed' both leave the message in the list, with its status.
// 'not-allowed' means the rules did not take it, and the view gives the person their words back.
const result = await world.send(words);
if (result === 'not-allowed') {
setText(words);
setNotice('You cannot send now.');
} else {
setNotice('');
}
}
return (
<>
<form onSubmit={handleSubmit}>
<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Write a message" />
{/* The rules say when the person may send (their turn, for example). */}
<button disabled={!world.canSend}>Send</button>
</form>
<p>{notice}</p>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that answers every message.
const arena = {
name: 'Arena',
onMessage: (message) => `Got it: ${message.text}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const list = document.createElement('ul');
const form = document.createElement('form');
const input = document.createElement('input');
const button = document.createElement('button');
const notice = document.createElement('p');
input.placeholder = 'Write a message';
button.textContent = 'Send';
form.append(input, button);
document.body.append(list, form, notice);
form.onsubmit = async (event) => {
event.preventDefault();
const text = input.value.trim();
if (!text) return;
input.value = '';
// 'sent' and 'failed' both leave the message in the list, with its status.
// 'not-allowed' means the rules did not take it, and the view gives the person their words back.
const result = await world.send(text);
if (result === 'not-allowed') {
input.value = text;
notice.textContent = 'You cannot send now.';
} else {
notice.textContent = '';
}
};
// Called at once, then after every change of the world.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('li');
const who = message.fromMe ? 'You' : message.from;
// The person's messages have a status: 'sending', 'sent' or 'failed'.
item.textContent = message.fromMe ? `${who}: ${message.text} (${message.status})` : `${who}: ${message.text}`;
return item;
}));
// The rules say when the person may send (their turn, for example).
button.disabled = !node.canSend;
});- Disable the button while
canSendisfalse.canSendreflects the rules and is alsofalsewhile a message is pending. This prevents double sends (The actions the rules offer). - Inside the webapp
sendcan also reject: with'failed'when the webapp cannot complete the call and with'too-big'for a file over 20 MB. Errors and the person's controls shows how to catch the error.
Delivery and retry
The messages of the person have a status that is 'sending' while they are pending and then becomes 'sent' or 'failed'. On a failed message, retry() resends the same message without adding an entry to the list and resolves with the same values as send.
This fake world fails the first message on purpose (failNext: true):
import { useWorld } from './useWorld.js';
// A fake world whose first message fails (`failNext`), to let you try a retry.
const arena = {
name: 'Arena',
failNext: true,
onMessage: (message) => `Got it: ${message.text}`,
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<ul>
{world.messages.map((message) => (
<li key={message.id}>
{message.fromMe ? `You: ${message.text} (${message.status}) ` : `${message.from}: ${message.text}`}
{/* A failed message can be sent again, as the same message and not a new one. */}
{message.status === 'failed' && <button onClick={() => message.retry()}>Retry</button>}
</li>
))}
</ul>
<button onClick={() => world.send('hello')}>Say hello</button>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world whose first message fails (`failNext`), to let you try a retry.
const arena = {
name: 'Arena',
failNext: true,
onMessage: (message) => `Got it: ${message.text}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const list = document.createElement('ul');
const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(list, button);
// Called at once, then after every change of the world.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('li');
if (!message.fromMe) {
item.textContent = `${message.from}: ${message.text}`;
return item;
}
item.textContent = `You: ${message.text} (${message.status}) `;
// A failed message can be sent again, as the same message and not a new one.
if (message.status === 'failed') {
const retry = document.createElement('button');
retry.textContent = 'Retry';
retry.onclick = () => message.retry();
item.append(retry);
}
return item;
}));
});Show Retry only when status is 'failed'. The recipes Show whether a message was delivered and Retry a failed message show other ways to render the delivery status.
Sending a picture
world.send({ image, text }) sends an image with an optional text. image is a URL or, more often, a data URI that comes from a canvas (canvas.toDataURL('image/jpeg', 0.8)), from a file picked by the person or from the camera.
import { useEffect, useRef } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that likes pictures.
const gallery = {
name: 'Gallery',
onMessage: (message) => (message.image ? 'What a nice picture!' : 'Send me a picture.'),
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: gallery } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<PictureSender world={world} />
<div>
{world.messages.map((message) => (
<p key={message.id}>
{message.fromMe ? 'You' : message.from}: {message.text ?? ''}
{message.image && <img src={message.image} alt={message.text ?? 'A picture'} style={{ display: 'block' }} />}
</p>
))}
</div>
</>
);
}
function PictureSender({ world }) {
const canvasRef = useRef(null);
// The picture to send, drawn here on a canvas. A photo or a file works the same way.
useEffect(() => {
const context = canvasRef.current.getContext('2d');
context.fillStyle = 'crimson';
context.fillRect(0, 0, 60, 60);
}, []);
// A picture is an image source (a data URI), with words that go with it.
function sendPicture() {
world.send({ image: canvasRef.current.toDataURL('image/png'), text: 'A red square' });
}
return (
<>
<canvas ref={canvasRef} width={60} height={60} />
<button onClick={sendPicture}>Send a picture</button>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that likes pictures.
const gallery = {
name: 'Gallery',
onMessage: (message) => (message.image ? 'What a nice picture!' : 'Send me a picture.'),
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: gallery } });
// The picture to send, drawn here on a canvas. A photo or a file works the same way.
const canvas = document.createElement('canvas');
canvas.width = 60;
canvas.height = 60;
const context = canvas.getContext('2d');
context.fillStyle = 'crimson';
context.fillRect(0, 0, 60, 60);
const button = document.createElement('button');
button.textContent = 'Send a picture';
// A picture is an image source (a data URI), with words that go with it.
button.onclick = () => world.send({ image: canvas.toDataURL('image/png'), text: 'A red square' });
const list = document.createElement('div');
document.body.append(canvas, button, list);
// Called at once, then after every change of the world.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('p');
item.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
if (message.image) {
const picture = document.createElement('img');
picture.src = message.image;
picture.alt = message.text ?? 'A picture';
picture.style.display = 'block';
item.append(picture);
}
return item;
}));
});To send an image picked by the person, read the file as a data URI:
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*';
picker.onchange = () => {
const file = picker.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => world.send({ image: reader.result, text: file.name });
reader.readAsDataURL(file);
};A phone photo can take several megabytes. Downscale it on a canvas first (a width of 1,000 pixels is enough for most worlds) and send canvas.toDataURL('image/jpeg', 0.8) instead of the original file. The camera is covered in The camera and the rest of the browser and in the recipe Send a photo from the camera.
Sending a file
world.send({ file, text }) sends a file of at most 20 MB. Pass the File of a file input or of a drop event as it is and let send read its content.
const picker = document.createElement('input');
picker.type = 'file';
picker.onchange = async () => {
const file = picker.files[0];
if (!file) return;
try {
await world.send({ file, text: file.name });
} catch (error) {
if (error.code === 'too-big') showError('Pick a file under 20 MB.');
}
};- Delivered does not mean read. A result of
'sent'means that the world has received the file. Only agents with a file input read it and the others ignore it without an error. Since the owner of the world decides which agents have a file input, ask them before offering a file button. - One image or one file per message. A message with both resolves with
'failed'and sends nothing. - A file over 20 MB makes
sendreject with'too-big'before anything is sent. - A webapp that predates file sending makes
sendreject with'not-allowed-verb'and sends nothing. Hide the file button when this code arrives.
The message of the person has the file in files immediately. send › Send a file has a live example and the full details.
Sending a question
world.send({ text, form }) sends a question on behalf of the person. Its form has the same shape as the forms in the questions of the world (below):
await world.send({
text: 'Which day suits you?',
form: { fields: [{ name: 'day', type: 'select', options: ['Monday', 'Tuesday'] }] },
});The message appears in the list with its form and gets isAnswered: true when the receiver answers. Because the form is also sent as plain text, a world or an agent that does not read forms still understands the question.
Questions from the world
A question is a message with a form. Your view renders the form and message.answer(values) sends the answer of the person.
import { useWorld } from './useWorld.js';
// A fake world that asks a question, then replies to the answer.
const arena = {
name: 'Arena',
onMessage: (message) => {
// An answer arrives as a message with `values`, by field name.
if (message.values) return `You go ${message.values.direction}.`;
return {
text: 'Which way?',
form: { fields: [{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right'] }] },
};
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// The question still open is the newest one from the world with a form that is not answered yet.
const question = world.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
return (
<>
<ul>
{world.messages.map((message) => (
<li key={message.id}>
{message.values
? `You answered: ${Object.values(message.values).join(', ')}`
: `${message.fromMe ? 'You' : message.from}: ${message.text}`}
</li>
))}
</ul>
<button onClick={() => world.send('start')}>Start the game</button>
{/* The key keeps the person's choice while the question stays the same. */}
{question && <QuestionForm key={question.id} message={question} />}
</>
);
}
// The form of a question, with one field per field of `message.form`.
function QuestionForm({ message }) {
function handleSubmit(event) {
event.preventDefault();
message.answer(Object.fromEntries(new FormData(event.target)));
}
return (
<form onSubmit={handleSubmit}>
{message.form.fields.map((field) => (
<label key={field.name}>
{field.label ?? field.name}{' '}
{field.type === 'select' ? (
<select name={field.name}>
{/* Options can be plain strings or { value, label }. */}
{(field.options ?? []).map((option) => {
const value = typeof option === 'string' ? option : option.value;
return <option key={value} value={value}>{typeof option === 'string' ? option : option.label}</option>;
})}
</select>
) : (
<input name={field.name} type={field.type === 'number' ? 'number' : 'text'} />
)}
</label>
))}{' '}
<button>Answer</button>
</form>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that asks a question, then replies to the answer.
const arena = {
name: 'Arena',
onMessage: (message) => {
// An answer arrives as a message with `values`, by field name.
if (message.values) return `You go ${message.values.direction}.`;
return {
text: 'Which way?',
form: { fields: [{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right'] }] },
};
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const list = document.createElement('ul');
const start = document.createElement('button');
start.textContent = 'Start the game';
start.onclick = () => world.send('start');
const formPlace = document.createElement('div');
document.body.append(list, start, formPlace);
// Builds the form of a question, with one field per field of `message.form`.
function questionForm(message) {
const form = document.createElement('form');
for (const field of message.form.fields) {
const label = document.createElement('label');
const input = document.createElement(field.type === 'select' ? 'select' : 'input');
input.name = field.name;
if (field.type === 'number') input.type = 'number';
// Options can be plain strings or { value, label }.
for (const option of field.options ?? []) {
const choice = document.createElement('option');
choice.value = typeof option === 'string' ? option : option.value;
choice.textContent = typeof option === 'string' ? option : option.label;
input.append(choice);
}
label.append(`${field.label ?? field.name} `, input);
form.append(label);
}
const button = document.createElement('button');
button.textContent = 'Answer';
form.append(' ', button);
form.onsubmit = (event) => {
event.preventDefault();
message.answer(Object.fromEntries(new FormData(form)));
};
return form;
}
let shownQuestionId = null;
// Called at once, then after every change of the world.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('li');
item.textContent = message.values
? `You answered: ${Object.values(message.values).join(', ')}`
: `${message.fromMe ? 'You' : message.from}: ${message.text}`;
return item;
}));
// The question still open is the newest one from the world with a form that is not answered yet.
const question = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
// Build the form only when the question changes, to keep what the person chose through other changes.
if ((question?.id ?? null) === shownQuestionId) return;
shownQuestionId = question?.id ?? null;
formPlace.replaceChildren(...(question ? [questionForm(question)] : []));
});The form. message.form.fields is the list of fields:
| Field | What it is |
|---|---|
name | The key of the value in values. |
type | 'select', 'text', 'number' or another type that the world uses. |
label | The label to render. Fall back on name when it is missing. |
options | The options of a choice as { value, label }. Plain strings are accepted only in the forms you send. |
The answer. message.answer(values) takes an object keyed by field name such as { direction: 'right' } and resolves like send:
- a question is answered once, after which
isAnsweredistrueandanswerresolves with'not-allowed' answerresolves with'not-allowed'whenvaluescontains no field of the form- the answer appears in the list as a message of the person that carries three things: the answered
values, a text version of the answer for views that render only text and theidof the question inanswers.
Because FormData yields strings, convert a 'number' field with Number(value).
The open question is the newest unanswered question from the world:
const open = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);Keep the form mounted while the question does not change. A form rebuilt on every change of the world (a clock, a score) loses the input of the person. In React set key={question.id} on the form. In plain JavaScript the example rebuilds it only when the id of the open question changes.
The recipe Answer a question with a form and the component QuestionForm handle more field types.
Older messages: loadMore
world.messages starts with the recent part of the conversation. await world.loadMore() prepends older messages and resolves with the number of messages it added or with 0 once none are left. A fake world has no older messages and always resolves with 0.
const older = document.createElement('button');
older.textContent = 'Show older messages';
older.onclick = async () => {
const added = await world.loadMore();
if (added === 0) older.remove(); // nothing older: no need for the button
};The prepended messages arrive through subscribe like any other change. The recipe Load older messages keeps the messages that the person is reading in place while older ones are prepended above them.
Things to watch
- Do not append messages yourself. The message of the person is in
world.messagesas soon assendis called. - Key by
id. Indexes change when older messages are prepended. textis nullable and untrusted. Never put it ininnerHTML.textdoes not include attachments. Read images, files, media and charts from their fields with?? []for older webapps.- Never mutate the list.
filterreturns a new array butsortworks in place and needs a copy first ([...node.messages]). - Event handlers read
world.get().messagesinstead of a value captured earlier (Thinking in views).
Next steps
- The actions the rules offer: the current state and the actions available to the person.
- Components › MessageList and MessageBox: a ready list and a ready input.
send,message.answerandmessage.retryin the reference.