Handle errors and finish
A finished view tells the person what happened when a page is opened outside the webapp or when the webapp fails to run a call made on behalf of the person. The view now handles both errors and gets a two-column layout for wide screens.
Outside the webapp
In a browser tab of its own the page has no webapp around it and connectToHost() rejects with the code 'no-host'. The view then replaces the error message with a short text that says what the page is and where to open it:
if (error?.code === 'no-host') return <OutsideTheWebapp />;
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting to the island…</p>;OutsideTheWebapp renders the name of the world, one sentence and a link to UNaIVERSE. The other code of connectToHost, 'unsupported', concerns the developer and is described in its Troubleshooting.
In plain JavaScript a try/catch wraps the connection and the view is built only after connectToHost resolves:
let world = null;
try {
world = await connectToHost({ fake: { world: island }, webapp: PHONE });
} catch (error) {
if (error.code === 'no-host') outsideTheWebapp(page);
else page.textContent = `Could not connect (${error.code}).`;
}
if (world) {
// ...build the view, as before
}One place for the errors
The webapp runs every call made by the view on behalf of the person (a move, a message, an answer, a retry or an action of the rules) and can fail to run it. In that case the Promise rejects with an error whose code gives the reason, for example 'failed' for an error inside the webapp. To handle these errors in one place the view passes every call through a single function run that catches the error and shows its reason as a sentence:
async function run(action) {
setProblem(null);
try {
await action();
} catch (failure) {
setProblem(explain(failure.code));
}
}<button onClick={() => run(() => world.send(move.direction))}>{move.label}</button>explain maps each known code to a sentence for the person. A code that it does not know (for example one added by a later version of the kit) is shown as it is. In React App passes run down as a prop to the components that make calls while the plain JavaScript version defines run once at the top level of the file. Both versions show the error in a single notice above the view.
A fake world never produces these errors and the notice stays hidden in the example. Errors and the person's controls shows how to trigger one for testing.
The final layout
The view places the island on the left of the conversation on a wide screen and above it on a phone. One CSS grid declaration handles both cases:
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))'Each column is a card with rounded corners on a translucent grey background (rgba(127, 127, 127, 0.08)).
The code
The new lines are highlighted. The code below is the complete view.
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 = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
// How each move changes the row and the column.
const STEPS = { north: [-1, 0], south: [1, 0], east: [0, 1], west: [0, -1] };
// Where the chest and the treasure are.
const CHEST = { row: 2, column: 2 };
const TREASURE = { row: 1, column: 2 };
// What changes in the fake world. The view reads it through `data`.
let position = { row: 3, column: 1 };
let coins = 0;
let isChestOpen = false;
let isTreasureFound = false;
// Moves you one square, unless there is water.
function walk(direction) {
const [down, right] = STEPS[direction];
const next = { row: position.row + down, column: position.column + right };
const ground = MAP[next.row]?.[next.column];
if (!ground || ground === '🌊') return `Water! You cannot go ${direction}.`;
position = next;
if (next.row === CHEST.row && next.column === CHEST.column && !isChestOpen) {
// A question: the view shows its form, and the answer comes back to onMessage.
return {
text: 'You find an old chest with a rusty lock. Three keys hang next to it.',
form: { fields: [{ name: 'key', label: 'Key', type: 'select', options: ['gold', 'silver', 'iron'] }] },
};
}
return `You walk ${direction}.`;
}
// Tries a key on the chest.
function openChest(key) {
if (key !== 'iron') return `The ${key} key does not turn. Step away and come back to try again.`;
isChestOpen = true;
coins += 10;
return 'The iron key turns. Inside: 10 coins!';
}
// Digs where you stand.
function dig() {
const isHere = position.row === TREASURE.row && position.column === TREASURE.column;
if (!isHere || isTreasureFound) return 'You dig, but find only sand.';
isTreasureFound = true;
coins += 50;
return 'You dig… and hit a wooden box. The treasure: 50 coins!';
}
const island = {
name: 'Treasure Island',
profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
now: {
text: 'The hunt is on.',
// The actions the rules offer the person now.
actions: [
{ name: 'dig', text: 'Dig here' },
{ name: 'hint', text: 'Ask for a hint' },
],
},
// What the world shows, by name.
data: {
map: MAP,
// Where you are on the map, given by a function that lets the view see each move.
position: { every: 200, value: () => position },
// 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)),
coins: { every: 200, value: () => coins },
found: { every: 200, value: () => isTreasureFound },
},
// Who is in the world, with their roles. The person is an explorer.
members: [
{ name: 'Pete', role: 'guide', isMaster: true },
{ name: 'Mia', role: 'explorer' },
],
roles: [
{ name: 'explorer', description: 'Walks the island and digs for the treasure.' },
{ name: 'guide', description: 'Knows the island and gives hints.' },
],
myRole: 'explorer',
// The world reads what the person writes and answers.
onMessage: (message) => {
// The answer to the question at the chest, with its values by field name.
if (message.values) return openChest(message.values.key);
const word = message.text.trim().toLowerCase();
if (STEPS[word]) return walk(word);
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: north, south, east, west or look.`;
},
// An action of the rules: the person chose one of `now.actions`.
onAction: (name) => {
if (name === 'hint') return 'An old map says: dig one step north of the chest.';
return dig();
},
};
// While building, pretend to be on a phone whose home bar covers 34 pixels at the bottom.
const PHONE = { insets: { top: 0, right: 0, bottom: 34, left: 0 } };
// The two themes of the webapp. The view takes the colors of the one the webapp shows.
const COLORS = {
light: { page: '#fbf6ec', text: '#1d2b36' },
dark: { page: '#13212b', text: '#e6eef3' },
};
// A notice above the view, and a card around each column.
const NOTICE = { padding: '8px 12px', borderRadius: 8, background: 'rgba(255, 170, 0, 0.25)' };
const CARD = { padding: 16, borderRadius: 12, background: 'rgba(127, 127, 127, 0.08)' };
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: island }, webapp: PHONE });
// Why the last thing the view did for the person did not work, or null.
const [problem, setProblem] = useState(null);
// A page opened alone, outside the webapp, has no world. Say where the view works.
if (error?.code === 'no-host') return <OutsideTheWebapp />;
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting to the island…</p>;
// Does something for the person (send, act, answer, retry) and explains the error if it fails.
async function run(action) {
setProblem(null);
try {
await action();
} catch (failure) {
setProblem(explain(failure.code));
}
}
// What the webapp says about itself: its theme and the parts of the screen to keep clear.
const { theme, insets, keyboard } = world.webapp;
const colors = COLORS[theme];
return (
<main
style={{
// The whole page, in the colors of the webapp. It scrolls inside.
position: 'fixed',
inset: 0,
overflowY: 'auto',
colorScheme: theme,
background: colors.page,
color: colors.text,
// Away from the notch and the home bar, with room for the keyboard while it is open.
paddingTop: insets.top + 16,
paddingRight: insets.right + 16,
paddingBottom: Math.max(insets.bottom, keyboard) + 16,
paddingLeft: insets.left + 16,
}}
>
<Header world={world} />
{problem && (
<p role="alert" style={NOTICE}>
{problem}
</p>
)}
{/* Two columns side by side when there is room, one under the other on a phone. */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16, alignItems: 'start' }}>
<div style={CARD}>
<IslandMap data={world.data} />
<Moves world={world} run={run} />
<Actions world={world} run={run} />
</div>
<div style={CARD}>
<Conversation world={world} run={run} />
<People world={world} />
</div>
</div>
</main>
);
}
// What to tell the person, by error code, when the webapp could not do an action.
function explain(code) {
// 'failed': something went wrong in the webapp, for example an answer to a message that is gone.
if (code === 'failed') return 'That did not work. Try again in a moment.';
// Any other code, including one that a later kit adds, is shown as it is.
return `That did not work (${code}).`;
}
// Shown when the page is opened alone, outside the UNaIVERSE webapp.
function OutsideTheWebapp() {
return (
<main>
<h1>Treasure Island</h1>
<p>This page is the view of a world of UNaIVERSE. Open the world in UNaIVERSE to play.</p>
<a href="https://unaiverse.io">Go to UNaIVERSE</a>
</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>
<p>
Coins: {world.data.coins ?? 0}
{world.data.found && ' · 🏆 Treasure found!'}
</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 four moves, placed like a compass. Each one is a message to the world, like the ones you write.
function Moves({ world, run }) {
const moves = [
{ direction: 'north', label: '↑ North', row: 1, column: 2 },
{ direction: 'west', label: '← West', row: 2, column: 1 },
{ direction: 'east', label: '→ East', row: 2, column: 3 },
{ direction: 'south', label: '↓ South', row: 3, column: 2 },
];
return (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 84px)', gap: 4, margin: '12px 0' }}>
{moves.map((move) => (
<button
key={move.direction}
style={{ gridRow: move.row, gridColumn: move.column }}
disabled={!world.canSend}
onClick={() => run(() => world.send(move.direction))}
>
{move.label}
</button>
))}
</div>
);
}
// The actions the rules offer the person now: one button each.
function Actions({ world, run }) {
const [note, setNote] = useState(null);
async function choose(action) {
// Asks the rules to do it for the person: 'requested', 'refused' or 'not-allowed'.
const result = await world.act(action.name);
setNote(result === 'requested' ? null : `The rules did not take “${action.text || action.name}” now.`);
}
// Only the actions the person may choose (the others run on their own).
const offered = (world.now?.actions ?? []).filter((action) => action.canChoose !== false);
return (
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', margin: '12px 0' }}>
{offered.map((action) => (
<button key={action.name} disabled={action.isRequested} onClick={() => run(() => choose(action))}>
{action.text || action.name}
</button>
))}
{note && <small>{note}</small>}
</div>
);
}
// The conversation with the world, oldest first, and a box to write to it.
function Conversation({ world, run }) {
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.
run(() => 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} run={run} />
))}
</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, run }) {
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>
{message.fromMe && <Delivery message={message} run={run} />}
{/* A question: its form until the person answers, then a note. */}
{message.form && !message.fromMe && !message.isAnswered && <QuestionForm message={message} run={run} />}
{message.form && message.isAnswered && <small> · answered</small>}
</li>
);
}
// The delivery of one of the person's messages: on its way, sent, or failed.
function Delivery({ message, run }) {
if (message.status === 'sending') return <small> · sending…</small>;
if (message.status === 'failed') {
return (
<small>
{' '}
· not delivered <button onClick={() => run(() => message.retry())}>Retry</button>
</small>
);
}
return <small> · sent ✓</small>;
}
// A question from the world: one field for each field of its form, and a button to answer.
function QuestionForm({ message, run }) {
const fields = message.form.fields;
// A choice starts on its first option, and a text or a number starts empty.
const [values, setValues] = useState(() =>
Object.fromEntries(fields.map((field) => [field.name, field.options ? optionValue(field.options[0]) : ''])),
);
function handleSubmit(event) {
event.preventDefault();
// The answer goes to the world, which finds it in `message.values`.
run(() => message.answer(values));
}
return (
<form onSubmit={handleSubmit} style={{ display: 'flex', gap: 8, flexWrap: 'wrap', margin: '6px 0' }}>
{fields.map((field) => (
<label key={field.name}>
{field.label || field.name}{' '}
{field.type === 'select' ? (
<select
value={values[field.name]}
onChange={(event) => setValues({ ...values, [field.name]: event.target.value })}
>
{field.options.map((option) => (
<option key={optionValue(option)} value={optionValue(option)}>
{optionLabel(option)}
</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>
);
}
// An option of a form is a plain string, or `{ value, label }`.
function optionValue(option) {
return typeof option === 'string' ? option : option.value;
}
function optionLabel(option) {
return typeof option === 'string' ? option : option.label;
}
// Who is in the world, their roles and the person's own role.
function People({ world }) {
const myRole = world.roles?.find((role) => role.name === world.myRole);
return (
<section>
<h2>People</h2>
<p>
Your role: {world.myRole ?? 'none'}
{myRole?.description && ` — ${myRole.description}`}
</p>
<ul>
{(world.members ?? []).map((member) => (
<li key={member.id}>
{member.status === 'online' ? '🟢' : '⚪'} {member.name} · {member.role}
{member.isMaster && ' · master'}
</li>
))}
</ul>
</section>
);
}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 = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
// How each move changes the row and the column.
const STEPS = { north: [-1, 0], south: [1, 0], east: [0, 1], west: [0, -1] };
// Where the chest and the treasure are.
const CHEST = { row: 2, column: 2 };
const TREASURE = { row: 1, column: 2 };
// What changes in the fake world. The view reads it through `data`.
let position = { row: 3, column: 1 };
let coins = 0;
let isChestOpen = false;
let isTreasureFound = false;
// Moves you one square, unless there is water.
function walk(direction) {
const [down, right] = STEPS[direction];
const next = { row: position.row + down, column: position.column + right };
const ground = MAP[next.row]?.[next.column];
if (!ground || ground === '🌊') return `Water! You cannot go ${direction}.`;
position = next;
if (next.row === CHEST.row && next.column === CHEST.column && !isChestOpen) {
// A question: the view shows its form, and the answer comes back to onMessage.
return {
text: 'You find an old chest with a rusty lock. Three keys hang next to it.',
form: { fields: [{ name: 'key', label: 'Key', type: 'select', options: ['gold', 'silver', 'iron'] }] },
};
}
return `You walk ${direction}.`;
}
// Tries a key on the chest.
function openChest(key) {
if (key !== 'iron') return `The ${key} key does not turn. Step away and come back to try again.`;
isChestOpen = true;
coins += 10;
return 'The iron key turns. Inside: 10 coins!';
}
// Digs where you stand.
function dig() {
const isHere = position.row === TREASURE.row && position.column === TREASURE.column;
if (!isHere || isTreasureFound) return 'You dig, but find only sand.';
isTreasureFound = true;
coins += 50;
return 'You dig… and hit a wooden box. The treasure: 50 coins!';
}
const island = {
name: 'Treasure Island',
profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
now: {
text: 'The hunt is on.',
// The actions the rules offer the person now.
actions: [
{ name: 'dig', text: 'Dig here' },
{ name: 'hint', text: 'Ask for a hint' },
],
},
// What the world shows, by name.
data: {
map: MAP,
// Where you are on the map, given by a function that lets the view see each move.
position: { every: 200, value: () => position },
// 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)),
coins: { every: 200, value: () => coins },
found: { every: 200, value: () => isTreasureFound },
},
// Who is in the world, with their roles. The person is an explorer.
members: [
{ name: 'Pete', role: 'guide', isMaster: true },
{ name: 'Mia', role: 'explorer' },
],
roles: [
{ name: 'explorer', description: 'Walks the island and digs for the treasure.' },
{ name: 'guide', description: 'Knows the island and gives hints.' },
],
myRole: 'explorer',
// The world reads what the person writes and answers.
onMessage: (message) => {
// The answer to the question at the chest, with its values by field name.
if (message.values) return openChest(message.values.key);
const word = message.text.trim().toLowerCase();
if (STEPS[word]) return walk(word);
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: north, south, east, west or look.`;
},
// An action of the rules: the person chose one of `now.actions`.
onAction: (name) => {
if (name === 'hint') return 'An old map says: dig one step north of the chest.';
return dig();
},
};
// While building, pretend to be on a phone whose home bar covers 34 pixels at the bottom.
const PHONE = { insets: { top: 0, right: 0, bottom: 34, left: 0 } };
// The two themes of the webapp. The view takes the colors of the one the webapp shows.
const COLORS = {
light: { page: '#fbf6ec', text: '#1d2b36' },
dark: { page: '#13212b', text: '#e6eef3' },
};
// A notice above the view, and a card around each column.
const NOTICE = 'padding: 8px 12px; border-radius: 8px; background: rgba(255, 170, 0, 0.25)';
const CARD = 'padding: 16px; border-radius: 12px; background: rgba(127, 127, 127, 0.08)';
// The page: one element that holds the whole view.
const page = document.createElement('main');
page.textContent = 'Connecting to the island…';
document.body.append(page);
// Why the last thing the view did for the person did not work.
const problem = document.createElement('p');
problem.setAttribute('role', 'alert');
problem.style.cssText = NOTICE;
problem.hidden = true;
let world = null;
try {
// While building: the fake world. In the webapp: world = await connectToHost();
world = await connectToHost({ fake: { world: island }, webapp: PHONE });
} catch (error) {
// A page opened alone, outside the webapp, has no world. Say where the view works.
if (error.code === 'no-host') outsideTheWebapp(page);
else page.textContent = `Could not connect (${error.code}).`;
}
if (world) {
page.textContent = '';
lookAndScreen(page, world);
header(page, world);
page.append(problem);
// Two columns side by side when there is room, one under the other on a phone.
const columns = document.createElement('div');
columns.style.cssText = 'display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; align-items: start';
const left = document.createElement('div');
const right = document.createElement('div');
left.style.cssText = CARD;
right.style.cssText = CARD;
columns.append(left, right);
page.append(columns);
islandMap(left, world);
moves(left, world);
actions(left, world);
conversation(right, world);
people(right, world);
}
// Does something for the person (send, act, answer, retry) and explains the error if it fails.
async function run(action) {
problem.hidden = true;
try {
await action();
} catch (failure) {
problem.textContent = explain(failure.code);
problem.hidden = false;
}
}
// What to tell the person, by error code, when the webapp could not do an action.
function explain(code) {
// 'failed': something went wrong in the webapp, for example an answer to a message that is gone.
if (code === 'failed') return 'That did not work. Try again in a moment.';
// Any other code, including one that a later kit adds, is shown as it is.
return `That did not work (${code}).`;
}
// Shown when the page is opened alone, outside the UNaIVERSE webapp.
function outsideTheWebapp(page) {
const title = document.createElement('h1');
title.textContent = 'Treasure Island';
const text = document.createElement('p');
text.textContent = 'This page is the view of a world of UNaIVERSE. Open the world in UNaIVERSE to play.';
const link = document.createElement('a');
link.href = 'https://unaiverse.io';
link.textContent = 'Go to UNaIVERSE';
page.replaceChildren(title, text, link);
}
// The page follows what the webapp says about itself: its theme and the parts of the screen to keep clear.
function lookAndScreen(page, world) {
// The whole page, in the colors of the webapp. It scrolls inside.
page.style.cssText = 'position: fixed; inset: 0; overflow-y: auto';
return world.subscribe((node) => {
const { theme, insets, keyboard } = node.webapp;
const colors = COLORS[theme];
page.style.colorScheme = theme;
page.style.background = colors.page;
page.style.color = colors.text;
// Away from the notch and the home bar, with room for the keyboard while it is open.
page.style.paddingTop = `${insets.top + 16}px`;
page.style.paddingRight = `${insets.right + 16}px`;
page.style.paddingBottom = `${Math.max(insets.bottom, keyboard) + 16}px`;
page.style.paddingLeft = `${insets.left + 16}px`;
});
}
// 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');
const coins = document.createElement('p');
container.append(title, about, now, coins);
// 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}.`;
coins.textContent = `Coins: ${node.data.coins ?? 0}${node.data.found ? ' · 🏆 Treasure found!' : ''}`;
});
}
// 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 four moves, placed like a compass. Each one is a message to the world, like the ones you write.
function moves(container, world) {
const moves = [
{ direction: 'north', label: '↑ North', row: 1, column: 2 },
{ direction: 'west', label: '← West', row: 2, column: 1 },
{ direction: 'east', label: '→ East', row: 2, column: 3 },
{ direction: 'south', label: '↓ South', row: 3, column: 2 },
];
const compass = document.createElement('div');
compass.style.cssText = 'display: grid; grid-template-columns: repeat(3, 84px); gap: 4px; margin: 12px 0';
const buttons = moves.map((move) => {
const button = document.createElement('button');
button.textContent = move.label;
button.style.gridRow = move.row;
button.style.gridColumn = move.column;
button.onclick = () => run(() => world.send(move.direction));
return button;
});
compass.append(...buttons);
container.append(compass);
return world.subscribe((node) => {
for (const button of buttons) button.disabled = !node.canSend;
});
}
// The actions the rules offer the person now: one button each.
function actions(container, world) {
const row = document.createElement('div');
row.style.cssText = 'display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 12px 0';
const note = document.createElement('small');
container.append(row);
async function choose(action) {
// Asks the rules to do it for the person: 'requested', 'refused' or 'not-allowed'.
const result = await world.act(action.name);
note.textContent = result === 'requested' ? '' : `The rules did not take “${action.text || action.name}” now.`;
}
let shown = '';
return world.subscribe((node) => {
// Only the actions the person may choose (the others run on their own).
const offered = (node.now?.actions ?? []).filter((action) => action.canChoose !== false);
// Draw the buttons again only when the actions changed.
const key = JSON.stringify(offered.map((action) => [action.name, action.text, action.isRequested]));
if (key === shown) return;
shown = key;
const buttons = offered.map((action) => {
const button = document.createElement('button');
button.textContent = action.text || action.name;
button.disabled = action.isRequested;
button.onclick = () => run(() => choose(action));
return button;
});
row.replaceChildren(...buttons, note);
});
}
// 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.
run(() => 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, message.status, message.isAnswered]));
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);
if (message.fromMe) item.append(delivery(message));
// A question: its form until the person answers, then a note.
if (message.form && !message.fromMe && !message.isAnswered) item.append(questionForm(message));
if (message.form && message.isAnswered) item.append(' · answered');
return item;
}
// The delivery of one of the person's messages: on its way, sent, or failed.
function delivery(message) {
const note = document.createElement('small');
if (message.status === 'sending') {
note.textContent = ' · sending…';
} else if (message.status === 'failed') {
const retry = document.createElement('button');
retry.textContent = 'Retry';
retry.onclick = () => run(() => message.retry());
note.append(' · not delivered ', retry);
} else {
note.textContent = ' · sent ✓';
}
return note;
}
// A question from the world: one field for each field of its form, and a button to answer.
function questionForm(message) {
const form = document.createElement('form');
form.style.cssText = 'display: flex; gap: 8px; flex-wrap: wrap; margin: 6px 0';
const inputs = {};
for (const field of message.form.fields) {
const label = document.createElement('label');
label.append(`${field.label || field.name} `);
let input;
if (field.type === 'select') {
// A choice starts on its first option.
input = document.createElement('select');
for (const option of field.options) {
const choice = document.createElement('option');
choice.value = optionValue(option);
choice.textContent = optionLabel(option);
input.append(choice);
}
} else {
input = document.createElement('input');
input.type = field.type === 'number' ? 'number' : 'text';
}
label.append(input);
form.append(label);
inputs[field.name] = input;
}
const answer = document.createElement('button');
answer.textContent = 'Answer';
form.append(answer);
form.onsubmit = (event) => {
event.preventDefault();
const values = {};
for (const [name, input] of Object.entries(inputs)) values[name] = input.value;
// The answer goes to the world, which finds it in `message.values`.
run(() => message.answer(values));
};
return form;
}
// An option of a form is a plain string, or `{ value, label }`.
function optionValue(option) {
return typeof option === 'string' ? option : option.value;
}
function optionLabel(option) {
return typeof option === 'string' ? option : option.label;
}
// Who is in the world, their roles and the person's own role.
function people(container, world) {
const heading = document.createElement('h2');
heading.textContent = 'People';
const mine = document.createElement('p');
const list = document.createElement('ul');
container.append(heading, mine, list);
return world.subscribe((node) => {
const myRole = node.roles?.find((role) => role.name === node.myRole);
mine.textContent = `Your role: ${node.myRole ?? 'none'}${myRole?.description ? ` — ${myRole.description}` : ''}`;
const items = (node.members ?? []).map((member) => {
const item = document.createElement('li');
item.textContent = `${member.status === 'online' ? '🟢' : '⚪'} ${member.name} · ${member.role}${member.isMaster ? ' · master' : ''}`;
return item;
});
list.replaceChildren(...items);
});
}What you built
The complete view connects to the world and draws its data. It shows the conversation, sends moves with their delivery status, answers questions and offers the actions of the rules. The view also lists the people, follows the theme of the webapp, keeps clear of the safe areas and the keyboard of a phone and explains its errors to the person.
To run it in the webapp, remove the fake world by calling useWorld() or connectToHost() without arguments. Then publish the view on your own server and enter its address in the settings of your world as described in Going live.
Next steps
- Tutorial: a turn-based game: a game for two with turns, a winner, a menu and links.
- Errors and the person's controls: every error code and how to handle it.
- Layout and style inside the webapp: how to fit the view in its iframe.