Skip to content

MessageBox ​

MessageBox mostra un campo di testo e un pulsante Send. Il pulsante invia il testo come messaggio della persona con world.send(text) e Enter nel campo fa lo stesso. In una chat la casella va sotto una MessageList.

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

// The component: copy this part.

/** What the box says when a message did not go, by the reason. */
const PROBLEMS = {
	failed: 'Not sent: you can retry it from the conversation.',
	'not-allowed': 'You cannot send now: wait for your turn.',
};

/**
 * Says why the person cannot send now, or null when they can.
 * @param {object} world - The world.
 * @returns {string|null} The reason.
 */
function whyNot(world) {
	if (world.status === 'ended') return 'This world has ended.';
	if (world.status !== 'online') return 'Waiting for the connection…';
	// The rules of the world say when the person may send.
	if (!world.canSend) return 'Wait for your turn to send.';
	return null;
}

/**
 * MessageBox: a field and a Send button that sends what the person wrote as
 * their message and waits while they cannot send. Enter sends too.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string} [props.placeholder='Write a message…'] - The hint in the empty field.
 * @param {(text: string) => void} [props.onSent] - Called after a message is delivered.
 */
export function MessageBox({ world, placeholder = 'Write a message…', onSent }) {
	const [text, setText] = useState('');
	const [isSending, setIsSending] = useState(false);
	const [problem, setProblem] = useState(null);

	const hint = whyNot(world);
	const canSendNow = hint === null;

	const submit = async (event) => {
		event.preventDefault();
		const value = text.trim();
		if (!value || isSending || !canSendNow) return;
		setIsSending(true);
		setProblem(null);
		try {
			const result = await world.send(value);
			// Sent, or failed: either way it is in the conversation now (a failed one with Retry).
			if (result !== 'not-allowed') setText('');
			if (result === 'sent') onSent?.(value);
			else setProblem(PROBLEMS[result]);
		} catch (error) {
			// The webapp could not try it (for example, 'failed' when something went wrong on its side).
			setProblem(PROBLEMS[error.code] ?? 'Not sent.');
		} finally {
			setIsSending(false);
		}
	};

	return (
		<form onSubmit={submit} style={{ display: 'grid', gap: 6 }}>
			<div style={{ display: 'flex', gap: 8 }}>
				<input value={text} onChange={(event) => setText(event.target.value)} placeholder={placeholder} aria-label="Message"
					style={{ flex: 1, minWidth: 0, padding: '10px 14px', borderRadius: 12, border: '1px solid rgba(127, 127, 127, 0.45)', background: 'transparent', color: 'inherit', font: 'inherit' }} />
				<button type="submit" disabled={!text.trim() || isSending || !canSendNow}
					style={{ padding: '10px 18px', borderRadius: 10, border: 0, background: '#2A54C4', color: '#fff', font: 'inherit', fontWeight: 600, cursor: 'pointer', opacity: !text.trim() || isSending || !canSendNow ? 0.5 : 1 }}>
					{isSending ? 'Sending…' : 'Send'}
				</button>
			</div>
			{/* Why the person cannot send, or why the last message did not go. */}
			<p role="status" style={{ margin: 0, minHeight: '1.4em', fontSize: 13, opacity: 0.75 }}>{problem ?? hint ?? ''}</p>
		</form>
	);
}

// Using it, on a fake agent.

// A fake agent to build with: it answers every message.
const echo = {
	name: 'Echo',
	onMessage: (message) => `You said: ${message.text}`,
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	const answer = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<div style={{ display: 'grid', gap: 12, maxWidth: 520 }}>
			<h2 style={{ margin: 0 }}>{world.name}</h2>
			<p style={{ margin: 0 }}>{answer ? answer.text : 'Write something to Echo.'}</p>
			<MessageBox world={world} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** What the box says when a message did not go, by the reason. */
const PROBLEMS = {
	failed: 'Not sent: you can retry it from the conversation.',
	'not-allowed': 'You cannot send now: wait for your turn.',
};

/**
 * Says why the person cannot send now, or null when they can.
 * @param {object} node - The world.
 * @returns {string|null} The reason.
 */
function whyNot(node) {
	if (node.status === 'ended') return 'This world has ended.';
	if (node.status !== 'online') return 'Waiting for the connection…';
	// The rules of the world say when the person may send.
	if (!node.canSend) return 'Wait for your turn to send.';
	return null;
}

/**
 * Draws into `container` a field and a Send button that sends what the person
 * wrote as their message and waits while they cannot send. Enter sends too.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {{placeholder?: string, onSent?: (text: string) => void}} [options] - The hint in the empty field, and what to do after a message is delivered.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function messageBox(container, world, { placeholder = 'Write a message…', onSent } = {}) {
	const form = document.createElement('form');
	Object.assign(form.style, { display: 'grid', gap: '6px' });
	const row = document.createElement('div');
	Object.assign(row.style, { display: 'flex', gap: '8px' });
	const input = document.createElement('input');
	input.placeholder = placeholder;
	input.setAttribute('aria-label', 'Message');
	Object.assign(input.style, { flex: '1', minWidth: '0', padding: '10px 14px', borderRadius: '12px', border: '1px solid rgba(127, 127, 127, 0.45)', background: 'transparent', color: 'inherit', font: 'inherit' });
	const button = document.createElement('button');
	button.type = 'submit';
	Object.assign(button.style, { padding: '10px 18px', borderRadius: '10px', border: '0', background: '#2A54C4', color: '#fff', font: 'inherit', fontWeight: '600', cursor: 'pointer' });
	// Why the person cannot send, or why the last message did not go.
	const status = document.createElement('p');
	status.setAttribute('role', 'status');
	Object.assign(status.style, { margin: '0', minHeight: '1.4em', fontSize: '13px', opacity: '0.75' });
	row.append(input, button);
	form.append(row, status);
	container.append(form);

	let isSending = false;
	let problem = null;

	/** Draws the button and the status line from the newest world. */
	const draw = () => {
		const hint = whyNot(world.get());
		const canSendNow = hint === null;
		button.textContent = isSending ? 'Sending…' : 'Send';
		button.disabled = !input.value.trim() || isSending || !canSendNow;
		button.style.opacity = button.disabled ? '0.5' : '1';
		status.textContent = problem ?? hint ?? '';
	};

	input.oninput = draw;
	form.onsubmit = async (event) => {
		event.preventDefault();
		const value = input.value.trim();
		if (!value || button.disabled) return;
		isSending = true;
		problem = null;
		draw();
		try {
			const result = await world.send(value);
			// Sent, or failed: either way it is in the conversation now (a failed one with Retry).
			if (result !== 'not-allowed') input.value = '';
			if (result === 'sent') onSent?.(value);
			else problem = PROBLEMS[result];
		} catch (error) {
			// The webapp could not try it (for example, 'failed' when something went wrong on its side).
			problem = PROBLEMS[error.code] ?? 'Not sent.';
		} finally {
			isSending = false;
			draw();
		}
	};

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

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

// Using it, on a fake agent.

// A fake agent to build with: it answers every message.
const echo = {
	name: 'Echo',
	onMessage: (message) => `You said: ${message.text}`,
};

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

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

messageBox(place, world);
world.subscribe((node) => {
	const last = node.messages.filter((message) => !message.fromMe).at(-1);
	title.textContent = node.name;
	answer.textContent = last ? last.text : 'Write something to Echo.';
});
Live, on a fake world
Open

Il campo conserva il suo testo quando send si risolve con 'not-allowed' e si svuota con 'sent' e 'failed'. Un messaggio fallito resta in world.messages con status: 'failed' e message.retry() lo invia di nuovo (send › Valore restituito).

Il pulsante resta disattivato in tre casi (un campo vuoto, un messaggio in corso e una persona che ora non può inviare). Per l'ultimo caso una riga di stato sotto il campo (una regione role="status") ne dà il motivo:

  • world.status è 'ended' ("This world has ended.") o qualsiasi valore diverso da 'online' ("Waiting for the connection…").
  • world.canSend è false durante il turno di un altro giocatore o in qualsiasi altro momento in cui le regole non accettano un messaggio ("Wait for your turn to send.").

Dopo un risultato 'failed' o 'not-allowed' la stessa riga mostra l'esito. Quando send viene rifiutata (con il codice 'failed' se la webapp non è riuscita a eseguire la chiamata) la riga mostra il testo previsto per quel code oppure "Not sent." per un codice che non conosce (Gli errori e i controlli della persona).

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo (o l'agente), da useWorld.
placeholder'Write a message…'Il placeholder del campo vuoto.
onSentnessunoUna callback (text) => void che riceve il testo dopo che send si è risolta con 'sent'.

Parametri ​

messageBox(container, world, options) disegna la casella dentro container e si iscrive al mondo per attivare e disattivare il pulsante.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo (o l'agente), da connectToHost.
options.placeholderIl placeholder del campo vuoto. Predefinito 'Write a message…'.
options.onSentUna callback (text) => void che riceve il testo dopo che send si è risolta con 'sent'.

Restituisce una funzione che annulla l'iscrizione al mondo e rimuove la casella.

Modificalo ​

  • Più righe: sostituisci l'input con una textarea e nel suo listener di keydown invia con Enter senza Shift.
  • I tuoi testi: modifica PROBLEMS e whyNot. Per usare la lingua della webapp, sceglili in base a world.webapp.language.
  • Sopra la tastiera del telefono: metti la casella dentro SafeArea (Tieni la casella dei messaggi sopra la tastiera).
  • Inviare anche un'immagine: world.send({ image, text }) prende insieme al testo un'immagine come data URI o URL (Invia una foto dalla fotocamera).

Vedi anche ​

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