Skip to content

SentToast ​

A view that does not render the conversation (a form, a game board, a vote) gives the person no sign of whether their message arrived. SentToast shows a short note at the bottom of the view when a message of the person is delivered. The note is titled Sent, shows the text of the message (or "A picture" for a message without text) and disappears after duration milliseconds. A failed message gives a Not sent note that stays on screen with Retry and a close button until the person presses one of them.

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

// The component: copy this part.

/**
 * SentToast: a short note at the bottom of the view when one of the
 * person's messages is delivered ("Sent"), or when it is not ("Not sent",
 * with Retry). Because it follows the person's messages, it works whatever
 * part of your view sends them.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {number} [props.duration=2500] - How long "Sent" stays, in milliseconds. "Not sent" stays until it is retried or closed.
 */
export function SentToast({ world, duration = 2500 }) {
	// The note shown now: `{ kind: 'sent' | 'failed', message }`, or null.
	const [toast, setToast] = useState(null);
	// The delivery of each of the person's messages, the last time we looked (null before the first look).
	const known = useRef(null);
	const mine = world.messages.filter((message) => message.fromMe);

	// At every change: a message whose delivery changed to 'sent' or 'failed' gets a note.
	useEffect(() => {
		const isFirstLook = known.current === null;
		if (isFirstLook) known.current = new Map();
		for (const message of mine) {
			const before = known.current.get(message.id);
			known.current.set(message.id, message.status);
			// Messages already there when the view opened get no note.
			if (isFirstLook || message.status === before) continue;
			if (message.status === 'sent' || message.status === 'failed') setToast({ kind: message.status, message });
		}
	});

	// "Sent" goes away by itself.
	useEffect(() => {
		if (toast?.kind !== 'sent') return undefined;
		const timer = setTimeout(() => setToast(null), duration);
		return () => clearTimeout(timer);
	}, [toast, duration]);

	// Above the home bar and the keyboard of the phone (see SafeArea).
	const { insets, keyboard } = world.webapp;
	const retry = () => {
		setToast(null);
		toast.message.retry().catch(() => {});
	};

	return (
		// Always on the page, even when empty, to let a screen reader read each new note.
		<div role="status" style={{ position: 'fixed', left: 16, right: 16, bottom: 16 + Math.max(insets.bottom, keyboard), display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
			{toast && (
				// The colours of the page, the other way round: dark on a light page, light on a dark one.
				<div style={{ pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 12, maxWidth: 420, padding: '10px 14px', borderRadius: 12, background: 'CanvasText', color: 'Canvas', boxShadow: '0 4px 16px rgba(0, 0, 0, 0.25)' }}>
					<span style={{ display: 'grid', minWidth: 0 }}>
						<strong>{toast.kind === 'sent' ? 'Sent' : 'Not sent'}</strong>
						<span style={{ fontSize: 13, opacity: 0.8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{toast.message.text ?? 'A picture'}</span>
					</span>
					{toast.kind === 'failed' && (
						<>
							<button type="button" onClick={retry} style={{ font: 'inherit', fontWeight: 600, padding: '4px 12px', borderRadius: 9, border: '1px solid currentColor', background: 'transparent', color: 'inherit', cursor: 'pointer' }}>Retry</button>
							<button type="button" aria-label="Close" onClick={() => setToast(null)} style={{ font: 'inherit', padding: '4px 8px', border: 0, background: 'transparent', color: 'inherit', cursor: 'pointer' }}>✕</button>
						</>
					)}
				</div>
			)}
		</div>
	);
}

// Using it, on a fake agent.

// A fake agent to build with: the first message sent to it fails (`failNext`) and the next ones go.
const desk = {
	name: 'Help desk',
	failNext: true,
	onMessage: () => 'We got your message.',
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<div style={{ display: 'grid', gap: 12, justifyItems: 'start' }}>
			<h2 style={{ margin: 0 }}>{world.name}</h2>
			<button type="button" disabled={!world.canSend} onClick={() => world.send('My printer is on fire')}>Send a message</button>
			<SentToast world={world} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * Shows a short note at the bottom of the view when one of the person's
 * messages is delivered ("Sent"), or when it is not ("Not sent", with
 * Retry). Because it follows the person's messages, it works whatever part
 * of your view sends them.
 * @param {HTMLElement} container - Where to put it (it shows at the bottom of the view wherever it is).
 * @param {object} world - The world, from connectToHost.
 * @param {{duration?: number}} [options] - How long "Sent" stays, in milliseconds (default 2500).
 *   "Not sent" stays until it is retried or closed.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function sentToast(container, world, { duration = 2500 } = {}) {
	// Always on the page, even when empty, to let a screen reader read each new note.
	const place = document.createElement('div');
	place.setAttribute('role', 'status');
	Object.assign(place.style, { position: 'fixed', left: '16px', right: '16px', display: 'flex', justifyContent: 'center', pointerEvents: 'none' });
	container.append(place);

	let hideTimer = null;

	/** Makes a button of the note. */
	const button = (text, onClick, style) => {
		const element = document.createElement('button');
		element.type = 'button';
		element.textContent = text;
		element.onclick = onClick;
		Object.assign(element.style, { font: 'inherit', background: 'transparent', color: 'inherit', cursor: 'pointer' }, style);
		return element;
	};

	/** Shows a note of kind 'sent' or 'failed' for a message. The kind null hides the note. */
	const show = (kind, message = null) => {
		clearTimeout(hideTimer);
		if (!kind) {
			place.replaceChildren();
			return;
		}
		// The colours of the page, the other way round: dark on a light page, light on a dark one.
		const note = document.createElement('div');
		Object.assign(note.style, { pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: '12px', maxWidth: '420px', padding: '10px 14px', borderRadius: '12px', background: 'CanvasText', color: 'Canvas', boxShadow: '0 4px 16px rgba(0, 0, 0, 0.25)' });
		const words = document.createElement('span');
		Object.assign(words.style, { display: 'grid', minWidth: '0' });
		const title = document.createElement('strong');
		title.textContent = kind === 'sent' ? 'Sent' : 'Not sent';
		const text = document.createElement('span');
		text.textContent = message.text ?? 'A picture';
		Object.assign(text.style, { fontSize: '13px', opacity: '0.8', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
		words.append(title, text);
		note.append(words);
		if (kind === 'failed') {
			note.append(
				button('Retry', () => {
					show(null);
					message.retry().catch(() => {});
				}, { fontWeight: '600', padding: '4px 12px', borderRadius: '9px', border: '1px solid currentColor' }),
				button('✕', () => show(null), { padding: '4px 8px', border: '0' }),
			);
			note.lastChild.setAttribute('aria-label', 'Close');
		}
		place.replaceChildren(note);
		// "Sent" goes away by itself.
		if (kind === 'sent') hideTimer = setTimeout(() => show(null), duration);
	};

	// The delivery of each of the person's messages, the last time we looked (null before the first look).
	let known = null;
	const stop = world.subscribe((node) => {
		// Above the home bar and the keyboard of the phone (see SafeArea).
		place.style.bottom = `${16 + Math.max(node.webapp.insets.bottom, node.webapp.keyboard)}px`;
		const isFirstLook = known === null;
		if (isFirstLook) known = new Map();
		for (const message of node.messages.filter((item) => item.fromMe)) {
			const before = known.get(message.id);
			known.set(message.id, message.status);
			// Messages already there when the view opened get no note.
			if (isFirstLook || message.status === before) continue;
			if (message.status === 'sent' || message.status === 'failed') show(message.status, message);
		}
	});

	return () => {
		stop();
		clearTimeout(hideTimer);
		place.remove();
	};
}

// Using it, on a fake agent.

// A fake agent to build with: the first message sent to it fails (`failNext`) and the next ones go.
const desk = {
	name: 'Help desk',
	failNext: true,
	onMessage: () => 'We got your message.',
};

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

const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', justifyItems: 'start' });
const title = document.createElement('h2');
title.style.margin = '0';
title.textContent = world.name;
const send = document.createElement('button');
send.type = 'button';
send.textContent = 'Send a message';
send.onclick = () => world.send('My printer is on fire');
page.append(title, send);
document.body.append(page);

sentToast(document.body, world);
world.subscribe((node) => {
	send.disabled = !node.canSend;
});
Live, on a fake world
Open

The fake agent fails the first message sent to it (failNext: true). Press Send a message and then Retry.

Instead of wrapping send, the component subscribes to the world and watches the status of the messages with fromMe ('sending', then 'sent' or 'failed'). Any part of your view that sends a message (a MessageBox, a Grid or a QuestionForm) therefore gets a note. Messages already in world.messages when the component starts get no note. Retry calls retry() on the failed message (Show whether a message was delivered and Retry a failed message).

The note has position: fixed and sits 16 pixels above the larger of world.webapp.insets.bottom and world.webapp.keyboard. To invert the colours of the page and stay visible in both themes, the note uses CanvasText as its background and Canvas as its text colour. Screen readers announce each new note because its container is a role="status" region that stays in the page even when empty.

Props ​

PropDefaultWhat it is
world(required)The world (or agent), from useWorld.
duration2500How long Sent stays in milliseconds. Not sent stays until the person retries or closes it.

Parameters ​

sentToast(container, world, options) appends the region of the note to container and subscribes to the world. Wherever container is, the note is fixed at the bottom of the view.

ParameterWhat it is
containerThe element that receives the region (for example document.body).
worldThe world (or agent), from connectToHost.
options.durationHow long Sent stays in milliseconds. Default 2500.

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

Change it ​

  • Only failures: skip the 'sent' notes in a chat or in any other view in which the reply already confirms the delivery.
  • Calls to send that the webapp could not run: they add no message to world.messages. The promise of send rejects instead with an error whose code gives the reason ('failed' or 'too-big' for a file). Catch it where you call send and show a note in the same way (Errors and the person's controls).
  • At the top: use top with world.webapp.insets.top instead of bottom.

See also ​

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