Skip to content

Spiega un messaggio rifiutato ​

world.send si risolve con 'not-allowed' e non invia niente in tre casi: (1) il valore è vuoto, (2) il mondo non è raggiungibile e (3) le regole del mondo in questo momento non accettano un messaggio. Un gioco a turni, per esempio, rifiuta i messaggi fuori dal turno della persona. Di' alla persona in quale caso si trova e lascia nella casella il testo che ha scritto. L'esempio dal vivo può mostrare solo il rifiuto di una casella vuota (premi Send senza scrivere niente) perché un mondo finto accetta sempre i messaggi.

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

// While you build, a fake game answers every move.
const arena = {
	name: 'Arena',
	now: { text: 'Your move, white' },
	onMessage: (message) => `Move taken: ${message.text}`,
};

// Says why the world did not take a message, in the person's words.
function whyNotAllowed(node, text) {
	if (!text.trim()) return 'Write your move first.';
	if (!node.isOnline) return 'The world cannot be reached now. Try again in a moment.';
	// Otherwise the rules of the world do not take a message now. Show what they say is happening.
	return `Not now: ${node.now?.text ?? 'it is not your turn'}.`;
}

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });
	const [text, setText] = useState('');
	const [note, setNote] = useState('');

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

	async function onSubmit(event) {
		event.preventDefault();
		const result = await world.send(text);
		// 'not-allowed' means that nothing was sent. Tell the person why, and keep what they wrote.
		if (result === 'not-allowed') {
			setNote(whyNotAllowed(world.get(), text));
			return;
		}
		setNote(result === 'sent' ? '' : 'Not delivered.');
		setText('');
	}

	const last = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<p>{world.now?.text}</p>
			<form onSubmit={onSubmit}>
				<input placeholder="Your move" value={text} onChange={(event) => setText(event.target.value)} />
				<button>Send</button>
			</form>
			<p>{note}</p>
			<p>{last ? last.text : ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// While you build, a fake game answers every move.
const arena = {
	name: 'Arena',
	now: { text: 'Your move, white' },
	onMessage: (message) => `Move taken: ${message.text}`,
};

// Says why the world did not take a message, in the person's words.
function whyNotAllowed(node, text) {
	if (!text.trim()) return 'Write your move first.';
	if (!node.isOnline) return 'The world cannot be reached now. Try again in a moment.';
	// Otherwise the rules of the world do not take a message now. Show what they say is happening.
	return `Not now: ${node.now?.text ?? 'it is not your turn'}.`;
}

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

const now = document.createElement('p');
const form = document.createElement('form');
const input = document.createElement('input');
input.placeholder = 'Your move';
const send = document.createElement('button');
send.textContent = 'Send';
form.append(input, send);
const note = document.createElement('p');
const answer = document.createElement('p');
document.body.append(now, form, note, answer);

form.onsubmit = async (event) => {
	event.preventDefault();
	const text = input.value;
	const result = await world.send(text);
	// 'not-allowed' means that nothing was sent. Tell the person why, and keep what they wrote.
	if (result === 'not-allowed') {
		note.textContent = whyNotAllowed(world.get(), text);
		return;
	}
	note.textContent = result === 'sent' ? '' : 'Not delivered.';
	input.value = '';
};

// Called at once, then after every change of the world.
world.subscribe((node) => {
	now.textContent = node.now?.text ?? '';
	const last = node.messages.filter((message) => !message.fromMe).at(-1);
	answer.textContent = last ? last.text : '';
});
Live, on a fake world
Open

Come funziona ​

  • Il rifiuto è un risultato e non un errore. Per questo send si risolve con 'not-allowed' e la Promise non viene rifiutata. Non è stato inviato niente e più tardi non verrà inviato niente.
  • Quando sono le regole a rifiutare, now.text descrive che cosa succede nel mondo ("Waiting for Bob to move") ed è il motivo migliore da mostrare. Un mondo non raggiungibile ha isOnline: false.
  • Disattiva la casella mentre world.canSend è false (Disattiva la casella dei messaggi quando la persona non può inviare) e gestisci comunque 'not-allowed' per un mondo che cambia fra l'ultimo render e il clic.
  • message.answer si risolve con 'not-allowed' per una domanda che ha già una risposta o per valori che non contengono nessun campo del modulo. act si risolve con lo stesso valore per un'azione che le regole adesso non offrono.
  • Un messaggio 'failed' invece è stato inviato senza essere consegnato. message.retry() lo invia di nuovo (Riprova un messaggio fallito).

Vedi anche ​

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