Grid
La scacchiera di un gioco, una mappa a caselle o i posti di una sala arrivano alla tua vista come una griglia di valori nei dati del mondo. Grid disegna questa griglia e la disegna di nuovo a ogni cambiamento. Un valore che ha un colore in colors riempie la sua casella con quel colore e ogni altro valore viene scritto nella casella come testo. Con onCellClick ogni casella diventa anche un pulsante.
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>
);
}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.';
});Nell'esempio un clic su una casella invia al mondo un messaggio con la riga e la colonna. Il mondo finto risponde con la sua mossa e la griglia mostra la nuova scacchiera.
Una griglia in world.data è un array di righe. Il kit toglie ogni livello di array che contiene un solo elemento. Una scacchiera di una sola riga arriva quindi come array piatto e una scacchiera di una sola casella come valore nudo. rowsOf riporta tutti e due i casi in righe (I dati del mondo).
Il componente si limita a disegnare la griglia e lascia a te l'effetto di un clic. Qui onCellClick invia la mossa "row,column" che questo mondo finto capisce. In un mondo vero il formato di una mossa lo definiscono le sue regole. Ogni casella cliccabile ha un nome accessibile come "Row 2, column 2, X" (o "empty" per una casella vuota). Quando la scacchiera cambia il focus resta sulla casella che lo aveva.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo restituito da useWorld. |
name | (obbligatorio) | Il nome della griglia in world.data. |
colors | {} | Un colore CSS per ogni valore che riempie la sua casella (per esempio { 1: '#2A54C4', 2: '#9F466B' }). I valori senza colore vengono scritti come testo. |
cellSize | 48 | Il lato di una casella in pixel. |
onCellClick | nessuno | Una callback (row, column, value) => void chiamata al clic con riga e colonna contate da zero. Senza la callback le caselle non sono pulsanti. |
label | 'Grid' | Il nome accessibile della griglia. |
Parametri
grid(container, world, options) disegna dentro container e disegna di nuovo ogni volta che la griglia cambia.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo con cui si risolve connectToHost. |
options.name | Il nome della griglia in world.data. |
options.colors | Un colore CSS per ogni valore che riempie la sua casella. Predefinito {}. |
options.cellSize | Il lato di una casella in pixel. Predefinito 48. |
options.onCellClick | Una callback (row, column, value) => void chiamata al clic. |
options.label | Il nome accessibile della griglia. Predefinito 'Grid'. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove la griglia.
Modificalo
- Disegna una mappa colorata con
colorscome{ 0: 'transparent', 1: '#399D57', 2: '#2A54C4' }per caselle vuote, erba e acqua. - Accetta i clic solo nel turno della persona. Passa
onCellClicksolo mentreworld.canSendètruee le caselle restano semplici mentre la persona aspetta. - Passa a un canvas per una griglia grande. Oltre qualche migliaio di caselle disegnala come in Disegna una griglia su un canvas.
- Adattala allo schermo con un
cellSizepari alla larghezza della vista divisa per il numero di colonne.
Vedi anche
TurnIndicator: mostra di chi è il turno accanto alla scacchiera.DataImage: per un'immagine al posto di una griglia di valori.- Tutorial: un gioco a turni: un gioco intero intorno a una scacchiera.