TurnIndicator
TurnIndicator mostra di chi è il turno accanto al tabellone di un gioco a turni o in qualsiasi mondo in cui si procede a turni (un'asta, un dibattito, un giro di domande). Durante il turno della persona il badge mostra Your turn sullo sfondo blu che usa la webapp. Quando gioca qualcun altro mostra "Waiting for" seguito dal ruolo indicato nei dati ("Waiting for black") oppure da "the others" quando i dati non ne indicano nessuno. Gli screen reader annunciano Your turn una volta sola all'inizio del turno della persona perché il badge è una regione role="status" il cui testo cambia solo con il turno.
import { useWorld } from './useWorld.js';
// The component: copy this part.
/**
* Tells whose turn it is. When the world says it in its data (a role, like
* 'white'), it is the person's turn when that is their role. Otherwise it is
* their turn while the rules of the world let them send.
* @param {object} world - The world.
* @param {string} name - The name in `world.data` that says whose turn it is.
* @returns {{isMine: boolean, whose: string|null}} Whether it is the person's turn, and whose it is.
*/
function turnOf(world, name) {
const whose = world.data[name];
if (typeof whose === 'string') return { isMine: whose === world.myRole, whose };
return { isMine: world.canSend, whose: null };
}
/**
* TurnIndicator: whose turn it is, in a game or any world where people take
* turns. When the turn comes, "Your turn" stands out and screen readers say it.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} [props.name='turn'] - The name in `world.data` that says whose turn it is (a role).
*/
export function TurnIndicator({ world, name = 'turn' }) {
const { isMine, whose } = turnOf(world, name);
let text = isMine ? 'Your turn' : `Waiting for ${whose ?? 'the others'}`;
if (world.status === 'ended') text = 'The game is over';
const isHighlighted = isMine && world.status !== 'ended';
return (
<p role="status" style={{
display: 'inline-flex', alignItems: 'center', gap: 8, margin: 0, padding: '6px 14px', borderRadius: 30, fontWeight: 600,
background: isHighlighted ? '#2A54C4' : 'rgba(127, 127, 127, 0.15)', color: isHighlighted ? '#fff' : 'inherit',
}}>
<span aria-hidden="true" style={{ width: 8, height: 8, borderRadius: '50%', background: isHighlighted ? '#fff' : '#9D9C9A' }} />
{text}
</p>
);
}
// Using it, on a fake world.
// Whose turn it is in the fake world: the person plays white.
let turn = 'white';
// A fake world to build with: after the person's move, black plays for a second and a half.
const chess = {
name: 'Chess',
roles: [{ name: 'white' }, { name: 'black' }],
myRole: 'white',
data: { turn: { every: 200, value: () => turn } },
onMessage: () => {
turn = 'black';
setTimeout(() => { turn = 'white'; }, 1500);
return 'Black is thinking…';
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: chess } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
const isMyTurn = world.data.turn === world.myRole;
return (
<div style={{ display: 'grid', gap: 12, justifyItems: 'start' }}>
<h2 style={{ margin: 0 }}>{world.name}</h2>
<TurnIndicator world={world} />
<button type="button" disabled={!isMyTurn} onClick={() => world.send('e2-e4')}>Make a move</button>
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/**
* Tells whose turn it is. When the world says it in its data (a role, like
* 'white'), it is the person's turn when that is their role. Otherwise it is
* their turn while the rules of the world let them send.
* @param {object} node - The world.
* @param {string} name - The name in `world.data` that says whose turn it is.
* @returns {{isMine: boolean, whose: string|null}} Whether it is the person's turn, and whose it is.
*/
function turnOf(node, name) {
const whose = node.data[name];
if (typeof whose === 'string') return { isMine: whose === node.myRole, whose };
return { isMine: node.canSend, whose: null };
}
/**
* Draws whose turn it is into `container` (in a game, or any world where
* people take turns), then again at every change. When the turn comes,
* "Your turn" stands out and screen readers say it.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world, from connectToHost.
* @param {{name?: string}} [options] - The name in `world.data` that says whose turn it is (a role). Default 'turn'.
* @returns {() => void} Stops following the world and removes what it drew.
*/
export function turnIndicator(container, world, { name = 'turn' } = {}) {
const badge = document.createElement('p');
badge.setAttribute('role', 'status');
Object.assign(badge.style, { display: 'inline-flex', alignItems: 'center', gap: '8px', margin: '0', padding: '6px 14px', borderRadius: '30px', fontWeight: '600' });
const dot = document.createElement('span');
dot.setAttribute('aria-hidden', 'true');
Object.assign(dot.style, { width: '8px', height: '8px', borderRadius: '50%' });
const words = document.createElement('span');
badge.append(dot, words);
container.append(badge);
// Called at once, then after every change of the world.
const stop = world.subscribe((node) => {
const { isMine, whose } = turnOf(node, name);
let text = isMine ? 'Your turn' : `Waiting for ${whose ?? 'the others'}`;
if (node.status === 'ended') text = 'The game is over';
const isHighlighted = isMine && node.status !== 'ended';
// Write only new words, to let a screen reader say them once.
if (words.textContent !== text) words.textContent = text;
badge.style.background = isHighlighted ? '#2A54C4' : 'rgba(127, 127, 127, 0.15)';
badge.style.color = isHighlighted ? '#fff' : 'inherit';
dot.style.background = isHighlighted ? '#fff' : '#9D9C9A';
});
return () => {
stop();
badge.remove();
};
}
// Using it, on a fake world.
// Whose turn it is in the fake world: the person plays white.
let turn = 'white';
// A fake world to build with: after the person's move, black plays for a second and a half.
const chess = {
name: 'Chess',
roles: [{ name: 'white' }, { name: 'black' }],
myRole: 'white',
data: { turn: { every: 200, value: () => turn } },
onMessage: () => {
turn = 'black';
setTimeout(() => { turn = 'white'; }, 1500);
return 'Black is thinking…';
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: chess } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', justifyItems: 'start' });
const title = document.createElement('h2');
title.style.margin = '0';
title.textContent = world.name;
const place = document.createElement('div');
const move = document.createElement('button');
move.type = 'button';
move.textContent = 'Make a move';
move.onclick = () => world.send('e2-e4');
page.append(title, place, move);
document.body.append(page);
turnIndicator(place, world);
world.subscribe((node) => {
move.disabled = node.data.turn !== node.myRole;
});Make a move passa il turno al nero per un secondo e mezzo prima che torni al bianco.
Un mondo può indicare di chi è il turno in due modi (Persone e ruoli e I dati del mondo) e il componente li legge entrambi:
- Nei suoi dati, per ruolo. Nell'esempio
world.data.turnvale'white'o'black'. Il turno è della persona quando quella stringa è uguale al suo ruolo inworld.myRole. Il mondo finto dell'esempio usa questa forma perché un valore che cambia nel tempo va indata. - Solo con le sue regole. In questo caso il turno è della persona finché le regole accettano un suo messaggio (
world.canSend).
Quando world.status è 'ended' il componente mostra "The game is over".
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo, da useWorld. |
name | 'turn' | La chiave in world.data che contiene il ruolo di turno. Se sotto quella chiave non c'è una stringa il componente segue world.canSend. |
Parametri
turnIndicator(container, world, options) disegna il badge dentro container e lo ridisegna a ogni cambiamento del mondo.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo, da connectToHost. |
options.name | La chiave in world.data che contiene il ruolo di turno. Predefinito 'turn'. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove il badge.
Modificalo
- Nomi invece di ruoli: quando il mondo mette nei suoi dati il nome di un membro, confrontalo con il nickname della persona in
world.me.nickname(WhoAmI). - Un suono o una vibrazione nel turno della persona: conserva l'ultimo
isMinee chiamanavigator.vibrate(200)o riproduci un breve suono quando diventatrue(Riproduci un suono per un messaggio nuovo). - Il tempo rimasto: mettici accanto un
Timer.
Vedi anche
Grid: il tabellone su cui si giocano i turni.Timer: un conto alla rovescia per ogni turno.- Tutorial: un gioco a turni.