Skip to content

Grid ​

A game board, a map of tiles or the seats of a room reach your view as a grid of values in the data of the world. Grid renders that grid and renders it again on every change. A value with a colour in colors fills its cell with that colour and any other value is written in the cell as text. With onCellClick every cell also becomes a button.

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

// The component: copy this part.

/**
 * Gives a value of `data` as rows of cells. Because the kit removes the levels
 * that hold only one item, a grid of one row arrives as a plain list, and a
 * grid of one cell as the value alone.
 * @param {*} value - The value in `data`.
 * @returns {Array<Array<*>>} The rows (none when there is no value).
 */
function rowsOf(value) {
	if (value === undefined || value === null) return [];
	if (!Array.isArray(value)) return [[value]];
	return Array.isArray(value[0]) ? value : [value];
}

/**
 * Grid: a grid of values from the data of the world (a board, a map, a seating
 * plan), drawn again at every change. A value with a colour in `colors` fills
 * its cell, and any other value is written in it. When you pass `onCellClick`,
 * every cell is a button.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string} props.name - The name of the grid in `world.data`: rows of values.
 * @param {Record<string, string>} [props.colors] - A CSS colour for some values, for example `{ 1: '#2A54C4' }`.
 * @param {number} [props.cellSize=48] - The side of a cell, in pixels.
 * @param {(row: number, column: number, value: *) => void} [props.onCellClick] - Called when the person picks a cell (counting from 0).
 * @param {string} [props.label='Grid'] - What the grid is, for screen readers.
 */
export function Grid({ world, name, colors = {}, cellSize = 48, onCellClick, label = 'Grid' }) {
	const rows = rowsOf(world.data[name]);
	if (rows.length === 0) return <p style={{ opacity: 0.6 }}>No grid yet.</p>;
	const columns = Math.max(...rows.map((row) => row.length));

	return (
		<div role={onCellClick ? 'group' : 'img'} aria-label={onCellClick ? label : `${label}: ${rows.length} rows by ${columns} columns`}
			style={{ display: 'inline-grid', gridTemplateColumns: `repeat(${columns}, ${cellSize}px)`, gap: 4 }}>
			{rows.flatMap((row, rowIndex) => row.map((value, columnIndex) => {
				const color = colors[value];
				const text = color || value === '' || value === null ? '' : String(value);
				const style = {
					width: cellSize, height: cellSize, display: 'grid', placeItems: 'center', padding: 0, borderRadius: 6,
					border: '1px solid rgba(127, 127, 127, 0.35)', background: color ?? 'transparent', color: 'inherit',
					font: 'inherit', fontSize: cellSize * 0.45, fontWeight: 700,
				};
				const key = `${rowIndex}-${columnIndex}`;
				if (!onCellClick) return <div key={key} style={style}>{text}</div>;
				return (
					<button key={key} type="button" onClick={() => onCellClick(rowIndex, columnIndex, value)}
						aria-label={`Row ${rowIndex + 1}, column ${columnIndex + 1}, ${text || 'empty'}`} style={{ ...style, cursor: 'pointer' }}>
						{text}
					</button>
				);
			}))}
		</div>
	);
}

// Using it, on a fake world.

// The board of the fake world. The person plays X, and the world answers with O.
let board = [['', '', ''], ['', '', ''], ['', '', '']];

/** Puts a mark on the board, as a new board (the old one stays as it was). */
function mark(row, column, value) {
	board = board.map((cells, r) => cells.map((cell, c) => (r === row && c === column ? value : cell)));
}

// A fake world to build with: it shows the board, and plays when the person does.
const ticTacToe = {
	name: 'Tic-tac-toe',
	data: { board: { every: 200, value: () => board } },
	onMessage: (message) => {
		const [row, column] = message.text.split(',').map(Number);
		if (board[row][column] !== '') return 'That cell is taken.';
		mark(row, column, 'X');
		// The world plays O in the first free cell.
		const free = board.flatMap((cells, r) => cells.map((cell, c) => [r, c, cell])).find(([, , cell]) => cell === '');
		if (free) mark(free[0], free[1], 'O');
		return `You played row ${row + 1}, column ${column + 1}.`;
	},
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	const said = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<div style={{ display: 'grid', gap: 12, justifyItems: 'start' }}>
			<p style={{ margin: 0 }}>{said ? said.text : 'Your move: pick a cell.'}</p>
			{/* A move is a message to the world: "row,column". */}
			<Grid world={world} name="board" label="Board" onCellClick={(row, column) => world.send(`${row},${column}`)} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * Gives a value of `data` as rows of cells. Because the kit removes the levels
 * that hold only one item, a grid of one row arrives as a plain list, and a
 * grid of one cell as the value alone.
 * @param {*} value - The value in `data`.
 * @returns {Array<Array<*>>} The rows (none when there is no value).
 */
function rowsOf(value) {
	if (value === undefined || value === null) return [];
	if (!Array.isArray(value)) return [[value]];
	return Array.isArray(value[0]) ? value : [value];
}

/**
 * Draws into `container` a grid of values from the data of the world (a board,
 * a map, a seating plan), and again whenever it changes. A value with a colour
 * in `colors` fills its cell, and any other value is written in it. When you pass
 * `onCellClick`, every cell is a button.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {object} options - What to draw.
 * @param {string} options.name - The name of the grid in `world.data`: rows of values.
 * @param {Record<string, string>} [options.colors] - A CSS colour for some values, for example `{ 1: '#2A54C4' }`.
 * @param {number} [options.cellSize=48] - The side of a cell, in pixels.
 * @param {(row: number, column: number, value: *) => void} [options.onCellClick] - Called when the person picks a cell (counting from 0).
 * @param {string} [options.label='Grid'] - What the grid is, for screen readers.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function grid(container, world, { name, colors = {}, cellSize = 48, onCellClick, label = 'Grid' }) {
	const box = document.createElement('div');
	container.append(box);

	// The grid drawn now. It is made again only when it changes, to let a cell keep its focus.
	let drawn = '';
	const stop = world.subscribe((node) => {
		const rows = rowsOf(node.data[name]);
		const shown = JSON.stringify(rows);
		if (shown === drawn) return;
		drawn = shown;

		if (rows.length === 0) {
			const empty = document.createElement('p');
			empty.textContent = 'No grid yet.';
			empty.style.opacity = '0.6';
			box.replaceChildren(empty);
			return;
		}
		const columns = Math.max(...rows.map((row) => row.length));
		const cells = document.createElement('div');
		cells.setAttribute('role', onCellClick ? 'group' : 'img');
		cells.setAttribute('aria-label', onCellClick ? label : `${label}: ${rows.length} rows by ${columns} columns`);
		Object.assign(cells.style, { display: 'inline-grid', gridTemplateColumns: `repeat(${columns}, ${cellSize}px)`, gap: '4px' });

		rows.forEach((row, rowIndex) => row.forEach((value, columnIndex) => {
			const color = colors[value];
			const text = color || value === '' || value === null ? '' : String(value);
			const cell = document.createElement(onCellClick ? 'button' : 'div');
			cell.textContent = text;
			Object.assign(cell.style, {
				width: `${cellSize}px`, height: `${cellSize}px`, display: 'grid', placeItems: 'center', padding: '0', borderRadius: '6px',
				border: '1px solid rgba(127, 127, 127, 0.35)', background: color ?? 'transparent', color: 'inherit',
				font: 'inherit', fontSize: `${cellSize * 0.45}px`, fontWeight: '700',
			});
			if (onCellClick) {
				cell.type = 'button';
				cell.style.cursor = 'pointer';
				cell.setAttribute('aria-label', `Row ${rowIndex + 1}, column ${columnIndex + 1}, ${text || 'empty'}`);
				cell.onclick = () => onCellClick(rowIndex, columnIndex, value);
			}
			cells.append(cell);
		}));

		// Keep the focus on the same cell, for those who play with the keyboard.
		const focused = [...box.querySelectorAll('button')].indexOf(document.activeElement);
		box.replaceChildren(cells);
		if (focused >= 0) cells.children[focused]?.focus();
	});

	return () => {
		stop();
		box.remove();
	};
}

// Using it, on a fake world.

// The board of the fake world. The person plays X, and the world answers with O.
let board = [['', '', ''], ['', '', ''], ['', '', '']];

/** Puts a mark on the board, as a new board (the old one stays as it was). */
function mark(row, column, value) {
	board = board.map((cells, r) => cells.map((cell, c) => (r === row && c === column ? value : cell)));
}

// A fake world to build with: it shows the board, and plays when the person does.
const ticTacToe = {
	name: 'Tic-tac-toe',
	data: { board: { every: 200, value: () => board } },
	onMessage: (message) => {
		const [row, column] = message.text.split(',').map(Number);
		if (board[row][column] !== '') return 'That cell is taken.';
		mark(row, column, 'X');
		// The world plays O in the first free cell.
		const free = board.flatMap((cells, r) => cells.map((cell, c) => [r, c, cell])).find(([, , cell]) => cell === '');
		if (free) mark(free[0], free[1], 'O');
		return `You played row ${row + 1}, column ${column + 1}.`;
	},
};

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

const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', justifyItems: 'start' });
const said = document.createElement('p');
said.style.margin = '0';
const place = document.createElement('div');
page.append(said, place);
document.body.append(page);

// A move is a message to the world: "row,column".
grid(place, world, { name: 'board', label: 'Board', onCellClick: (row, column) => world.send(`${row},${column}`) });
world.subscribe((node) => {
	const last = node.messages.filter((message) => !message.fromMe).at(-1);
	said.textContent = last ? last.text : 'Your move: pick a cell.';
});
Live, on a fake world
Open

In the example a click on a cell sends the world a message with the row and the column. The fake world plays its move in reply and the grid shows the new board.

A grid in world.data is an array of rows. The kit removes every array level that holds a single item. A board of one row therefore arrives as a flat array and a board of one cell as the bare value. rowsOf turns both back into rows (The data of the world).

The component only renders the grid and leaves the effect of a click to you. Here onCellClick sends the move "row,column" that this fake world understands. A real world defines the format of a move in its rules. Each clickable cell has an accessible name such as "Row 2, column 2, X" (or "empty" for an empty cell). When the board changes, focus stays on the cell that had it.

Props ​

PropDefaultWhat it is
world(required)The world returned by useWorld.
name(required)The name of the grid in world.data.
colors{}A CSS colour for each value that fills its cell (for example { 1: '#2A54C4', 2: '#9F466B' }). Values without a colour are written as text.
cellSize48The side of a cell in pixels.
onCellClicknoneA (row, column, value) => void callback called on a click with zero-based row and column. Without it the cells are not buttons.
label'Grid'The accessible name of the grid.

Parameters ​

grid(container, world, options) renders into container and renders again whenever the grid changes.

ParameterWhat it is
containerThe element to render into.
worldThe world that connectToHost resolves with.
options.nameThe name of the grid in world.data.
options.colorsA CSS colour for each value that fills its cell. Default {}.
options.cellSizeThe side of a cell in pixels. Default 48.
options.onCellClickA (row, column, value) => void callback called on a click.
options.labelThe accessible name of the grid. Default 'Grid'.

It returns a function that unsubscribes from the world and removes the grid.

Change it ​

  • Draw a coloured map with colors such as { 0: 'transparent', 1: '#399D57', 2: '#2A54C4' } for empty cells, grass and water.
  • Accept clicks only on the turn of the person. Pass onCellClick only while world.canSend is true and the cells stay plain while the person waits.
  • Switch to a canvas for a big grid. Past a few thousand cells draw it as in Draw a grid on a canvas.
  • Fit the screen with a cellSize equal to the width of the view divided by the number of columns.

See also ​

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