Fake worlds
A fake world runs inside your page with no account, no webapp and no network. It lets you build and test your view before you publish it in UNaIVERSE. You describe it in a plain object passed to connectToHost:
const arena = {
name: 'Arena',
owner: 'acme',
profile: { description: 'A board game for two', place: 'Rome' },
data: { board: [[0, 1], [1, 0]], clock: (time) => Math.floor(time / 1000) % 60 },
now: { text: 'Your move', actions: [{ name: 'pass', text: 'Pass your turn' }] },
members: [{ name: 'Bob', role: 'player', data: { score: 2 } }],
roles: [{ name: 'player', description: 'Moves a piece each turn' }],
myRole: 'player',
onMessage: (message) => `You said ${message.text}`,
onAction: (name) => `You chose ${name}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });The call resolves to a world with the same fields and methods as in the webapp. Removing fake switches to the real world.
FakeNode
A FakeNode passed as fake.agent describes a fake agent and a FakeWorld accepts all its fields as well. Only name is required.
name
string. The kit uses it as the name of the world and as the second part of its address.
{ name: 'Arena' }owner
string, optional ('demo' by default). It becomes the owner of the world in profile.owner and the first part of the address ('acme/Arena').
{ name: 'Arena', owner: 'acme' } // world.address is 'acme/Arena'profile
{ description?: string; place?: string; isVerified?: boolean }, optional. Its fields fill the profile of the world and the since of that profile is always 1 January 2026.
{ name: 'Arena', profile: { description: 'A board game', place: 'Rome', isVerified: true } }data
Record<string, unknown | ((time) => unknown) | { every?: number; value: (time) => unknown }>, optional. Each key becomes a name in the data of the world with a value in one of three forms:
| You write | The world shows |
|---|---|
A value: score: 3 | That value for the whole life of the world. |
A function of time: clock: (time) => ... | A new value every second. The function gets the time (Unix milliseconds) and returns the value. |
{ every: 200, value: (time) => ... } | A new value every every milliseconds. |
data: {
board: [[0, 1], [1, 0]], // a grid: an array of rows
visitors: (time) => 10 + (Math.floor(time / 1000) % 5),
camera: { every: 100, value: () => canvas.toDataURL('image/jpeg') },
}- The values of a fake world are in
datawhenconnectToHostresolves (those of a fake agent once it is'online'). The functions run on their timers for the whole life of the page. - To make the world react to the person return one of your variables from a function with a short
every(data: { board: { every: 200, value: () => board } }).onMessageoronActionthen changeboard. - A function can be called more often than its timer (for example at the start). Its value must depend on the time or on your variables and never on the number of calls.
- An array of one item arrives as that item as happens with the numbers sent by a real world (
[5]becomes5and[[1, 2]]becomes[1, 2]). Give a grid at least two rows or wrap a single value in an object. dataHistoryreturns the last 200 values of each name.onDatagets every new value even when it equals the previous one.
now
{ text?: string; next?: string[]; actions?: Array<{ name: string; text?: string; to?: string }> }, optional. It describes the current moment of the rules and becomes the now of the world.
now: {
text: 'Voting is open',
next: ['counting'],
actions: [{ name: 'vote', text: 'Vote now', to: 'counting' }, { name: 'pass' }],
}- It is fixed for the whole life of the fake world. Neither messages nor actions change it. Put what changes (whose turn it is, a score) in
data. now.nextis yournextfollowed by thetoof each action. Because an action with notoleads to its ownname, the example above gives['counting', 'pass'].- Each action has
canChoose: true,isRequested: falseand emptyargs. Itstextis the label of the button. - Without
nowa fake world has anowwith no text, an emptynextand no actions. A fake agent hasnow: nullinstead.
onMessage
(message, node, sender) => FakeAnswer | null | undefined, optional and possibly async. About 200 milliseconds after each message of the person (answers to questions included) the kit calls it and delivers the returned FakeAnswer as the answer of the world:
| It returns | The person gets |
|---|---|
'Hi' | Text. |
{ text, images, files, media, charts } | A message with text, images, files, videos and charts (FakeAnswer says what a world keeps of it). |
{ text, form } | A question with a form (FormSpec). |
{ from: 'Otto', text } | In a fake world, an answer written by its member Otto. |
null, undefined or '' | No answer. |
The callback receives three arguments:
| Argument | What it is |
|---|---|
message | The message of the person as the world receives it. This GuiMessage has text, image, files, from ('You') and time. files is an empty array or holds the file of the person as [{ name, type, url }] with its original name. An answer to a question also has values. Its fromMe is false because the world is the receiver. |
node | The fake world as { name, address }. |
sender | The person as { name: 'You', address: 'you/You' }. |
onMessage: (message) => {
if (message.files.length > 0) return `Got ${message.files[0].name}`;
if (message.values) return `You chose ${message.values.direction}`;
return { text: 'Which way?', form: { fields: [{ name: 'direction', type: 'select', options: ['left', 'right'] }] } };
},Two rules decide what the person receives:
- What arrives depends on who answers. The answer of a world is a note of its rules without images and files. The answer of a member (with
from) or of an agent keeps everything (FakeAnswer). - A form that breaks the rules of a form arrives as plain text with no
form. A fake world is therefore a quick place to check your forms before a real one shows them.
failNext
boolean, optional. When it is true send resolves 'failed' for the next message of the person and leaves that message with status: 'failed'. The kit then resets it to false and a retry of that message goes through.
const arena = { name: 'Arena', failNext: true, onMessage: () => 'Got it' };
const world = await connectToHost({ fake: { world: arena } });
// Later, to fail the next message again:
arena.failNext = true;onAction
(name, args, sender) => FakeAnswer | null | undefined, optional and possibly async. When the person chooses one of now.actions with act, the kit calls it about 200 milliseconds after act resolved 'requested'. Like onMessage it returns a FakeAnswer.
| Argument | What it is |
|---|---|
name | The name of the action. |
args | The args given to act ({} when there were none). |
sender | The person as { name: 'You', address: 'you/You' }. |
now: { actions: [{ name: 'roll', text: 'Roll the die' }] },
onAction: (name) => {
lastRoll = 1 + Math.floor(Math.random() * 6);
return `You rolled ${lastRoll}`;
},act resolves 'not-allowed' for an action missing from now.actions and does not call onAction.
me
Partial<GuiMe>, optional. The kit reads it only on the world or agent passed to fake (never on its members). It describes the person using your view in the form the webapp would provide. It becomes the me of the world and the value identity() resolves to. Give it the nickname and any fields of a GuiMe you want to try among name, surname, title, organization, city and country.
const club = { name: 'Book club', me: { nickname: 'ada', city: 'Siena' } };- The nickname defaults to
'you'even whenmeis missing altogether. - As in the webapp, only the
GuiMefields that hold text are kept. Anything else inme(an email, for example) never reaches your view.
FakeWorld
A FakeWorld is a FakeNode with members and roles that you pass as fake.world.
members
Array<FakeNode & { role?: string; isMaster?: boolean }>, optional. The kit turns each item into one of the members of the world.
members: [
{ name: 'Bob', role: 'player', data: { score: 2 } },
{ name: 'Referee', isMaster: true },
],Each member is an 'online' agent with its role ('member' by default), its isMaster and its own data. That data works like the data of the world and supports timers too. The kit never calls the onMessage of a member because the messages of the person go to the world. A member speaks when the onMessage or onAction of the world returns an answer whose from is the name of the member.
roles
Array<{ name: string; description?: string }>, optional. Each item becomes one of the roles of the world with a diagram that holds only its name and its description.
roles: [{ name: 'player', description: 'Moves a piece each turn' }, { name: 'watcher' }],myRole
string, optional. The person plays this role in the world and your view reads it in myRole ('member' by default).
myRole: 'player',showsSenders
boolean, optional. With false the world asks views to hide who wrote each message and its showsSenders is false. Leave it out (or write true) for a world that shows them. Nothing else changes because from and fromId are still there and your view decides what to render.
const masks = { name: 'Masks', showsSenders: false, members: [{ name: 'Otto' }] };FakeAnswer
onMessage and onAction return a string or an object with any of these fields:
| Field | What it is |
|---|---|
text | The text of the message. |
image, images | Images as URLs or data URIs (an inline SVG is the easiest to write). image comes before the items of images. |
files | Files as { name, type, url } with a data URI in url. Only the url is sent. Like the files of a real agent, the file arrives with name: null and a type read from the url. |
media | Videos, audio, PDFs and links as { url, type, title?, poster?, alt? } (GuiMedia). url and poster are https: only and a missing alt defaults to the title or to the type. |
charts | Charts as { kind, series, alt } (GuiChart). A missing alt defaults to the kind. |
form | The FormSpec of a question. |
from | The name of the member (from members) that writes the answer. Only a fake world uses it. |
onMessage: () => ({
text: 'Your week',
charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
}),Each kind of sender produces a different message:
| Who answers | It arrives as | With |
|---|---|---|
| A fake world | a note of its rules with isSystem: true, the name of the world in from and its id in fromId | text, media, charts and a form with no images or files (like the notes of a real world) |
A fake world with from: 'Otto' | the message of Otto with isSystem: false, from: 'Otto' and the id of Otto in fromId | everything |
| A fake agent | the message of the agent with isSystem: false and the id of the agent in fromId | everything |
In this example the world and its member Otto give the same answer (an image with text). The note of the world arrives without the image and the message of Otto arrives with it.
import { useWorld } from './useWorld.js';
// A small picture, as an inline SVG.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><circle cx="20" cy="20" r="18" fill="orange"/></svg>')}`;
// A fake world with one member. The world and Otto give the same answer.
const arena = {
name: 'Arena',
members: [{ name: 'Otto', role: 'player' }],
onMessage: (message) => {
const answer = { text: 'Here is a picture', images: [PICTURE] };
// With `from`, a member says it, as a plain message with its pictures.
// Without `from`, the world says it, as a note of its rules with no pictures.
return message.text === 'Ask Otto' ? { ...answer, from: 'Otto' } : answer;
},
};
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>;
// For each answer, show who said it, whether it is a note and how many pictures it has.
const answers = world.messages.filter((message) => !message.fromMe);
return (
<>
<button onClick={() => world.send('Ask the world')}>Ask the world</button>
<button onClick={() => world.send('Ask Otto')}>Ask Otto</button>
<ul>
{answers.map((message) => (
<li key={message.id}>
{message.from}{message.isSystem ? ' (note)' : ''}: {message.text} · pictures: {(message.images ?? []).length}
</li>
))}
</ul>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A small picture, as an inline SVG.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><circle cx="20" cy="20" r="18" fill="orange"/></svg>')}`;
// A fake world with one member. The world and Otto give the same answer.
const arena = {
name: 'Arena',
members: [{ name: 'Otto', role: 'player' }],
onMessage: (message) => {
const answer = { text: 'Here is a picture', images: [PICTURE] };
// With `from`, a member says it, as a plain message with its pictures.
// Without `from`, the world says it, as a note of its rules with no pictures.
return message.text === 'Ask Otto' ? { ...answer, from: 'Otto' } : answer;
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const askWorld = document.createElement('button');
askWorld.textContent = 'Ask the world';
askWorld.onclick = () => world.send('Ask the world');
const askOtto = document.createElement('button');
askOtto.textContent = 'Ask Otto';
askOtto.onclick = () => world.send('Ask Otto');
const list = document.createElement('ul');
document.body.append(askWorld, askOtto, list);
// For each answer, show who said it, whether it is a note and how many pictures it has.
world.subscribe((node) => {
const answers = node.messages.filter((message) => !message.fromMe);
list.replaceChildren(...answers.map((message) => {
const item = document.createElement('li');
const kind = message.isSystem ? ' (note)' : '';
item.textContent = `${message.from}${kind}: ${message.text} · pictures: ${(message.images ?? []).length}`;
return item;
}));
});Four more rules apply to answers:
- A
fromthat names no member gives the note of the world as iffromwere missing. - A file whose
urlis an image (data:image/...) arrives inimagesinstead offiles. - A media item that breaks its rules (for example an
http:address) arrives as itsaltintextwith an emptymediaexactly as from a real world. - The files of the person keep their name.
message.filesinonMessageholds thename,typeandurlsent by the person.
A fake agent
For the view of an agent, pass a FakeNode as fake.agent:
const helper = await connectToHost({
fake: { agent: { name: 'Helper', onMessage: (message) => ({ text: 'Here you are', image: drawPicture(message.text) }) } },
});As in the webapp, the agent has to be reached first. For about a third of a second its status is 'connecting', it has no data and canSend is false. Then it turns 'online'. A send made in the meantime waits for the agent. The agent has no members, roles or myRole and its showsSenders is always true. Its answers are its own messages that keep everything a FakeAnswer holds (images and files included).
What else a fake world pretends
- The person is called
'You'and has the address'you/You'. webapptakes its theme from the colour scheme of your page and its language from the browser in the browser format (for example'en-US'). It has no safe areas and no keyboard and allows everyBrowserFeature.connectToHost({ fake, webapp: { theme: 'dark', language: 'it', keyboard: 300 } })lets you try other values.setPath,onBackandaskForare accepted and do nothing.setPathandaskForresolvetruewhile anonBackhandler never runs.identity()resolves at once with themeof the fake world.openProfile(id)shows no card. It resolvestruefor the id of the world or of a member (for a fake agent the id of the agent) andfalsefor any other id.loadMoreresolves0because a fake world keeps no older messages.- No error code except
'too-big'. Nobody asks the person anything and no webapp can fail. The kit itself checks the size of a file and rejects with'too-big'over 20 MB as in the webapp (Testing your error handling). - Everything lives in your page. Reloading the page starts the fake world over.
See also
- Testing with fake worlds: a whole view built on a fake world.
- The recipes A fake world that changes over time and Test failures with a fake world.