Skip to content

Messaggi e domande ​

world.messages è la conversazione fra il mondo e la persona, ordinata dal messaggio più vecchio al più recente. Contiene i messaggi della persona, quelli del mondo e dei suoi membri, le note delle sue regole e le domande (i messaggi che portano un modulo). La tua vista mostra ogni messaggio insieme alle sue immagini, ai suoi file, ai media e ai grafici. Inoltre invia per conto della persona testo, immagini, file, domande e risposte e mostra lo stato di consegna di ogni messaggio.

I messaggi ​

A ogni cambiamento del mondo node.messages contiene la lista completa ordinata dal messaggio più vecchio al più recente. La lista qui sotto mostra ogni messaggio in modo diverso a seconda di chi l'ha inviato:

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

// A fake world that greets the person by name.
const arena = {
	name: 'Arena',
	onMessage: (message, world, person) => `Hello, ${person.name}! Welcome to the ${world.name}.`,
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			{/* The whole list, oldest first, with the id of each message as its key. */}
			<div>
				{world.messages.length === 0 && 'No messages yet.'}
				{world.messages.map((message) => <MessageItem key={message.id} message={message} />)}
			</div>
			<button onClick={() => world.send('hello')}>Say hello</button>
		</>
	);
}

// One message, drawn according to who sent it.
function MessageItem({ message }) {
	const time = new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
	let style = {};
	let words = `${message.from}: ${message.text ?? ''}`; // someone else in the world (an agent)
	if (message.fromMe) {
		// The person's own message, on the right.
		style = { textAlign: 'right' };
		words = `You: ${message.text ?? ''}`;
	} else if (message.isSystem) {
		// A note from the rules of the world, in the middle and quieter.
		style = { textAlign: 'center', fontStyle: 'italic' };
		words = message.text ?? '';
	}
	return (
		<p style={style} title={time}>
			{words}
			{message.image && <><br /><img src={message.image} alt="" style={{ maxHeight: 80 }} /></>}
		</p>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that greets the person by name.
const arena = {
	name: 'Arena',
	onMessage: (message, world, person) => `Hello, ${person.name}! Welcome to the ${world.name}.`,
};

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

const list = document.createElement('div');
const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(list, button);

// One message, drawn according to who sent it.
function messageItem(message) {
	const item = document.createElement('p');
	const time = new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
	if (message.fromMe) {
		// The person's own message, on the right.
		item.style.textAlign = 'right';
		item.textContent = `You: ${message.text ?? ''}`;
	} else if (message.isSystem) {
		// A note from the rules of the world, in the middle and quieter.
		item.style.textAlign = 'center';
		item.style.fontStyle = 'italic';
		item.textContent = message.text ?? '';
	} else {
		// Someone else in the world (an agent), with their name and words.
		item.textContent = `${message.from}: ${message.text ?? ''}`;
	}
	item.title = time;
	if (message.image) {
		const picture = document.createElement('img');
		picture.src = message.image;
		picture.alt = '';
		picture.style.maxHeight = '80px';
		item.append(document.createElement('br'), picture);
	}
	return item;
}

// Called at once, then after every change of the world, with the whole list oldest first.
world.subscribe((node) => {
	if (node.messages.length === 0) {
		list.textContent = 'No messages yet.';
		return;
	}
	list.replaceChildren(...node.messages.map(messageItem));
});
Live, on a fake world
Open

Ogni messaggio ha questi campi (GuiMessage):

CampoChe cos'è
idIdentificatore stabile per tutta la vita del messaggio. Usalo come key in React.
textIl testo del messaggio. È null per un messaggio senza testo come un'immagine da sola.
imageURL o data URI della prima immagine per img.src. È null quando il messaggio non ha immagini.
imagesTutte le immagini in ordine.
filesI file allegati come { name, type, url }.
mediaVideo, audio, PDF e link.
chartsI dati dei grafici.
fromIl nome di chi ha scritto il messaggio.
fromIdL'id del membro o del mondo che ha scritto il messaggio. Per la persona è null (Persone e ruoli).
timeIl momento del messaggio in millisecondi dall'epoca Unix. Date.now() usa la stessa unità.
fromMetrue per i messaggi della persona.
isSystemtrue per le note delle regole del mondo.

Questi campi esistono solo su alcuni messaggi:

CampoSuChe cos'è
statusi messaggi della persona'sending', 'sent' o 'failed'.
retry()i messaggi della personaInvia di nuovo un messaggio fallito.
formuna domandaIl modulo da compilare.
isAnswereduna domandatrue dopo che la domanda ha avuto risposta.
answer(values)una domandaRisponde alla domanda.
valuesuna rispostaI valori della risposta indicizzati per nome del campo.
answersuna rispostaL'id della domanda a cui risponde.

Una lista corretta segue quattro regole:

  • Usa id come chiave e mai l'indice. loadMore aggiunge in testa i messaggi più vecchi e sposta tutti gli indici senza cambiare nessun id.
  • text può essere null. Leggilo come message.text ?? '' e mostra immagini, file, media e grafici dai loro campi (più avanti).
  • Non usare mai innerHTML. Dato che il testo arriva da altri e non è affidabile, assegnalo a textContent o lascialo mostrare a React.
  • time è un numero. new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) lo formatta secondo le impostazioni locali della persona.

Immagini, file, video e grafici ​

I contenuti diversi dal testo hanno campi propri: images, files, charts e media per video, audio, PDF e link. In questo esempio un agente finto risponde con un elemento di ogni tipo:

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

// A small picture as an inline SVG, because a picture in a message is an image source.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="teal"/></svg>')}`;

// A fake agent whose answer holds words, a picture, a file, a video and a chart.
const coach = {
	name: 'Coach',
	onMessage: () => ({
		text: 'Here is your week',
		images: [PICTURE],
		files: [{ name: 'plan.txt', type: 'text/plain', url: `data:text/plain;base64,${btoa('Monday: run 5 km')}` }],
		media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
		charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
	}),
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;
	return (
		<>
			<button onClick={() => agent.send('My week, please')}>Show my week</button>
			<div>
				{agent.messages.map((message) => <MessageItem key={message.id} message={message} />)}
			</div>
		</>
	);
}

// One message, with its words and then its pictures, files, media and charts, each in its own field.
// An older webapp does not give these fields, and `?? []` covers that case.
function MessageItem({ message }) {
	return (
		<div style={{ marginBottom: 12 }}>
			<div>{message.fromMe ? 'You' : message.from}: {message.text ?? ''}</div>
			{(message.images ?? []).map((image, index) => <img key={index} src={image} alt="" />)}
			{(message.files ?? []).map((file, index) => (
				// The file of an agent arrives without a name and needs words of your own.
				<a key={index} href={file.url} download={file.name ?? 'file'}>Download {file.name ?? 'the file'} ({file.type})</a>
			))}
			{(message.media ?? []).map((media, index) => (
				// A link loads nothing until the person opens it.
				<div key={index}><a href={media.url} target="_blank">{media.title ?? media.alt} ({media.type})</a></div>
			))}
			{(message.charts ?? []).map((chart, index) => (
				<div key={index}>
					<div>{chart.alt} ({chart.kind} chart)</div>
					{chart.series.map((series) => (
						<div key={series.label}>{series.label}: {series.points.map(([x, y]) => `${x} ${y}`).join(' · ')}</div>
					))}
				</div>
			))}
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A small picture as an inline SVG, because a picture in a message is an image source.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="teal"/></svg>')}`;

// A fake agent whose answer holds words, a picture, a file, a video and a chart.
const coach = {
	name: 'Coach',
	onMessage: () => ({
		text: 'Here is your week',
		images: [PICTURE],
		files: [{ name: 'plan.txt', type: 'text/plain', url: `data:text/plain;base64,${btoa('Monday: run 5 km')}` }],
		media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
		charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
	}),
};

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

const button = document.createElement('button');
button.textContent = 'Show my week';
button.onclick = () => agent.send('My week, please');
const list = document.createElement('div');
document.body.append(button, list);

// Adds a line of text to an element.
function addLine(parent, text) {
	const line = document.createElement('div');
	line.textContent = text;
	parent.append(line);
	return line;
}

// One message, with its words and then its pictures, files, media and charts, each in its own field.
// An older webapp does not give these fields, and `?? []` covers that case.
function messageItem(message) {
	const item = document.createElement('div');
	item.style.marginBottom = '12px';
	addLine(item, `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`);
	for (const image of message.images ?? []) {
		const picture = document.createElement('img');
		picture.src = image;
		picture.alt = '';
		item.append(picture);
	}
	for (const file of message.files ?? []) {
		// The file of an agent arrives without a name and needs words of your own.
		const link = document.createElement('a');
		link.href = file.url;
		link.download = file.name ?? 'file';
		link.textContent = `Download ${file.name ?? 'the file'} (${file.type})`;
		item.append(link);
	}
	for (const media of message.media ?? []) {
		// A link loads nothing until the person opens it.
		const link = document.createElement('a');
		link.href = media.url;
		link.target = '_blank';
		link.textContent = `${media.title ?? media.alt} (${media.type})`;
		addLine(item, '').append(link);
	}
	for (const chart of message.charts ?? []) {
		addLine(item, `${chart.alt} (${chart.kind} chart)`);
		for (const series of chart.series) {
			addLine(item, `${series.label}: ${series.points.map(([x, y]) => `${x} ${y}`).join(' · ')}`);
		}
	}
	return item;
}

// Called at once, then after every change.
agent.subscribe((node) => {
	list.replaceChildren(...node.messages.map(messageItem));
});
Live, on a fake world
Open

text non ripete gli allegati. Mostra gli allegati da media e charts e mostra text così com'è. Un contenuto di un tipo che il kit non gestisce ancora arriva come testo semplice in text. Una vista che mostra sempre text non lo perde quindi mai.

Ognuno dei quattro campi si mostra in un modo suo:

  • images contiene URL o data URI che vanno ognuno in un <img> suo. Il primo è anche in image per le viste che mostrano una sola immagine per messaggio.
  • files contiene oggetti { name, type, url } il cui url è un data URI che funziona come href di un <a download>. I file inviati da un agente hanno name: null e richiedono un'etichetta tua. Dopo un ricaricamento della webapp un file inviato dalla persona conserva il suo name ma il suo url diventa null.
  • media contiene risorse remote. url è l'indirizzo, type è un tipo MIME o un tipo di provider ('video/mp4', 'audio/mpeg', 'application/pdf', 'video/youtube', ...) e title e alt descrivono la risorsa a parole. Mostra video e audio in un <video> o in un <audio> con preload="none" per non caricare niente prima della riproduzione. Un tipo 'image/...' va in un <img> e ogni altro tipo, PDF compresi, diventa un link.
  • charts contiene dati con un kind ('bar', 'line' o 'pie'), una series di punti [x, y] e una descrizione alt. Disegna i dati con codice tuo o con una libreria di grafici (Chart) e usa alt come etichetta accessibile del disegno.
js
// A video plays in the page; nothing loads before the person presses play.
const video = document.createElement('video');
video.src = media.url;
video.controls = true;
video.preload = 'none';
video.setAttribute('aria-label', media.alt);

Attenzione

Monta un player di YouTube o di Vimeo ('video/youtube', 'video/vimeo') solo al clic. Il player è una pagina del provider incorporata nella tua. Appena viene montato carica i suoi script e può salvare cookie. Mostra il titolo e un pulsante di riproduzione come fa la webapp nella sua conversazione e sostituiscili con il player quando la persona fa clic.

I quattro campi esistono dalla versione della webapp di novembre 2026 e mancano nelle webapp più vecchie come un'app per telefono non ancora aggiornata. Leggili con valori di default come message.images ?? [] e ripiega su image e text. Tipi › GuiMessage descrive ogni campo.

Chi ha inviato che cosa ​

I messaggi vengono da tre tipi di mittente e di solito una vista mostra ciascun tipo in modo diverso:

  • La persona (fromMe: true). from contiene una stringa fissa e mai il nickname della persona (quello sta in world.me). Controlla fromMe e mostra un'etichetta tua come "Tu". Solo questi messaggi hanno uno status.
  • Le regole del mondo (isSystem: true), per esempio "Inizia il round 2" o "Tocca a te". Le note, il cui from è il nome del mondo, portano testo, media, grafici e domande ma mai immagini o file. Di solito le viste le mostrano con meno risalto della conversazione. In un mondo finto ogni risposta di onMessage e di onAction è una nota a meno che il suo from nomini un membro del mondo.
  • Tutti gli altri, il cui nome sta in from: un agente, un altro membro del mondo o l'agente stesso nella vista di un agente.

Confrontando fromId con members trovi il membro che ha scritto un messaggio. Quando showsSenders è false il mondo chiede alla vista di non mostrare i mittenti (Chi l'ha scritto). La ricetta Raggruppa i messaggi per mittente raggruppa i messaggi consecutivi di uno stesso mittente.

Inviare un testo ​

world.send(text) invia un testo per conto della persona. Il messaggio compare subito in world.messages con status: 'sending' e la vista non deve aggiungerlo da sé. Poi send si risolve con l'esito:

RisultatoSignificatoChe cosa fa la vista
'sent'Consegnato.Niente. Il messaggio mostra già 'sent'.
'failed'Non consegnato. Il messaggio resta nella lista con status: 'failed'.Niente. La lista offre un nuovo tentativo (più avanti).
'not-allowed'Il testo era vuoto oppure le regole ora non accettano un messaggio, per esempio perché non è il turno della persona. Nella lista non è stato aggiunto niente.Rimetti il testo nella casella e mostra il motivo.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world that answers every message.
const arena = {
	name: 'Arena',
	onMessage: (message) => `Got it: ${message.text}`,
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{message.fromMe ? 'You' : message.from}: {message.text}
						{/* The person's messages have a status: 'sending', 'sent' or 'failed'. */}
						{message.fromMe && ` (${message.status})`}
					</li>
				))}
			</ul>
			<MessageBox world={world} />
		</>
	);
}

function MessageBox({ world }) {
	const [text, setText] = useState('');
	const [notice, setNotice] = useState('');

	async function handleSubmit(event) {
		event.preventDefault();
		const words = text.trim();
		if (!words) return;
		setText('');
		// 'sent' and 'failed' both leave the message in the list, with its status.
		// 'not-allowed' means the rules did not take it, and the view gives the person their words back.
		const result = await world.send(words);
		if (result === 'not-allowed') {
			setText(words);
			setNotice('You cannot send now.');
		} else {
			setNotice('');
		}
	}

	return (
		<>
			<form onSubmit={handleSubmit}>
				<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Write a message" />
				{/* The rules say when the person may send (their turn, for example). */}
				<button disabled={!world.canSend}>Send</button>
			</form>
			<p>{notice}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that answers every message.
const arena = {
	name: 'Arena',
	onMessage: (message) => `Got it: ${message.text}`,
};

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

const list = document.createElement('ul');
const form = document.createElement('form');
const input = document.createElement('input');
const button = document.createElement('button');
const notice = document.createElement('p');
input.placeholder = 'Write a message';
button.textContent = 'Send';
form.append(input, button);
document.body.append(list, form, notice);

form.onsubmit = async (event) => {
	event.preventDefault();
	const text = input.value.trim();
	if (!text) return;
	input.value = '';
	// 'sent' and 'failed' both leave the message in the list, with its status.
	// 'not-allowed' means the rules did not take it, and the view gives the person their words back.
	const result = await world.send(text);
	if (result === 'not-allowed') {
		input.value = text;
		notice.textContent = 'You cannot send now.';
	} else {
		notice.textContent = '';
	}
};

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		const who = message.fromMe ? 'You' : message.from;
		// The person's messages have a status: 'sending', 'sent' or 'failed'.
		item.textContent = message.fromMe ? `${who}: ${message.text} (${message.status})` : `${who}: ${message.text}`;
		return item;
	}));
	// The rules say when the person may send (their turn, for example).
	button.disabled = !node.canSend;
});
Live, on a fake world
Open
  • Disattiva il pulsante mentre canSend è false. canSend segue le regole ed è false anche mentre un messaggio è in corso. Questo impedisce gli invii doppi (Le azioni delle regole).
  • Dentro la webapp send può anche essere rifiutata: con 'failed' quando la webapp non riesce a completare la chiamata e con 'too-big' per un file oltre i 20 MB. Errori e controlli della persona mostra come intercettare l'errore.

Consegna e nuovo tentativo ​

I messaggi della persona hanno uno status che vale 'sending' mentre sono in corso e poi diventa 'sent' o 'failed'. Su un messaggio fallito retry() invia di nuovo lo stesso messaggio senza aggiungere voci alla lista e si risolve con gli stessi valori di send.

Questo mondo finto fa fallire apposta il primo messaggio (failNext: true):

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

// A fake world whose first message fails (`failNext`), to let you try a retry.
const arena = {
	name: 'Arena',
	failNext: true,
	onMessage: (message) => `Got it: ${message.text}`,
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{message.fromMe ? `You: ${message.text} (${message.status}) ` : `${message.from}: ${message.text}`}
						{/* A failed message can be sent again, as the same message and not a new one. */}
						{message.status === 'failed' && <button onClick={() => message.retry()}>Retry</button>}
					</li>
				))}
			</ul>
			<button onClick={() => world.send('hello')}>Say hello</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world whose first message fails (`failNext`), to let you try a retry.
const arena = {
	name: 'Arena',
	failNext: true,
	onMessage: (message) => `Got it: ${message.text}`,
};

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

const list = document.createElement('ul');
const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(list, button);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		if (!message.fromMe) {
			item.textContent = `${message.from}: ${message.text}`;
			return item;
		}
		item.textContent = `You: ${message.text} (${message.status}) `;
		// A failed message can be sent again, as the same message and not a new one.
		if (message.status === 'failed') {
			const retry = document.createElement('button');
			retry.textContent = 'Retry';
			retry.onclick = () => message.retry();
			item.append(retry);
		}
		return item;
	}));
});
Live, on a fake world
Open

Mostra Riprova solo quando status è 'failed'. Le ricette Mostra se un messaggio è stato consegnato e Riprova un messaggio fallito mostrano altri modi di mostrare lo stato della consegna.

Inviare un'immagine ​

world.send({ image, text }) invia un'immagine con un testo facoltativo. image è un URL o, più spesso, un data URI che viene da un canvas (canvas.toDataURL('image/jpeg', 0.8)), da un file scelto dalla persona o dalla fotocamera.

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

// A fake world that likes pictures.
const gallery = {
	name: 'Gallery',
	onMessage: (message) => (message.image ? 'What a nice picture!' : 'Send me a picture.'),
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<PictureSender world={world} />
			<div>
				{world.messages.map((message) => (
					<p key={message.id}>
						{message.fromMe ? 'You' : message.from}: {message.text ?? ''}
						{message.image && <img src={message.image} alt={message.text ?? 'A picture'} style={{ display: 'block' }} />}
					</p>
				))}
			</div>
		</>
	);
}

function PictureSender({ world }) {
	const canvasRef = useRef(null);

	// The picture to send, drawn here on a canvas. A photo or a file works the same way.
	useEffect(() => {
		const context = canvasRef.current.getContext('2d');
		context.fillStyle = 'crimson';
		context.fillRect(0, 0, 60, 60);
	}, []);

	// A picture is an image source (a data URI), with words that go with it.
	function sendPicture() {
		world.send({ image: canvasRef.current.toDataURL('image/png'), text: 'A red square' });
	}

	return (
		<>
			<canvas ref={canvasRef} width={60} height={60} />
			<button onClick={sendPicture}>Send a picture</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that likes pictures.
const gallery = {
	name: 'Gallery',
	onMessage: (message) => (message.image ? 'What a nice picture!' : 'Send me a picture.'),
};

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

// The picture to send, drawn here on a canvas. A photo or a file works the same way.
const canvas = document.createElement('canvas');
canvas.width = 60;
canvas.height = 60;
const context = canvas.getContext('2d');
context.fillStyle = 'crimson';
context.fillRect(0, 0, 60, 60);

const button = document.createElement('button');
button.textContent = 'Send a picture';
// A picture is an image source (a data URI), with words that go with it.
button.onclick = () => world.send({ image: canvas.toDataURL('image/png'), text: 'A red square' });
const list = document.createElement('div');
document.body.append(canvas, button, list);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('p');
		item.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
		if (message.image) {
			const picture = document.createElement('img');
			picture.src = message.image;
			picture.alt = message.text ?? 'A picture';
			picture.style.display = 'block';
			item.append(picture);
		}
		return item;
	}));
});
Live, on a fake world
Open

Per inviare un'immagine scelta dalla persona, leggi il file come data URI:

js
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*';
picker.onchange = () => {
  const file = picker.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = () => world.send({ image: reader.result, text: file.name });
  reader.readAsDataURL(file);
};

Una foto scattata col telefono può pesare diversi megabyte. Riducila prima su un canvas (una larghezza di 1.000 pixel basta per la maggior parte dei mondi) e invia canvas.toDataURL('image/jpeg', 0.8) al posto del file originale. La fotocamera è trattata in La fotocamera e il resto del browser e nella ricetta Invia una foto dalla fotocamera.

Inviare un file ​

world.send({ file, text }) invia un file di al massimo 20 MB. Passa così com'è il File di un input o di un trascinamento e lascia a send la lettura del contenuto.

js
const picker = document.createElement('input');
picker.type = 'file';
picker.onchange = async () => {
  const file = picker.files[0];
  if (!file) return;
  try {
    await world.send({ file, text: file.name });
  } catch (error) {
    if (error.code === 'too-big') showError('Pick a file under 20 MB.');
  }
};
  • Consegnato non vuol dire letto. Il risultato 'sent' vuol dire che il mondo ha ricevuto il file. Lo leggono solo gli agenti con un input di tipo file e gli altri lo ignorano senza errori. Dato che è il proprietario del mondo a decidere quali agenti hanno un input di tipo file, chiediglielo prima di offrire un pulsante per i file.
  • Un'immagine o un file per messaggio. Un messaggio con tutti e due si risolve con 'failed' e non invia niente.
  • Un file oltre i 20 MB fa rifiutare send con 'too-big' prima che venga inviato qualsiasi cosa.
  • Una webapp precedente all'invio dei file fa rifiutare send con 'not-allowed-verb' e non invia niente. Quando arriva questo codice nascondi il pulsante per i file.

Il messaggio della persona ha subito il file in files. send › Inviare un file ha un esempio dal vivo e tutti i dettagli.

Inviare una domanda ​

world.send({ text, form }) invia una domanda per conto della persona. Il suo modulo ha la stessa forma dei moduli nelle domande del mondo (più avanti):

js
await world.send({
  text: 'Which day suits you?',
  form: { fields: [{ name: 'day', type: 'select', options: ['Monday', 'Tuesday'] }] },
});

Il messaggio compare nella lista con il suo form e prende isAnswered: true quando chi lo riceve risponde. Dato che il modulo viene inviato anche come testo semplice, un mondo o un agente che non legge i moduli capisce comunque la domanda.

Le domande del mondo ​

Una domanda è un messaggio con un form. La tua vista mostra il modulo e message.answer(values) invia la risposta della persona.

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

// A fake world that asks a question, then replies to the answer.
const arena = {
	name: 'Arena',
	onMessage: (message) => {
		// An answer arrives as a message with `values`, by field name.
		if (message.values) return `You go ${message.values.direction}.`;
		return {
			text: 'Which way?',
			form: { fields: [{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right'] }] },
		};
	},
};

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

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

	// The question still open is the newest one from the world with a form that is not answered yet.
	const question = world.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
	return (
		<>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{message.values
							? `You answered: ${Object.values(message.values).join(', ')}`
							: `${message.fromMe ? 'You' : message.from}: ${message.text}`}
					</li>
				))}
			</ul>
			<button onClick={() => world.send('start')}>Start the game</button>
			{/* The key keeps the person's choice while the question stays the same. */}
			{question && <QuestionForm key={question.id} message={question} />}
		</>
	);
}

// The form of a question, with one field per field of `message.form`.
function QuestionForm({ message }) {
	function handleSubmit(event) {
		event.preventDefault();
		message.answer(Object.fromEntries(new FormData(event.target)));
	}

	return (
		<form onSubmit={handleSubmit}>
			{message.form.fields.map((field) => (
				<label key={field.name}>
					{field.label ?? field.name}{' '}
					{field.type === 'select' ? (
						<select name={field.name}>
							{/* Options can be plain strings or { value, label }. */}
							{(field.options ?? []).map((option) => {
								const value = typeof option === 'string' ? option : option.value;
								return <option key={value} value={value}>{typeof option === 'string' ? option : option.label}</option>;
							})}
						</select>
					) : (
						<input name={field.name} type={field.type === 'number' ? 'number' : 'text'} />
					)}
				</label>
			))}{' '}
			<button>Answer</button>
		</form>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that asks a question, then replies to the answer.
const arena = {
	name: 'Arena',
	onMessage: (message) => {
		// An answer arrives as a message with `values`, by field name.
		if (message.values) return `You go ${message.values.direction}.`;
		return {
			text: 'Which way?',
			form: { fields: [{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right'] }] },
		};
	},
};

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

const list = document.createElement('ul');
const start = document.createElement('button');
start.textContent = 'Start the game';
start.onclick = () => world.send('start');
const formPlace = document.createElement('div');
document.body.append(list, start, formPlace);

// Builds the form of a question, with one field per field of `message.form`.
function questionForm(message) {
	const form = document.createElement('form');
	for (const field of message.form.fields) {
		const label = document.createElement('label');
		const input = document.createElement(field.type === 'select' ? 'select' : 'input');
		input.name = field.name;
		if (field.type === 'number') input.type = 'number';
		// Options can be plain strings or { value, label }.
		for (const option of field.options ?? []) {
			const choice = document.createElement('option');
			choice.value = typeof option === 'string' ? option : option.value;
			choice.textContent = typeof option === 'string' ? option : option.label;
			input.append(choice);
		}
		label.append(`${field.label ?? field.name} `, input);
		form.append(label);
	}
	const button = document.createElement('button');
	button.textContent = 'Answer';
	form.append(' ', button);
	form.onsubmit = (event) => {
		event.preventDefault();
		message.answer(Object.fromEntries(new FormData(form)));
	};
	return form;
}

let shownQuestionId = null;
// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		item.textContent = message.values
			? `You answered: ${Object.values(message.values).join(', ')}`
			: `${message.fromMe ? 'You' : message.from}: ${message.text}`;
		return item;
	}));
	// The question still open is the newest one from the world with a form that is not answered yet.
	const question = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
	// Build the form only when the question changes, to keep what the person chose through other changes.
	if ((question?.id ?? null) === shownQuestionId) return;
	shownQuestionId = question?.id ?? null;
	formPlace.replaceChildren(...(question ? [questionForm(question)] : []));
});
Live, on a fake world
Open

Il modulo. message.form.fields è la lista dei campi:

CampoChe cos'è
nameLa chiave del valore in values.
type'select', 'text', 'number' o un altro tipo che il mondo usa.
labelL'etichetta da mostrare. Se manca, usa name.
optionsLe opzioni di una scelta come { value, label }. Le stringhe semplici sono accettate solo nei moduli che invii tu.

La risposta. message.answer(values) prende un oggetto indicizzato per nome del campo come { direction: 'right' } e si risolve come send:

  • a una domanda si risponde una volta sola. Dopo la risposta isAnswered è true e answer si risolve con 'not-allowed'
  • answer si risolve con 'not-allowed' quando values non contiene nessun campo del modulo
  • la risposta compare nella lista come un messaggio della persona che contiene tre cose: i valori in values, una versione testuale della risposta per le viste che mostrano solo testo e l'id della domanda in answers.

Dato che FormData restituisce stringhe, converti un campo 'number' con Number(value).

La domanda aperta è la domanda più recente del mondo che non ha ancora risposta:

js
const open = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);

Tieni montato il modulo finché la domanda resta la stessa. Un modulo ricostruito a ogni cambiamento del mondo (un orologio, un punteggio) perde quello che la persona ha inserito. In React imposta key={question.id} sul modulo. Nella versione in JavaScript semplice l'esempio lo ricostruisce solo quando cambia l'id della domanda aperta.

La ricetta Rispondi a una domanda con un modulo e il componente QuestionForm gestiscono altri tipi di campo.

I messaggi più vecchi: loadMore ​

world.messages comincia con la parte recente della conversazione. await world.loadMore() aggiunge in testa i messaggi più vecchi e si risolve con il numero dei messaggi aggiunti oppure con 0 quando non ce ne sono altri. Un mondo finto non ha messaggi più vecchi e si risolve sempre con 0.

js
const older = document.createElement('button');
older.textContent = 'Show older messages';
older.onclick = async () => {
  const added = await world.loadMore();
  if (added === 0) older.remove(); // nothing older: no need for the button
};

I messaggi aggiunti arrivano attraverso subscribe come qualsiasi altro cambiamento. La ricetta Carica i messaggi precedenti tiene fermi i messaggi che la persona sta leggendo mentre quelli più vecchi vengono aggiunti sopra.

A che cosa stare attenti ​

  • Non aggiungere messaggi da te. Il messaggio della persona è in world.messages appena chiami send.
  • Usa id come chiave. Gli indici cambiano quando arrivano in testa i messaggi più vecchi.
  • text può essere null e non è affidabile. Non metterlo mai in innerHTML.
  • text non contiene gli allegati. Leggi immagini, file, media e grafici dai loro campi con ?? [] per le webapp più vecchie.
  • Non modificare la lista. filter restituisce un array nuovo ma sort lavora sull'array stesso e richiede prima una copia ([...node.messages]).
  • I gestori di eventi leggono world.get().messages invece di un valore catturato prima (Pensare per viste).

Prossimi passi ​

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