Skip to content

ActionButtons ​

ActionButtons mostra un pulsante per ogni azione che le regole di un mondo offrono alla persona in world.now.actions (votare, passare, entrare in una squadra). Un clic sul pulsante chiede alle regole di eseguire quell'azione. Usalo nella vista di un gioco, di una votazione, di un flusso di lavoro o di qualsiasi altro mondo con delle regole. Finché le regole non offrono azioni il componente non mostra niente.

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

// The component: copy this part.

/** What the buttons say when an action did not go, for each reason. */
const PROBLEMS = {
	refused: 'The rules refused it.',
	'not-allowed': 'You cannot choose it now.',
};

/**
 * ActionButtons: the actions that the rules of the world offer the person now,
 * as buttons. Each button asks the rules to do its action and is marked as
 * waiting once someone asked for it. It shows nothing when the rules offer none.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string} [props.title='What will you do?'] - The words above the buttons.
 */
export function ActionButtons({ world, title = 'What will you do?' }) {
	const titleId = useId();
	// The action being asked for now, and why the last one did not go.
	const [asking, setAsking] = useState(null);
	const [problem, setProblem] = useState(null);
	const actions = world.now?.actions ?? [];
	if (actions.length === 0) return null;

	const choose = async (action) => {
		setAsking(action.name);
		setProblem(null);
		try {
			// 'requested' means that the rules will do it, and the answer of the world follows. Any other result is a reason.
			const result = await world.act(action.name);
			if (result !== 'requested') setProblem(PROBLEMS[result]);
		} catch (error) {
			setProblem(PROBLEMS[error.code] ?? 'It did not go.');
		} finally {
			setAsking(null);
		}
	};

	return (
		<div role="group" aria-labelledby={titleId} style={{ display: 'grid', gap: 8 }}>
			<p id={titleId} style={{ margin: 0, fontWeight: 600 }}>{title}</p>
			<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
				{actions.map((action) => {
					// `canChoose` is false when the rules list the action but the person may not choose it.
					const isOff = asking !== null || action.canChoose === false;
					return (
						<button key={`${action.name}-${action.to}`} type="button" disabled={isOff} onClick={() => choose(action)}
							title={action.to ? `Leads to: ${action.to}` : undefined}
							style={{
								padding: '8px 16px', borderRadius: 10, font: 'inherit', fontWeight: 600, cursor: isOff ? 'not-allowed' : 'pointer',
								border: '1px solid #2A54C4', opacity: isOff ? 0.5 : 1,
								background: action.isRequested ? '#2A54C4' : 'transparent', color: action.isRequested ? '#fff' : 'inherit',
							}}>
							{asking === action.name ? 'Asking…' : action.text || action.name}
							{action.isRequested && ' · waiting'}
						</button>
					);
				})}
			</div>
			<p role="status" style={{ margin: 0, minHeight: '1.4em', fontSize: 13, opacity: 0.8 }}>
				{problem}
			</p>
		</div>
	);
}

// Using it, on a fake world.

// A fake world to build with: its rules offer three actions now.
const council = {
	name: 'Council',
	now: {
		text: 'The vote is open.',
		actions: [
			{ name: 'yes', text: 'Vote yes', to: 'counting' },
			{ name: 'no', text: 'Vote no', to: 'counting' },
			{ name: 'abstain', text: 'Abstain', to: 'counting' },
		],
	},
	// Answers what the person chose, with a note of the world.
	onAction: (name) => `Your vote is counted: ${name}.`,
};

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

	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 }}>
			<h2 style={{ margin: 0 }}>{world.name}</h2>
			<p style={{ margin: 0 }}>{said ? said.text : world.now?.text}</p>
			<ActionButtons world={world} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** What the buttons say when an action did not go, for each reason. */
const PROBLEMS = {
	refused: 'The rules refused it.',
	'not-allowed': 'You cannot choose it now.',
};

/**
 * Draws into `container`, as buttons, the actions that the rules of the world
 * offer the person now, and draws them again at every change. Each button asks
 * the rules to do its action and is marked as waiting once someone asked for it.
 * It draws nothing when the rules offer no action.
 * @param {HTMLElement} container - Where to draw them.
 * @param {object} world - The world, from connectToHost.
 * @param {{title?: string}} [options] - The words above the buttons.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function actionButtons(container, world, { title = 'What will you do?' } = {}) {
	const group = document.createElement('div');
	group.setAttribute('role', 'group');
	group.setAttribute('aria-label', title);
	Object.assign(group.style, { display: 'grid', gap: '8px' });
	const heading = document.createElement('p');
	heading.textContent = title;
	Object.assign(heading.style, { margin: '0', fontWeight: '600' });
	const row = document.createElement('div');
	Object.assign(row.style, { display: 'flex', flexWrap: 'wrap', gap: '8px' });
	const status = document.createElement('p');
	status.setAttribute('role', 'status');
	Object.assign(status.style, { margin: '0', minHeight: '1.4em', fontSize: '13px', opacity: '0.8' });
	group.append(heading, row, status);
	container.append(group);

	// The action being asked for now, and why the last one did not go.
	let asking = null;
	let problem = null;
	// What the buttons show now. They are made again only when it changes, to let a button keep its focus.
	let drawn = '';

	/** Draws the buttons from the newest world. */
	const draw = () => {
		const node = world.get();
		const actions = node.now?.actions ?? [];
		group.style.display = actions.length === 0 ? 'none' : 'grid';
		status.textContent = problem ?? '';
		const shown = JSON.stringify([actions, asking]);
		if (shown === drawn) return;
		drawn = shown;
		row.replaceChildren(...actions.map((action) => {
			// `canChoose` is false when the rules list the action but the person may not choose it.
			const isOff = asking !== null || action.canChoose === false;
			const button = document.createElement('button');
			button.type = 'button';
			button.disabled = isOff;
			button.textContent = asking === action.name ? 'Asking…' : action.text || action.name;
			if (action.isRequested) button.textContent += ' · waiting';
			if (action.to) button.title = `Leads to: ${action.to}`;
			Object.assign(button.style, {
				padding: '8px 16px', borderRadius: '10px', font: 'inherit', fontWeight: '600', cursor: isOff ? 'not-allowed' : 'pointer',
				border: '1px solid #2A54C4', opacity: isOff ? '0.5' : '1',
				background: action.isRequested ? '#2A54C4' : 'transparent', color: action.isRequested ? '#fff' : 'inherit',
			});
			button.onclick = () => choose(action);
			return button;
		}));
	};

	const choose = async (action) => {
		asking = action.name;
		problem = null;
		draw();
		try {
			// 'requested' means that the rules will do it, and the answer of the world follows. Any other result is a reason.
			const result = await world.act(action.name);
			if (result !== 'requested') problem = PROBLEMS[result];
		} catch (error) {
			problem = PROBLEMS[error.code] ?? 'It did not go.';
		} finally {
			asking = null;
			draw();
		}
	};

	// Called at once, then after every change of the world.
	const stop = world.subscribe(draw);

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

// Using it, on a fake world.

// A fake world to build with: its rules offer three actions now.
const council = {
	name: 'Council',
	now: {
		text: 'The vote is open.',
		actions: [
			{ name: 'yes', text: 'Vote yes', to: 'counting' },
			{ name: 'no', text: 'Vote no', to: 'counting' },
			{ name: 'abstain', text: 'Abstain', to: 'counting' },
		],
	},
	// Answers what the person chose, with a note of the world.
	onAction: (name) => `Your vote is counted: ${name}.`,
};

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

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

actionButtons(place, world);
world.subscribe((node) => {
	const last = node.messages.filter((message) => !message.fromMe).at(-1);
	title.textContent = node.name;
	said.textContent = last ? last.text : node.now?.text ?? '';
});
Live, on a fake world
Open

Ogni pulsante mostra il text della sua azione (o il name quando text manca) e indica nel tooltip il passo a cui porta l'azione (to). Un pulsante è disattivato quando canChoose è false e prende un segno di attesa quando isRequested è true (Le azioni delle regole descrive ogni campo). Al clic il componente chiama world.act(name) e la Promise restituita si risolve con 'requested', 'refused' o 'not-allowed'. Dopo 'requested' la risposta del mondo arriva come nuovo messaggio.

Tutti i pulsanti restano disattivati finché la chiamata ad act in corso non si conclude. Quando la chiamata si risolve con 'refused' o 'not-allowed' oppure viene rifiutata, il componente scrive il motivo in una riga di stato sotto i pulsanti.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo restituito da useWorld.
title'What will you do?'L'intestazione sopra i pulsanti e il nome accessibile del gruppo di pulsanti.

Parametri ​

actionButtons(container, world, options) disegna dentro container e disegna di nuovo a ogni cambiamento del mondo.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo con cui si risolve connectToHost.
options.titleL'intestazione sopra i pulsanti. Predefinito 'What will you do?'.

Restituisce una funzione che annulla l'iscrizione al mondo e rimuove i pulsanti.

Modificalo ​

  • Nascondi le azioni che la persona non può scegliere saltando quelle con canChoose === false invece di disattivarle.
  • Chiedi conferma prima di una scelta importante con confirm(...) o con una tua finestra di dialogo dentro choose prima della chiamata a world.act.
  • Mostra dove porta un'azione. Oltre che nel tooltip puoi scrivere action.to sotto il pulsante.
  • Mostra solo ciò che è in attesa come in Mostra quale azione è in attesa.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.