Talk with the world
The person writes to the world and the world replies with messages of its own. The view now renders the conversation and gets a text box with a Send button.
The world answers
A fake world replies through onMessage. The kit calls this function with each message of the person and turns the returned string into the reply of the world:
onMessage: (message) => {
const word = message.text.trim().toLowerCase();
if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
return `The island does not know “${message.text}”. Try: look.`;
},A real world replies according to its own rules. The view renders whatever arrives in messages and does not depend on how the reply was produced.
The messages
world.messages is the conversation between the person and the world sorted from the oldest message to the newest. The view reads five fields of each message:
id: a stable identifier to use as the Reactkey.text: the text of the message ornullfor a message without text.fromMe:truefor the messages of the person.from: the display name of the sender. A reply of the world itself has'Treasure Island'infrom.isSystem:truefor the notes that the rules of the world write in the conversation. The replies of this fake world are notes of this kind.
The view labels the messages of the person as "You" and aligns them to the right:
<li style={{ margin: '6px 0', textAlign: message.fromMe ? 'right' : 'left' }}>
<span style={{ /* a bubble */ }}>
{message.fromMe ? 'You' : message.from}: {message.text}
</span>
</li>Send
world.send(text) sends a message on behalf of the person and adds it to messages immediately. The reply of the world arrives later as one more message and the view renders it like any other.
function handleSubmit(event) {
event.preventDefault();
if (!text.trim()) return;
world.send(text);
setText('');
}world.canSend is false while the rules of the world refuse messages from the person and while a message is pending. Disable the Send button in both cases and keep the text field enabled (Disable the message box when the person cannot send explains why).
Draw the list only when it changed
On this island the tide changes the world every second and the plain JavaScript listener of subscribe runs on each of these changes. If the list were rebuilt every second, the buttons and forms that the next steps put inside it would lose the focus and whatever the person has typed or selected. The view therefore stores the ids of the messages it rendered and rebuilds the list only when they change:
const key = JSON.stringify(node.messages.map((message) => message.id));
if (key === shown) return;
shown = key;
list.replaceChildren(...node.messages.map(messageItem));React needs no such check because it updates only the DOM nodes whose output changed.
The code
The new lines are highlighted. Type look in the box and send it.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world to build with, a small treasure hunt that needs no account and no network.
// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
const island = {
name: 'Treasure Island',
profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
now: { text: 'The hunt is on.' },
// What the world shows, by name.
data: {
map: MAP,
// Where you are on the map.
position: { row: 3, column: 1 },
// The tide rises and falls: a function of time gives a new value every second.
tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
},
// The world reads what the person writes and answers.
onMessage: (message) => {
const word = message.text.trim().toLowerCase();
if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
return `The island does not know “${message.text}”. Try: look.`;
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: island } });
// The three states of every view: it failed, it is connecting, it is here.
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<main>
<Header world={world} />
<IslandMap data={world.data} />
<Conversation world={world} />
</main>
);
}
// The name of the world, what it is about and what is happening now.
function Header({ world }) {
return (
<header>
<h1>{world.name}</h1>
<p>{world.profile.description}</p>
<p>
Now: {world.now?.text} The world is {world.status}.
</p>
</header>
);
}
// The island from the data of the world: one square per cell, you on yours, and the tide.
function IslandMap({ data }) {
const { map, position, tide } = data;
// A name of `data` can be missing for a moment while the world sends it.
if (!map || !position) return <p>The map is on its way…</p>;
return (
<section>
<div
role="img"
aria-label="Map of the island"
style={{ display: 'grid', gridTemplateColumns: `repeat(${map[0].length}, 44px)`, gap: 2 }}
>
{map.map((row, rowIndex) =>
row.map((ground, columnIndex) => {
const isHere = rowIndex === position.row && columnIndex === position.column;
return (
<div
key={`${rowIndex}-${columnIndex}`}
style={{
height: 44,
display: 'grid',
placeItems: 'center',
fontSize: 24,
borderRadius: 6,
background: isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)',
}}
>
{isHere ? '🧍' : ground}
</div>
);
}),
)}
</div>
<p>
Tide <meter min={0} max={100} value={tide} /> {tide}%
</p>
</section>
);
}
// The conversation with the world, oldest first, and a box to write to it.
function Conversation({ world }) {
const [text, setText] = useState('');
function handleSubmit(event) {
event.preventDefault();
if (!text.trim()) return;
// Sends as the person. The world reads it and answers with a message.
world.send(text);
setText('');
}
return (
<section>
<h2>Messages</h2>
{world.messages.length === 0 && <p>No messages yet. Write “look” to the world.</p>}
<ul style={{ listStyle: 'none', padding: 0 }}>
{world.messages.map((message) => (
<Message key={message.id} message={message} />
))}
</ul>
<form onSubmit={handleSubmit} style={{ display: 'flex', gap: 8 }}>
<input
value={text}
onChange={(event) => setText(event.target.value)}
placeholder="Write to the world"
aria-label="Write to the world"
style={{ flex: 1 }}
/>
{/* canSend: the rules of the world let the person send now. */}
<button disabled={!world.canSend}>Send</button>
</form>
</section>
);
}
// One message: who said it and what. The person's own are on the right.
function Message({ message }) {
return (
<li style={{ margin: '6px 0', textAlign: message.fromMe ? 'right' : 'left' }}>
<span style={{ display: 'inline-block', padding: '6px 10px', borderRadius: 10, background: 'rgba(127, 127, 127, 0.15)' }}>
{message.fromMe ? 'You' : message.from}: {message.text}
</span>
</li>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with, a small treasure hunt that needs no account and no network.
// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
const island = {
name: 'Treasure Island',
profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
now: { text: 'The hunt is on.' },
// What the world shows, by name.
data: {
map: MAP,
// Where you are on the map.
position: { row: 3, column: 1 },
// The tide rises and falls: a function of time gives a new value every second.
tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
},
// The world reads what the person writes and answers.
onMessage: (message) => {
const word = message.text.trim().toLowerCase();
if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
return `The island does not know “${message.text}”. Try: look.`;
},
};
// The page: one element that holds the whole view.
const page = document.createElement('main');
page.textContent = 'Connecting…';
document.body.append(page);
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: island } });
page.textContent = '';
header(page, world);
islandMap(page, world);
conversation(page, world);
// The name of the world, what it is about and what is happening now.
function header(container, world) {
const title = document.createElement('h1');
const about = document.createElement('p');
const now = document.createElement('p');
container.append(title, about, now);
// Called at once, then after every change of the world.
return world.subscribe((node) => {
title.textContent = node.name;
about.textContent = node.profile.description ?? '';
now.textContent = `Now: ${node.now?.text ?? ''} The world is ${node.status}.`;
});
}
// The island from the data of the world: one square per cell, you on yours, and the tide.
function islandMap(container, world) {
const grid = document.createElement('div');
grid.setAttribute('role', 'img');
grid.setAttribute('aria-label', 'Map of the island');
grid.style.cssText = 'display: grid; gap: 2px';
const tide = document.createElement('p');
const meter = document.createElement('meter');
meter.min = 0;
meter.max = 100;
const level = document.createElement('span');
tide.append('Tide ', meter, level);
container.append(grid, tide);
return world.subscribe((node) => {
const { map, position } = node.data;
// A name of `data` can be missing for a moment while the world sends it.
if (!map || !position) {
grid.textContent = 'The map is on its way…';
return;
}
grid.style.gridTemplateColumns = `repeat(${map[0].length}, 44px)`;
const cells = [];
map.forEach((row, rowIndex) => {
row.forEach((ground, columnIndex) => {
const isHere = rowIndex === position.row && columnIndex === position.column;
const cell = document.createElement('div');
cell.style.cssText = 'height: 44px; display: grid; place-items: center; font-size: 24px; border-radius: 6px';
cell.style.background = isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)';
cell.textContent = isHere ? '🧍' : ground;
cells.push(cell);
});
});
grid.replaceChildren(...cells);
meter.value = node.data.tide;
level.textContent = ` ${node.data.tide}%`;
});
}
// The conversation with the world, oldest first, and a box to write to it.
function conversation(container, world) {
const heading = document.createElement('h2');
heading.textContent = 'Messages';
const empty = document.createElement('p');
empty.textContent = 'No messages yet. Write “look” to the world.';
const list = document.createElement('ul');
list.style.cssText = 'list-style: none; padding: 0';
const form = document.createElement('form');
form.style.cssText = 'display: flex; gap: 8px';
const input = document.createElement('input');
input.placeholder = 'Write to the world';
input.setAttribute('aria-label', 'Write to the world');
input.style.flex = '1';
const send = document.createElement('button');
send.textContent = 'Send';
form.append(input, send);
container.append(heading, empty, list, form);
form.onsubmit = (event) => {
event.preventDefault();
if (!input.value.trim()) return;
// Sends as the person. The world reads it and answers with a message.
world.send(input.value);
input.value = '';
};
let shown = '';
return world.subscribe((node) => {
// canSend: the rules of the world let the person send now.
send.disabled = !node.canSend;
empty.hidden = node.messages.length > 0;
// Draw the list again only when the messages changed, not at every change of the data.
const key = JSON.stringify(node.messages.map((message) => message.id));
if (key === shown) return;
shown = key;
list.replaceChildren(...node.messages.map(messageItem));
});
}
// One message: who said it and what. The person's own are on the right.
function messageItem(message) {
const item = document.createElement('li');
item.style.margin = '6px 0';
item.style.textAlign = message.fromMe ? 'right' : 'left';
const bubble = document.createElement('span');
bubble.style.cssText = 'display: inline-block; padding: 6px 10px; border-radius: 10px; background: rgba(127, 127, 127, 0.15)';
bubble.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
item.append(bubble);
return item;
}Next steps
The person can talk with the world but cannot walk on the island yet. Step 4: Make a move adds buttons that send moves and shows whether each one was delivered.
Messages and questions covers the rendering of every kind of message including images and files. The reference of send lists the values it accepts besides text.