Skip to content

Parla con il mondo ​

La persona scrive al mondo e il mondo risponde con messaggi suoi. Ora la vista mostra la conversazione e aggiunge una casella di testo con un pulsante Send.

Il mondo risponde ​

Un mondo finto risponde attraverso onMessage. Il kit chiama questa funzione con ogni messaggio della persona e trasforma la stringa restituita nella risposta del mondo:

js
onMessage: (message) => {
  const word = message.text.trim().toLowerCase();
  if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
  return `The island does not know “${message.text}”. Try: look.`;
},

Un mondo vero risponde secondo le sue regole. La vista mostra qualunque cosa arrivi in messages e non dipende dal modo in cui la risposta è stata prodotta.

I messaggi ​

world.messages è la conversazione fra la persona e il mondo ordinata dal messaggio più vecchio al più recente. La vista legge cinque campi di ogni messaggio:

  • id: un identificatore stabile da usare come key in React.
  • text: il testo del messaggio oppure null per un messaggio senza testo.
  • fromMe: true per i messaggi della persona.
  • from: il nome di chi ha inviato il messaggio. Una risposta del mondo stesso ha 'Treasure Island' in from.
  • isSystem: true per le note che le regole del mondo scrivono nella conversazione. Le risposte di questo mondo finto sono note di questo tipo.

La vista etichetta come "You" i messaggi della persona e li allinea a destra:

jsx
<li style={{ margin: '6px 0', textAlign: message.fromMe ? 'right' : 'left' }}>
  <span style={{ /* a bubble */ }}>
    {message.fromMe ? 'You' : message.from}: {message.text}
  </span>
</li>

Invia ​

world.send(text) invia un messaggio per conto della persona e lo aggiunge subito a messages. La risposta del mondo arriva più tardi come un messaggio in più che la vista mostra come tutti gli altri.

jsx
function handleSubmit(event) {
  event.preventDefault();
  if (!text.trim()) return;
  world.send(text);
  setText('');
}

world.canSend è false mentre le regole del mondo rifiutano i messaggi della persona e mentre un messaggio è in corso. In entrambi i casi disattiva il pulsante Send e lascia attivo il campo di testo (Disattiva la casella dei messaggi quando la persona non può inviare spiega il motivo).

Ridisegna la lista solo quando è cambiata ​

Su quest'isola la marea cambia il mondo ogni secondo e il listener di subscribe in JavaScript semplice gira a ognuno di questi cambiamenti. Se la lista venisse ricostruita ogni secondo, i pulsanti e i moduli che i passi successivi ci mettono dentro perderebbero il focus e quello che la persona ha scritto o selezionato. Per questo la vista conserva gli id dei messaggi che ha mostrato e ricostruisce la lista solo quando cambiano:

js
const key = JSON.stringify(node.messages.map((message) => message.id));
if (key === shown) return;
shown = key;
list.replaceChildren(...node.messages.map(messageItem));

In React questo controllo non serve perché React aggiorna solo i nodi del DOM il cui output è cambiato.

Il codice ​

Le righe nuove sono evidenziate. Scrivi look nella casella e invialo.

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

// A fake world to build with, a small treasure hunt that needs no account and no network.

// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
	['🌊', '🌊', '🌴', '🌊', '🌊'],
	['🌊', '🌴', '·', '⛰️', '🌊'],
	['🌴', '·', '·', '·', '🌴'],
	['🌊', '·', '⛰️', '·', '🌊'],
	['🌊', '🌊', '·', '🌴', '🌊'],
];

const island = {
	name: 'Treasure Island',
	profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
	now: { text: 'The hunt is on.' },
	// What the world shows, by name.
	data: {
		map: MAP,
		// Where you are on the map.
		position: { row: 3, column: 1 },
		// The tide rises and falls: a function of time gives a new value every second.
		tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
	},
	// The world reads what the person writes and answers.
	onMessage: (message) => {
		const word = message.text.trim().toLowerCase();
		if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
		return `The island does not know “${message.text}”. Try: look.`;
	},
};

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

	// The three states of every view: it failed, it is connecting, it is here.
	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	return (
		<main>
			<Header world={world} />
			<IslandMap data={world.data} />
			<Conversation world={world} />
		</main>
	);
}

// The name of the world, what it is about and what is happening now.
function Header({ world }) {
	return (
		<header>
			<h1>{world.name}</h1>
			<p>{world.profile.description}</p>
			<p>
				Now: {world.now?.text} The world is {world.status}.
			</p>
		</header>
	);
}

// The island from the data of the world: one square per cell, you on yours, and the tide.
function IslandMap({ data }) {
	const { map, position, tide } = data;
	// A name of `data` can be missing for a moment while the world sends it.
	if (!map || !position) return <p>The map is on its way…</p>;

	return (
		<section>
			<div
				role="img"
				aria-label="Map of the island"
				style={{ display: 'grid', gridTemplateColumns: `repeat(${map[0].length}, 44px)`, gap: 2 }}
			>
				{map.map((row, rowIndex) =>
					row.map((ground, columnIndex) => {
						const isHere = rowIndex === position.row && columnIndex === position.column;
						return (
							<div
								key={`${rowIndex}-${columnIndex}`}
								style={{
									height: 44,
									display: 'grid',
									placeItems: 'center',
									fontSize: 24,
									borderRadius: 6,
									background: isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)',
								}}
							>
								{isHere ? '🧍' : ground}
							</div>
						);
					}),
				)}
			</div>
			<p>
				Tide <meter min={0} max={100} value={tide} /> {tide}%
			</p>
		</section>
	);
}

// The conversation with the world, oldest first, and a box to write to it.
function Conversation({ world }) {
	const [text, setText] = useState('');

	function handleSubmit(event) {
		event.preventDefault();
		if (!text.trim()) return;
		// Sends as the person. The world reads it and answers with a message.
		world.send(text);
		setText('');
	}

	return (
		<section>
			<h2>Messages</h2>
			{world.messages.length === 0 && <p>No messages yet. Write “look” to the world.</p>}
			<ul style={{ listStyle: 'none', padding: 0 }}>
				{world.messages.map((message) => (
					<Message key={message.id} message={message} />
				))}
			</ul>
			<form onSubmit={handleSubmit} style={{ display: 'flex', gap: 8 }}>
				<input
					value={text}
					onChange={(event) => setText(event.target.value)}
					placeholder="Write to the world"
					aria-label="Write to the world"
					style={{ flex: 1 }}
				/>
				{/* canSend: the rules of the world let the person send now. */}
				<button disabled={!world.canSend}>Send</button>
			</form>
		</section>
	);
}

// One message: who said it and what. The person's own are on the right.
function Message({ message }) {
	return (
		<li style={{ margin: '6px 0', textAlign: message.fromMe ? 'right' : 'left' }}>
			<span style={{ display: 'inline-block', padding: '6px 10px', borderRadius: 10, background: 'rgba(127, 127, 127, 0.15)' }}>
				{message.fromMe ? 'You' : message.from}: {message.text}
			</span>
		</li>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world to build with, a small treasure hunt that needs no account and no network.

// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
	['🌊', '🌊', '🌴', '🌊', '🌊'],
	['🌊', '🌴', '·', '⛰️', '🌊'],
	['🌴', '·', '·', '·', '🌴'],
	['🌊', '·', '⛰️', '·', '🌊'],
	['🌊', '🌊', '·', '🌴', '🌊'],
];

const island = {
	name: 'Treasure Island',
	profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
	now: { text: 'The hunt is on.' },
	// What the world shows, by name.
	data: {
		map: MAP,
		// Where you are on the map.
		position: { row: 3, column: 1 },
		// The tide rises and falls: a function of time gives a new value every second.
		tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
	},
	// The world reads what the person writes and answers.
	onMessage: (message) => {
		const word = message.text.trim().toLowerCase();
		if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
		return `The island does not know “${message.text}”. Try: look.`;
	},
};

// The page: one element that holds the whole view.
const page = document.createElement('main');
page.textContent = 'Connecting…';
document.body.append(page);

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: island } });
page.textContent = '';
header(page, world);
islandMap(page, world);
conversation(page, world);

// The name of the world, what it is about and what is happening now.
function header(container, world) {
	const title = document.createElement('h1');
	const about = document.createElement('p');
	const now = document.createElement('p');
	container.append(title, about, now);

	// Called at once, then after every change of the world.
	return world.subscribe((node) => {
		title.textContent = node.name;
		about.textContent = node.profile.description ?? '';
		now.textContent = `Now: ${node.now?.text ?? ''} The world is ${node.status}.`;
	});
}

// The island from the data of the world: one square per cell, you on yours, and the tide.
function islandMap(container, world) {
	const grid = document.createElement('div');
	grid.setAttribute('role', 'img');
	grid.setAttribute('aria-label', 'Map of the island');
	grid.style.cssText = 'display: grid; gap: 2px';
	const tide = document.createElement('p');
	const meter = document.createElement('meter');
	meter.min = 0;
	meter.max = 100;
	const level = document.createElement('span');
	tide.append('Tide ', meter, level);
	container.append(grid, tide);

	return world.subscribe((node) => {
		const { map, position } = node.data;
		// A name of `data` can be missing for a moment while the world sends it.
		if (!map || !position) {
			grid.textContent = 'The map is on its way…';
			return;
		}
		grid.style.gridTemplateColumns = `repeat(${map[0].length}, 44px)`;
		const cells = [];
		map.forEach((row, rowIndex) => {
			row.forEach((ground, columnIndex) => {
				const isHere = rowIndex === position.row && columnIndex === position.column;
				const cell = document.createElement('div');
				cell.style.cssText = 'height: 44px; display: grid; place-items: center; font-size: 24px; border-radius: 6px';
				cell.style.background = isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)';
				cell.textContent = isHere ? '🧍' : ground;
				cells.push(cell);
			});
		});
		grid.replaceChildren(...cells);
		meter.value = node.data.tide;
		level.textContent = ` ${node.data.tide}%`;
	});
}

// The conversation with the world, oldest first, and a box to write to it.
function conversation(container, world) {
	const heading = document.createElement('h2');
	heading.textContent = 'Messages';
	const empty = document.createElement('p');
	empty.textContent = 'No messages yet. Write “look” to the world.';
	const list = document.createElement('ul');
	list.style.cssText = 'list-style: none; padding: 0';
	const form = document.createElement('form');
	form.style.cssText = 'display: flex; gap: 8px';
	const input = document.createElement('input');
	input.placeholder = 'Write to the world';
	input.setAttribute('aria-label', 'Write to the world');
	input.style.flex = '1';
	const send = document.createElement('button');
	send.textContent = 'Send';
	form.append(input, send);
	container.append(heading, empty, list, form);

	form.onsubmit = (event) => {
		event.preventDefault();
		if (!input.value.trim()) return;
		// Sends as the person. The world reads it and answers with a message.
		world.send(input.value);
		input.value = '';
	};

	let shown = '';
	return world.subscribe((node) => {
		// canSend: the rules of the world let the person send now.
		send.disabled = !node.canSend;
		empty.hidden = node.messages.length > 0;
		// Draw the list again only when the messages changed, not at every change of the data.
		const key = JSON.stringify(node.messages.map((message) => message.id));
		if (key === shown) return;
		shown = key;
		list.replaceChildren(...node.messages.map(messageItem));
	});
}

// One message: who said it and what. The person's own are on the right.
function messageItem(message) {
	const item = document.createElement('li');
	item.style.margin = '6px 0';
	item.style.textAlign = message.fromMe ? 'right' : 'left';
	const bubble = document.createElement('span');
	bubble.style.cssText = 'display: inline-block; padding: 6px 10px; border-radius: 10px; background: rgba(127, 127, 127, 0.15)';
	bubble.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
	item.append(bubble);
	return item;
}
Live, on a fake world
Open

Prossimi passi ​

La persona può parlare con il mondo ma non può ancora camminare sull'isola. Il passo 4: Fai una mossa aggiunge dei pulsanti che inviano le mosse e mostra se ognuna è stata consegnata.

Messaggi e domande tratta il modo di mostrare ogni tipo di messaggio comprese le immagini e i file. Il riferimento di send elenca i valori che accetta oltre al testo.

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