Skip to content

ActionButtons ​

ActionButtons renders a button for each action that the rules of a world offer the person in world.now.actions (voting, passing, joining a team). A click on a button asks the rules to perform that action. Use it in the view of a game, a vote, a workflow or any other world with rules. While the rules offer no action the component renders nothing.

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

Each button shows the text of its action (or the name when text is missing) and gives in its tooltip the step that the action leads to (to). A button is disabled when canChoose is false and gets a "waiting" mark when isRequested is true (The actions the rules offer describes every field). On a click the component calls world.act(name) and the returned Promise resolves with 'requested', 'refused' or 'not-allowed'. After 'requested' the answer of the world arrives as a new message.

All buttons stay disabled until the pending call to act settles. When the call resolves with 'refused' or 'not-allowed' or rejects, the component writes the reason in a status line under the buttons.

Props ​

PropDefaultWhat it is
world(required)The world returned by useWorld.
title'What will you do?'The heading above the buttons and the accessible name of the button group.

Parameters ​

actionButtons(container, world, options) renders into container and renders again on every change of the world.

ParameterWhat it is
containerThe element to render into.
worldThe world that connectToHost resolves with.
options.titleThe heading above the buttons. Default 'What will you do?'.

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

Change it ​

  • Hide the actions the person cannot choose by skipping those with canChoose === false instead of disabling them.
  • Ask for confirmation before a big choice with confirm(...) or a dialog of your own in choose before the call to world.act.
  • Show where an action leads by writing action.to under the button as well as in its tooltip.
  • Show only what is waiting as in Show which action is waiting.

See also ​

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