Skip to content

The data of the world ​

A score, a board, a camera frame and a file to download all reach your view in world.data under their names and ready to use. Each kind of value is rendered in its own way. Three cases need more care: (1) a value that changes many times per second, (2) the recent history of a value and (3) the data of a fake world during development.

What data is ​

world.data is an object that maps each name used by the world to its newest value.

js
world.subscribe((node) => {
  score.textContent = node.data.score;   // a number
  board.draw(node.data.board);           // a grid
  camera.src = node.data.camera;         // a picture
});
  • The world chooses the names. Its owner tells you which ones it uses and Object.keys(world.data) lists those present.
  • The values are ready to use. A number arrives as a number, a picture as a URL or data URI for img.src and a file as an object with a name and a URL.
  • A new value is a change of the world. Your subscribe listener runs again with the new data whenever the world sends one.
  • A name appears once the world has given it a value. Until then node.data.score is undefined and the view renders a placeholder such as node.data.score ?? '–'.

The view of an agent also gets data with the values of the agent. In a world each member also has its own data (People and roles).

The kinds of values ​

The example renders one value of each kind in the simplest way:

jsx
import { useWorld } from './useWorld.js';

// A small picture, written as an image source (an SVG data URI).
const cover = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" rx="8" fill="teal"/></svg>')}`;

// A fake world that shows one value of each kind.
const atelier = {
	name: 'Atelier',
	data: {
		players: 3, // a number
		motto: 'Paint together', // text
		board: [[0, 1, 0], [1, 0, 1]], // a grid, as an array of rows
		cover, // a picture, as an image source
		rules: { name: 'rules.txt', type: 'text/plain', url: 'data:text/plain,Be%20kind.' }, // a file
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: atelier } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	const { data } = world;
	return (
		<>
			<p>Players: {data.players}</p>
			<p>Motto: {data.motto}</p>
			{/* One table row per row of the grid, one cell per value. */}
			<table>
				<tbody>
					{data.board.map((row, y) => (
						<tr key={y}>
							{row.map((value, x) => <td key={x}>{value ? '●' : '·'}</td>)}
						</tr>
					))}
				</tbody>
			</table>
			<img src={data.cover} alt="The cover" />
			<a href={data.rules.url} download={data.rules.name}>Download {data.rules.name}</a>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A small picture, written as an image source (an SVG data URI).
const cover = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" rx="8" fill="teal"/></svg>')}`;

// A fake world that shows one value of each kind.
const atelier = {
	name: 'Atelier',
	data: {
		players: 3, // a number
		motto: 'Paint together', // text
		board: [[0, 1, 0], [1, 0, 1]], // a grid, as an array of rows
		cover, // a picture, as an image source
		rules: { name: 'rules.txt', type: 'text/plain', url: 'data:text/plain,Be%20kind.' }, // a file
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: atelier } });

const players = document.createElement('p');
const motto = document.createElement('p');
const board = document.createElement('table');
const picture = document.createElement('img');
const file = document.createElement('a');
picture.alt = 'The cover';
document.body.append(players, motto, board, picture, file);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	const { data } = node;
	players.textContent = `Players: ${data.players}`;
	motto.textContent = `Motto: ${data.motto}`;
	// One table row per row of the grid, one cell per value.
	board.replaceChildren(...data.board.map((row) => {
		const line = document.createElement('tr');
		line.append(...row.map((value) => {
			const cell = document.createElement('td');
			cell.textContent = value ? '●' : '·';
			return cell;
		}));
		return line;
	}));
	picture.src = data.cover;
	file.href = data.rules.url;
	file.download = data.rules.name;
	file.textContent = `Download ${data.rules.name}`;
});
Live, on a fake world
Open
KindWhat you getHow to draw it
Number42, 3.5textContent. Round it with toFixed and format it with toLocaleString.
Texta stringtextContent (or {text} in React) and never innerHTML because the text comes from others.
Gridan array of rows such as [[0, 1, 0], [1, 0, 1]] read as grid[y][x]a table (a canvas for big grids).
Listan array such as [3, 1, 4]a list or a chart.
Picturea URL or, more often, a data URI such as 'data:image/png;base64,...'img.src
File{ name, type, url } with a data URI in url and a MIME type such as 'application/pdf' in typea link (<a href={url} download={name}>)
Anything elsethe value as the world sent it (true, an object)your own code.

An array of one item arrives as the item

Worlds send numeric values as nested arrays whose outer levels sometimes hold a single item. The kit removes every such level and a score sent as [[42]] arrives as 42. The same rule, however, turns a grid with a single row into that row and a list with a single item into the item. When the size can change, restore the levels before rendering:

js
// Makes sure a grid is an array of rows, even with one row or one cell.
function rowsOf(value) {
  if (!Array.isArray(value)) return [[value]]; // a single cell
  return Array.isArray(value[0]) ? value : [value]; // a single row
}

Grids ​

A grid is an array of rows whose items are the cells. grid[y][x] reads the cell in row y and column x. Every change of the grid gives you a whole new grid that you render again from scratch:

jsx
import { useWorld } from './useWorld.js';

// A fake world with a road, a grid of 3 rows and 5 columns where 1 is the car.
// A new grid every half second, with the car one column further to the right.
function road(time) {
	const column = Math.floor(time / 500) % 5;
	return [0, 1, 2].map((y) => [0, 1, 2, 3, 4].map((x) => (y === 1 && x === column ? 1 : 0)));
}
const track = { name: 'Track', data: { road: { every: 500, value: road } } };

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: track } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	const rows = world.data.road;
	// rows[y][x] reads the row first, then the column.
	const column = rows[1].indexOf(1);
	return (
		<>
			<table style={{ fontSize: 24 }}>
				<tbody>
					{rows.map((row, y) => (
						<tr key={y}>
							{row.map((value, x) => <td key={x}>{value === 1 ? '■' : '·'}</td>)}
						</tr>
					))}
				</tbody>
			</table>
			<p>The car is in column {column + 1} of {rows[1].length}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with a road, a grid of 3 rows and 5 columns where 1 is the car.
// A new grid every half second, with the car one column further to the right.
function road(time) {
	const column = Math.floor(time / 500) % 5;
	return [0, 1, 2].map((y) => [0, 1, 2, 3, 4].map((x) => (y === 1 && x === column ? 1 : 0)));
}
const track = { name: 'Track', data: { road: { every: 500, value: road } } };

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: track } });

const table = document.createElement('table');
table.style.fontSize = '24px';
const where = document.createElement('p');
document.body.append(table, where);

// Called at once, then after every change of the world, with a new grid each time.
world.subscribe((node) => {
	const rows = node.data.road;
	table.replaceChildren(...rows.map((row) => {
		const line = document.createElement('tr');
		line.append(...row.map((value) => {
			const cell = document.createElement('td');
			cell.textContent = value === 1 ? '■' : '·';
			return cell;
		}));
		return line;
	}));
	// rows[y][x] reads the row first, then the column.
	const column = rows[1].indexOf(1);
	where.textContent = `The car is in column ${column + 1} of ${rows[1].length}`;
});
Live, on a fake world
Open

A table works up to a few hundred cells. A bigger board or one that changes several times per second belongs on a canvas (Draw a grid on a canvas).

Pictures ​

A picture in data is a URL or data URI that you assign to img.src unchanged. Worlds that film or draw (a camera, a map, a plot) send a new one each time the picture changes.

jsx
import { useWorld } from './useWorld.js';

// Draws a dial whose hand moves every second, as an image source (an SVG data URI).
// A real world sends its pictures the same way, often the frames of a camera as JPEG or PNG.
function dial(time) {
	const angle = (Math.floor(time / 1000) % 60) * 6;
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120">
		<circle cx="60" cy="60" r="54" fill="white" stroke="black" stroke-width="4"/>
		<line x1="60" y1="60" x2="60" y2="14" stroke="crimson" stroke-width="5" transform="rotate(${angle} 60 60)"/>
	</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake world with a picture. A function of time gives a new one every second.
const observatory = { name: 'Observatory', data: { sky: dial } };

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: observatory } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			{/* React changes `src` only when the picture changed. */}
			<img src={world.data.sky} alt="The sky, as the world shows it" width={120} height={120} />
			<p>The world’s picture, new every second.</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// Draws a dial whose hand moves every second, as an image source (an SVG data URI).
// A real world sends its pictures the same way, often the frames of a camera as JPEG or PNG.
function dial(time) {
	const angle = (Math.floor(time / 1000) % 60) * 6;
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120">
		<circle cx="60" cy="60" r="54" fill="white" stroke="black" stroke-width="4"/>
		<line x1="60" y1="60" x2="60" y2="14" stroke="crimson" stroke-width="5" transform="rotate(${angle} 60 60)"/>
	</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake world with a picture. A function of time gives a new one every second.
const observatory = { name: 'Observatory', data: { sky: dial } };

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: observatory } });

const picture = document.createElement('img');
picture.alt = 'The sky, as the world shows it';
picture.width = 120;
picture.height = 120;
const caption = document.createElement('p');
caption.textContent = 'The world’s picture, new every second.';
document.body.append(picture, caption);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// Only when the picture changed, because the world also changes for other reasons (a message, another value).
	if (picture.getAttribute('src') !== node.data.sky) picture.src = node.data.sky;
});
Live, on a fake world
Open
  • Give the image a fixed size (width and height or CSS) to keep the layout from shifting while each new picture loads.
  • Change src only when the picture changed. Your listener also runs on other changes such as a message or another value. React already skips a src that did not change. In plain JavaScript the example compares the new value with getAttribute('src').
  • Large pictures do not slow down the webapp. A big picture is sent to your view once and not again with every message (Performance).
  • To draw a picture on a canvas, load it first with const image = new Image(); image.onload = () => context.drawImage(image, 0, 0); image.src = node.data.camera;. The recipe Show a picture from data has a complete example.

Files ​

A file is an object { name, type, url }:

  • url is a data URI with the content of the file for a link or an <img>.
  • type is the MIME type ('application/pdf', 'image/png', 'text/csv'). The view reads it to choose between showing a picture and offering a link.
  • name is the name of the file or null when the world gave none. file.name ?? 'download' covers both cases.
js
const link = document.createElement('a');
link.href = node.data.report.url;
link.download = node.data.report.name ?? 'report';
link.textContent = `Download ${node.data.report.name ?? 'the report'}`;

The recipe Download a file from data offers a single file with such a link. The component FileList lists several files with their type and size.

Follow one value: onData ​

subscribe calls its listener with the whole world on any change. world.onData(name, listener), on the other hand, calls listener only with each new value of one name and returns a function that stops it.

Use it for a value that changes often and that you render on its own without redrawing the whole page or re-rendering React each time. In the example a position arrives 20 times per second and the view redraws only the canvas:

jsx
import { useEffect, useRef } from 'react';
import { useWorld } from './useWorld.js';

// A fake world with fast data, a new position [x, y] 20 times a second.
const radar = {
	name: 'Radar',
	data: {
		blip: { every: 50, value: (time) => [100 + 70 * Math.cos(time / 600), 100 + 70 * Math.sin(time / 600)] },
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: radar } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<h2>{world.name}</h2>
			<Blip world={world} />
			<p>The dot is drawn by onData, at every new position.</p>
		</>
	);
}

// Draws the position on a canvas, without asking React to render again.
function Blip({ world }) {
	const canvasRef = useRef(null);

	useEffect(() => {
		const canvas = canvasRef.current;
		const context = canvas.getContext('2d');
		function drawBlip([x, y]) {
			context.clearRect(0, 0, canvas.width, canvas.height);
			context.fillStyle = 'crimson';
			context.beginPath();
			context.arc(x, y, 8, 0, 2 * Math.PI);
			context.fill();
		}
		// onData calls you only with each NEW value of one name. Draw the value it has now first.
		if (world.data.blip) drawBlip(world.data.blip);
		// It returns the function that stops it, and React calls it when the component goes away.
		return world.onData('blip', drawBlip);
		// Start once, when the component appears, because onData keeps following the newest world.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return <canvas ref={canvasRef} width={200} height={200} style={{ border: '1px solid gray' }} />;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with fast data, a new position [x, y] 20 times a second.
const radar = {
	name: 'Radar',
	data: {
		blip: { every: 50, value: (time) => [100 + 70 * Math.cos(time / 600), 100 + 70 * Math.sin(time / 600)] },
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: radar } });

const title = document.createElement('h2');
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
canvas.style.border = '1px solid gray';
const note = document.createElement('p');
note.textContent = 'The dot is drawn by onData, at every new position.';
document.body.append(title, canvas, note);

// Draws one position on the canvas.
const context = canvas.getContext('2d');
function drawBlip([x, y]) {
	context.clearRect(0, 0, canvas.width, canvas.height);
	context.fillStyle = 'crimson';
	context.beginPath();
	context.arc(x, y, 8, 0, 2 * Math.PI);
	context.fill();
}

// onData calls you only with each NEW value of one name. Draw the value it has now first.
if (world.data.blip) drawBlip(world.data.blip);
world.onData('blip', drawBlip);

// The rest of the page still follows the world with subscribe.
world.subscribe((node) => {
	title.textContent = node.name;
});
Live, on a fake world
Open

onData behaves in three ways that matter:

  • It passes new values only and never the current one. The example draws world.data[name] first. Without that the canvas stays empty until the next value.
  • A value that never changes never calls the listener (such as a fixed value in a fake world).
  • Inside the webapp it fires only when the webapp sends an updated world to your view and therefore at most once per animation frame. When a value is replaced twice within one frame, you get only the newer one. dataHistory gives every value when you need them all.

In React call onData in an effect that runs once and return its stop function from the effect for React to call on unmount. It makes no difference whether you call onData on world or on a node received by your listener because onData always delivers the newest values.

Fast data ​

Some worlds send many values per second (camera frames, sensor readings, positions in a game). Three practices keep a view smooth:

  • Render fast values on their own with onData on a canvas or an <img> instead of redrawing the whole page for each one.
  • In React, keep fast values out of state. Each setState re-renders your component and 30 renders per second add up. The example above draws through a ref and keeps in state only what the rest of the page shows.
  • Keep your subscribe listener cheap. It also runs on each of those fast changes. Create your elements once and update only their text inside the listener.

The recipe Follow fast data without slowing down and Performance go further. Tutorial: an agent with a camera builds a complete view on a camera that sends ten pictures per second.

Recent values: dataHistory ​

world.dataHistory(name) returns the recent values of one name from the oldest to the newest as [{ value, time }, ...] with the arrival time of each. It keeps up to 200 values and returns an empty array for a name that the world has not used.

jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world with a temperature that changes four times a second.
const station = {
	name: 'Weather station',
	data: {
		temperature: { every: 250, value: (time) => Math.round((20 + 2 * Math.sin(time / 2000)) * 10) / 10 },
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: station } });
	// The summary the person asked for, kept in the state of the page until they ask again.
	const [summary, setSummary] = useState('');

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	// The recent values, asked for when the person wants them. Await them, because inside the webapp they come as a promise.
	async function showHistory() {
		const history = await world.dataHistory('temperature');
		if (history.length === 0) {
			setSummary('No values yet.');
			return;
		}
		const values = history.map((item) => item.value);
		const seconds = Math.round((history.at(-1).time - history[0].time) / 1000);
		setSummary(`${history.length} values in ${seconds} s, lowest ${Math.min(...values)} °C, highest ${Math.max(...values)} °C`);
	}

	return (
		<>
			{/* The value now, from the world at every render. */}
			<p>Temperature now: {world.data.temperature} °C</p>
			<button onClick={showHistory}>Show the recent values</button>
			<p>{summary}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with a temperature that changes four times a second.
const station = {
	name: 'Weather station',
	data: {
		temperature: { every: 250, value: (time) => Math.round((20 + 2 * Math.sin(time / 2000)) * 10) / 10 },
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: station } });

const now = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Show the recent values';
const summary = document.createElement('p');
document.body.append(now, button, summary);

// The value now, from the world at every change.
world.subscribe((node) => {
	now.textContent = `Temperature now: ${node.data.temperature} °C`;
});

// The recent values, asked for when the person wants them. Await them, because inside the webapp they come as a promise.
button.onclick = async () => {
	const history = await world.dataHistory('temperature');
	if (history.length === 0) {
		summary.textContent = 'No values yet.';
		return;
	}
	const values = history.map((item) => item.value);
	const seconds = Math.round((history.at(-1).time - history[0].time) / 1000);
	summary.textContent = `${history.length} values in ${seconds} s, lowest ${Math.min(...values)} °C, highest ${Math.max(...values)} °C`;
};
Live, on a fake world
Open
  • Always await it. Inside the webapp it returns a Promise because the history is kept by the webapp and the kit has to request it. With a fake world it returns the array directly and await works with both.
  • It is a snapshot. Call it again each time you need it (on a button press or every second for a chart) instead of once at startup.
  • time is in milliseconds since the epoch like Date.now(). new Date(item.time) turns it into a date.

The recipe A chart of a number over time plots a value over time.

Data in a fake world ​

The data of a fake world takes three kinds of values:

  1. A fixed value such as table: 'Table 7' that stays the same for the whole life of the fake world.
  2. A function of time (time) => value that the fake world calls every second with the time in milliseconds.
  3. { every, value } for faster data or for a value that follows a variable. The fake world calls value(time) every every milliseconds.

To make the data follow what the person does, keep a variable in your file, change it in onMessage or onAction and read it in a { every, value } function:

jsx
import { useWorld } from './useWorld.js';

// The dice, kept in a variable of this file that the fake world changes.
let dice = 1;

// A fake world with the three kinds of fake data.
const diceTable = {
	name: 'Dice table',
	data: {
		// 1. A fixed value, the same for the whole life of the fake world.
		table: 'Table 7',
		// 2. A function of time, called every second.
		seconds: (time) => Math.floor(time / 1000) % 60,
		// 3. `{ every, value }`, called every 200 ms. It reads the variable and therefore follows the dice.
		dice: { every: 200, value: () => dice },
	},
	// The person's message changes the variable, and the next reading shows it.
	onMessage: (message) => {
		if (message.text !== 'roll') return 'Say roll to roll the dice.';
		dice = 1 + Math.floor(Math.random() * 6);
		return `You rolled ${dice}.`;
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: diceTable } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	const answer = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<p>Table: {world.data.table}</p>
			<p>Seconds: {world.data.seconds}</p>
			<p>Dice: {world.data.dice}</p>
			<button onClick={() => world.send('roll')}>Roll the dice</button>
			<p>{answer?.text ?? ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The dice, kept in a variable of this file that the fake world changes.
let dice = 1;

// A fake world with the three kinds of fake data.
const diceTable = {
	name: 'Dice table',
	data: {
		// 1. A fixed value, the same for the whole life of the fake world.
		table: 'Table 7',
		// 2. A function of time, called every second.
		seconds: (time) => Math.floor(time / 1000) % 60,
		// 3. `{ every, value }`, called every 200 ms. It reads the variable and therefore follows the dice.
		dice: { every: 200, value: () => dice },
	},
	// The person's message changes the variable, and the next reading shows it.
	onMessage: (message) => {
		if (message.text !== 'roll') return 'Say roll to roll the dice.';
		dice = 1 + Math.floor(Math.random() * 6);
		return `You rolled ${dice}.`;
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: diceTable } });

const table = document.createElement('p');
const seconds = document.createElement('p');
const shown = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Roll the dice';
button.onclick = () => world.send('roll');
const answer = document.createElement('p');
document.body.append(table, seconds, shown, button, answer);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	table.textContent = `Table: ${node.data.table}`;
	seconds.textContent = `Seconds: ${node.data.seconds}`;
	shown.textContent = `Dice: ${node.data.dice}`;
	answer.textContent = node.messages.filter((message) => !message.fromMe).at(-1)?.text ?? '';
});
Live, on a fake world
Open

Because the now of a fake world is fixed for its whole life, whatever changes (whose turn it is, a score, a board) goes in data as in the example. A fake world gives all its data at once when your view connects. A fake agent, on the other hand, starts with an empty data and gives its values a moment later as a real agent does. Testing with fake worlds covers the other features of a fake world.

Things to watch ​

  • undefined before the first value. Draw a placeholder until the name appears.
  • An array of one item arrives as the item. Use rowsOf above for grids whose size changes.
  • No copies. Read node.data inside your listener and world.get().data in a click handler (Thinking in views).
  • No innerHTML. The text of data comes from others and goes in textContent.
  • onData starts empty. Draw the current value before the first new one arrives.

Next steps ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.