Skip to content

MessageBox ​

MessageBox renders a text field and a Send button. The button sends the text as a message of the person with world.send(text) and Enter in the field does the same. In a chat the box goes under a 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

The field keeps its text when send resolves 'not-allowed' and empties on 'sent' and 'failed'. A failed message stays in world.messages with status: 'failed' and message.retry() sends it again (send › Returns).

The button stays disabled in three cases (an empty field, a pending message and a person who cannot send now). For the last case a status line under the field (a role="status" region) gives the reason:

  • world.status is 'ended' ("This world has ended.") or any value other than 'online' ("Waiting for the connection…").
  • world.canSend is false during the turn of another player or whenever else the rules do not accept a message ("Wait for your turn to send.").

After a 'failed' or 'not-allowed' result the same line shows the outcome. When send rejects (with the code 'failed' if the webapp could not run the call) the line shows the text for that code or "Not sent." for a code it does not know (Errors and the person's controls).

Props ​

PropDefaultWhat it is
world(required)The world (or agent), from useWorld.
placeholder'Write a message…'The placeholder of the empty field.
onSentnoneA (text) => void callback that receives the text after send resolves 'sent'.

Parameters ​

messageBox(container, world, options) draws the box into container and subscribes to the world to enable and disable the button.

ParameterWhat it is
containerThe element to draw into.
worldThe world (or agent), from connectToHost.
options.placeholderThe placeholder of the empty field. Default 'Write a message…'.
options.onSentA (text) => void callback that receives the text after send resolves 'sent'.

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

Change it ​

  • Several lines: replace the input with a textarea and submit on Enter without Shift in its keydown listener.
  • Your own texts: edit PROBLEMS and whyNot. To match the language of the webapp, pick them by world.webapp.language.
  • Above the phone keyboard: put the box inside SafeArea (Keep the message box above the keyboard).
  • Send a picture too: world.send({ image, text }) takes the image as a data URI or URL together with the text (Send a photo from the camera).

See also ​

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