Skip to content

Offri come pulsanti le azioni delle regole ​

Le regole di un mondo possono offrire alla persona azioni come votare, passare o uscire. Queste azioni sono in world.now.actions e cambiano quando le regole passano a un nuovo stato. Disegna un pulsante per ogni azione che la persona può scegliere e chiedi quell'azione con world.act(name). L'esempio offre un voto.

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

// In this fake town hall, the rules offer three actions and the world answers each one.
const townHall = {
	name: 'Town hall',
	now: {
		text: 'The meeting is open: vote on the new park.',
		actions: [
			{ name: 'vote_yes', text: 'Vote yes' },
			{ name: 'vote_no', text: 'Vote no' },
			{ name: 'leave', text: 'Leave the meeting' },
		],
	},
	onAction: (name) => (name === 'leave' ? 'You left the meeting.' : `Your vote is in: ${name === 'vote_yes' ? 'yes' : 'no'}.`),
};

// What act() answered, in words.
const RESULTS = {
	requested: 'Asked. The rules will do it.',
	refused: 'The rules did not take it now.',
	'not-allowed': 'This action is not offered now.',
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: townHall } });
	const [result, setResult] = useState('');

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	async function choose(name) {
		try {
			// act() asks the rules to do one of `now.actions` for the person.
			setResult(RESULTS[await world.act(name)]);
		} catch (error) {
			// The webapp could not even try it, for example 'failed' when something went wrong on its side.
			setResult(`Not done (${error.code}).`);
		}
	}

	// The actions the rules offer now. One whose `canChoose` is false runs on its own and gets no button.
	const actions = (world.now?.actions ?? []).filter((action) => action.canChoose !== false);
	const note = world.messages.filter((message) => message.isSystem).at(-1);
	return (
		<>
			<p>{world.now?.text}</p>
			{actions.map((action) => (
				<button key={action.name} onClick={() => choose(action.name)}>{action.text ?? action.name}</button>
			))}
			<p>{result}</p>
			<p>{note ? note.text : ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// In this fake town hall, the rules offer three actions and the world answers each one.
const townHall = {
	name: 'Town hall',
	now: {
		text: 'The meeting is open: vote on the new park.',
		actions: [
			{ name: 'vote_yes', text: 'Vote yes' },
			{ name: 'vote_no', text: 'Vote no' },
			{ name: 'leave', text: 'Leave the meeting' },
		],
	},
	onAction: (name) => (name === 'leave' ? 'You left the meeting.' : `Your vote is in: ${name === 'vote_yes' ? 'yes' : 'no'}.`),
};

// What act() answered, in words.
const RESULTS = {
	requested: 'Asked. The rules will do it.',
	refused: 'The rules did not take it now.',
	'not-allowed': 'This action is not offered now.',
};

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

const now = document.createElement('p');
const buttons = document.createElement('div');
const result = document.createElement('p');
const note = document.createElement('p');
document.body.append(now, buttons, result, note);

let shownActions = null; // the names of the buttons on the page
world.subscribe((node) => {
	now.textContent = node.now?.text ?? '';
	const last = node.messages.filter((message) => message.isSystem).at(-1);
	note.textContent = last ? last.text : '';

	// The actions the rules offer now. One whose `canChoose` is false runs on its own and gets no button.
	const actions = (node.now?.actions ?? []).filter((action) => action.canChoose !== false);
	const names = actions.map((action) => action.name).join(' ');
	if (names === shownActions) return;
	shownActions = names;
	buttons.replaceChildren(...actions.map((action) => {
		const button = document.createElement('button');
		button.textContent = action.text ?? action.name;
		button.onclick = async () => {
			try {
				// act() asks the rules to do one of `now.actions` for the person.
				result.textContent = RESULTS[await world.act(action.name)];
			} catch (error) {
				// The webapp could not even try it, for example 'failed' when something went wrong on its side.
				result.textContent = `Not done (${error.code}).`;
			}
		};
		return button;
	}));
});
Live, on a fake world
Open

Come funziona ​

  • Ogni azione ha un name che act riceve, un text che la descrive (oppure null) e canChoose. Un'azione con canChoose: false avviene da sola quando le regole lo decidono e non ha un pulsante (l'esempio la esclude).
  • world.act(name) si risolve con 'requested' quando le regole hanno accettato la richiesta, con 'refused' quando l'hanno respinta o non hanno risposto entro 10 secondi e con 'not-allowed' quando l'azione in questo momento non è offerta.
  • L'effetto dell'azione arriva dopo come un cambiamento del mondo. Nell'esempio è una nota delle regole (un messaggio con isSystem: true).
  • Se la webapp non riesce proprio a fare la chiamata, act viene rifiutata con un errore il cui code è 'failed' e il catch dell'esempio lo mostra.
  • Un mondo finto ha bisogno di now.actions e di una callback onAction(name) che restituisce la risposta del mondo all'azione scelta.

Vedi anche ​

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