Skip to content

SentToast ​

Una vista che non mostra la conversazione (un modulo, il tabellone di un gioco, una votazione) non dà alla persona nessun segno che il suo messaggio sia arrivato. SentToast mostra un breve avviso in fondo alla vista quando un messaggio della persona viene consegnato. L'avviso ha il titolo Sent, riporta il testo del messaggio (o "A picture" per un messaggio senza testo) e sparisce dopo duration millisecondi. Un messaggio fallito produce invece un avviso Not sent che resta sullo schermo con Retry e un pulsante di chiusura finché la persona non preme uno dei due.

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

L'agente finto fa fallire il primo messaggio che riceve (failNext: true). Premi Send a message e poi Retry.

Invece di avvolgere send, il componente si iscrive al mondo e osserva lo status dei messaggi con fromMe ('sending', poi 'sent' o 'failed'). Qualsiasi parte della tua vista che invia un messaggio (una MessageBox, una Grid o un QuestionForm) riceve quindi un avviso. I messaggi già presenti in world.messages quando il componente parte non ricevono nessun avviso. Retry chiama retry() sul messaggio fallito (Mostra se un messaggio è stato consegnato e Riprova un messaggio fallito).

L'avviso ha position: fixed e sta 16 pixel sopra il maggiore fra world.webapp.insets.bottom e world.webapp.keyboard. Per invertire i colori della pagina e restare visibile in entrambi i temi usa CanvasText come sfondo e Canvas come colore del testo. Gli screen reader annunciano ogni nuovo avviso perché il suo contenitore è una regione role="status" che resta nella pagina anche quando è vuota.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo (o l'agente), da useWorld.
duration2500Per quanti millisecondi resta Sent. Not sent resta finché la persona non riprova o lo chiude.

Parametri ​

sentToast(container, world, options) aggiunge a container la regione dell'avviso e si iscrive al mondo. In qualunque punto si trovi container, l'avviso resta fisso in fondo alla vista.

ParametroChe cos'è
containerL'elemento che riceve la regione (per esempio document.body).
worldIl mondo (o l'agente), da connectToHost.
options.durationPer quanti millisecondi resta Sent. Predefinito 2500.

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

Modificalo ​

  • Solo i fallimenti: salta gli avvisi 'sent' in una chat o in qualsiasi altra vista in cui è già la risposta a mostrare che il messaggio è arrivato.
  • Chiamate a send che la webapp non ha potuto eseguire: non aggiungono nessun messaggio a world.messages. La Promise di send viene invece rifiutata con un errore il cui code dà il motivo ('failed' o 'too-big' per un file). Intercettalo dove chiami send e mostra un avviso allo stesso modo (Gli errori e i controlli della persona).
  • In alto: usa top con world.webapp.insets.top al posto di bottom.

Vedi anche ​

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