Skip to content

Persone e ruoli ​

Oltre alla persona che usa la tua vista, un mondo contiene agenti, altre persone e i master che lo gestiscono. Ognuno di loro ha un ruolo (come la persona) e dei dati suoi. Con questi campi la tua vista elenca chi c'è nel mondo e chi è online, mostra i ruoli e quello della persona, costruisce una classifica dai dati di ogni membro e indica l'autore di ogni messaggio con un pulsante che ne apre la scheda del profilo.

I membri ​

world.members elenca gli altri membri del mondo. Ogni membro ha questi campi:

CampoChe cos'è
idUn identificatore stabile per tutta la vita del membro. Usalo come key in React.
nameIl suo nome oppure null.
type'agent', 'person', 'world' o 'unknown'.
roleIl suo ruolo nel mondo (uno di world.roles) oppure null.
isMastertrue per uno dei master che gestiscono il mondo.
status'online' mentre è nel mondo e altrimenti 'connecting' o 'offline'.
dataI valori del membro con i loro nomi nella stessa forma dei data del mondo.
jsx
import { useWorld } from './useWorld.js';

// A fake world with three members: two players and a referee, who is a master of the world.
const arena = {
	name: 'Arena',
	roles: [{ name: 'player', description: 'Plays the game' }, { name: 'referee', description: 'Keeps the score' }],
	members: [
		{ name: 'Ada', role: 'player' },
		{ name: 'Bo', role: 'player' },
		{ name: 'Rita', role: 'referee', isMaster: true },
	],
};

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>;

	// Only a world has members, and the view of an agent gets none.
	const members = world.members ?? [];
	const online = members.filter((member) => member.status === 'online');
	return (
		<>
			<h2>{members.length} in the world, {online.length} online</h2>
			<ul>
				{members.map((member) => <MemberLine key={member.id} member={member} />)}
			</ul>
		</>
	);
}

// One line per member: name, kind, role, master or not, online or not.
function MemberLine({ member }) {
	const parts = [member.name ?? 'Someone', member.type, member.role ?? 'no role'];
	if (member.isMaster) parts.push('master');
	parts.push(member.status === 'online' ? 'online' : 'away');
	return <li>{parts.join(' · ')}</li>;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with three members: two players and a referee, who is a master of the world.
const arena = {
	name: 'Arena',
	roles: [{ name: 'player', description: 'Plays the game' }, { name: 'referee', description: 'Keeps the score' }],
	members: [
		{ name: 'Ada', role: 'player' },
		{ name: 'Bo', role: 'player' },
		{ name: 'Rita', role: 'referee', isMaster: true },
	],
};

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

const count = document.createElement('h2');
const list = document.createElement('ul');
document.body.append(count, list);

// One line per member: name, kind, role, master or not, online or not.
function memberLine(member) {
	const parts = [member.name ?? 'Someone', member.type, member.role ?? 'no role'];
	if (member.isMaster) parts.push('master');
	parts.push(member.status === 'online' ? 'online' : 'away');
	const item = document.createElement('li');
	item.textContent = parts.join(' · ');
	return item;
}

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// Only a world has members, and the view of an agent gets none.
	const members = node.members ?? [];
	const online = members.filter((member) => member.status === 'online');
	count.textContent = `${members.length} in the world, ${online.length} online`;
	list.replaceChildren(...members.map(memberLine));
});
Live, on a fake world
Open
  • Solo un mondo ha dei membri. Nella vista di un agente members, roles e myRole sono undefined. Con node.members ?? [] lo stesso codice funziona in tutte e due le viste.
  • La persona non è nella lista. Il ruolo della persona è world.myRole (più avanti).
  • Un membro può non essersi ancora presentato. Finché non lo fa, il suo nome o il suo ruolo è null e il suo tipo è 'unknown'. Leggi il nome come member.name ?? 'Someone'.
  • La lista si svuota quando il mondo finisce (world.status vale 'ended'). I messaggi restano in messages.

Chi è online ​

member.status vale 'online' quando il membro è nel mondo. 'connecting' (mentre si riconnette) e 'offline' vogliono dire che in questo momento non è raggiungibile. Confronta con 'online' e considera assente il membro che ha uno degli altri due valori.

js
const members = node.members ?? [];
const online = members.filter((member) => member.status === 'online');
count.textContent = `${online.length} of ${members.length} online`;

Ogni arrivo o partenza di un membro è un cambiamento del mondo che chiama il tuo listener di subscribe con la nuova lista. La ricetta Mostra chi è online e il componente Members partono da questo codice.

I ruoli ​

world.roles elenca i ruoli del mondo. Ogni ruolo ha un name, una description (oppure null) e un diagram con le regole del ruolo così come le descrive il mondo (la maggior parte delle viste non lo legge mai). world.myRole è il nome del ruolo della persona e vale null finché la persona non ne ha uno.

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

// A fake world with two roles. The person is a player.
const arena = {
	name: 'Arena',
	roles: [{ name: 'player', description: 'Plays the game' }, { name: 'referee', description: 'Keeps the score' }],
	members: [
		{ name: 'Ada', role: 'player' },
		{ name: 'Bo', role: 'player' },
		{ name: 'Rita', role: 'referee', isMaster: true },
	],
	myRole: 'player',
};

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>;

	const roles = world.roles ?? [];
	const members = world.members ?? [];
	// The person's role, with its description when the world gives one.
	const myRole = roles.find((role) => role.name === world.myRole);
	return (
		<>
			<h2>
				{world.myRole ? `Your role: ${world.myRole} (${myRole?.description ?? 'no description'})` : 'You have no role yet.'}
			</h2>
			{/* Each role, with how many members have it. */}
			<ul>
				{roles.map((role) => (
					<li key={role.name} style={{ fontWeight: role.name === world.myRole ? 'bold' : 'normal' }}>
						{role.name}: {role.description ?? ''} ({members.filter((member) => member.role === role.name).length})
					</li>
				))}
			</ul>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with two roles. The person is a player.
const arena = {
	name: 'Arena',
	roles: [{ name: 'player', description: 'Plays the game' }, { name: 'referee', description: 'Keeps the score' }],
	members: [
		{ name: 'Ada', role: 'player' },
		{ name: 'Bo', role: 'player' },
		{ name: 'Rita', role: 'referee', isMaster: true },
	],
	myRole: 'player',
};

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

const mine = document.createElement('h2');
const list = document.createElement('ul');
document.body.append(mine, list);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	const roles = node.roles ?? [];
	const members = node.members ?? [];
	// The person's role, with its description when the world gives one.
	const myRole = roles.find((role) => role.name === node.myRole);
	mine.textContent = node.myRole ? `Your role: ${node.myRole} (${myRole?.description ?? 'no description'})` : 'You have no role yet.';
	// Each role, with how many members have it.
	list.replaceChildren(...roles.map((role) => {
		const holders = members.filter((member) => member.role === role.name).length;
		const item = document.createElement('li');
		item.textContent = `${role.name}: ${role.description ?? ''} (${holders})`;
		if (role.name === node.myRole) item.style.fontWeight = 'bold';
		return item;
	}));
});
Live, on a fake world
Open

Spesso è il ruolo della persona a decidere che cosa mostra la tua vista (un arbitro vede i controlli della partita e un giocatore vede la scacchiera). Un ruolo può cambiare durante la vita del mondo (un nuovo round, una promozione) e quindi myRole va letto a ogni cambiamento come qualsiasi altro campo.

js
world.subscribe((node) => {
  refereePanel.hidden = node.myRole !== 'referee';
  board.hidden = node.myRole !== 'player';
});

Il componente Avatar e RoleBadge mostra un membro con il suo ruolo.

I dati di un membro ​

I data di un membro contengono valori degli stessi tipi dei dati del mondo (numeri, testo, griglie, immagini, file) come un avatar, il punteggio di un giocatore o la posizione di un robot. La classifica qui sotto li legge nel listener di subscribe insieme al resto del mondo e ordina i membri per giri.

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

// A fake race: each runner shows its own laps in its `data`.
const race = {
	name: 'Race',
	members: [
		{ name: 'Ada', role: 'runner', data: { laps: (time) => Math.floor(time / 1000) % 10 } },
		{ name: 'Bo', role: 'runner', data: { laps: (time) => Math.floor(time / 1500) % 10 } },
		{ name: 'Cy', role: 'runner', data: { laps: 4 } },
	],
};

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

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

	// Sort a copy, because `members` belongs to the world and the view never changes it.
	const ranking = [...(world.members ?? [])].sort((a, b) => (b.data.laps ?? 0) - (a.data.laps ?? 0));
	return (
		<>
			<h2>Scoreboard</h2>
			<ol>
				{ranking.map((member) => (
					<li key={member.id}>{member.name}: {member.data.laps ?? 0} laps</li>
				))}
			</ol>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake race: each runner shows its own laps in its `data`.
const race = {
	name: 'Race',
	members: [
		{ name: 'Ada', role: 'runner', data: { laps: (time) => Math.floor(time / 1000) % 10 } },
		{ name: 'Bo', role: 'runner', data: { laps: (time) => Math.floor(time / 1500) % 10 } },
		{ name: 'Cy', role: 'runner', data: { laps: 4 } },
	],
};

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

const title = document.createElement('h2');
title.textContent = 'Scoreboard';
const list = document.createElement('ol');
document.body.append(title, list);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// Sort a copy, because `members` belongs to the world and the view never changes it.
	const ranking = [...(node.members ?? [])].sort((a, b) => (b.data.laps ?? 0) - (a.data.laps ?? 0));
	list.replaceChildren(...ranking.map((member) => {
		const item = document.createElement('li');
		item.textContent = `${member.name}: ${member.data.laps ?? 0} laps`;
		return item;
	}));
});
Live, on a fake world
Open
  • Ordina una copia ([...node.members].sort(...)). sort modifica l'array su cui la chiami e members appartiene al mondo.
  • Un nome può mancare nei data di un membro come nei data del mondo. Leggilo con un valore di default come member.data.laps ?? 0.
  • onData e dataHistory seguono solo i data del mondo. I valori di un membro si leggono da members a ogni cambiamento.

Il componente Scoreboard è una classifica pronta da copiare.

Chi l'ha scritto ​

Il fromId di un messaggio è l'id del suo autore in members. Il membro con quell'id ti dà il nome, il ruolo e i dati dell'autore.

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

// A fake world with two members. `from` makes one of them say the answer.
const arena = {
	name: 'Arena',
	members: [{ name: 'Ada', role: 'player' }, { name: 'Rita', role: 'referee', isMaster: true }],
	onMessage: () => ({ from: 'Rita', text: 'Ada, your move' }),
};

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 (
		<>
			<button onClick={() => world.send('hello')}>Say hello</button>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{/* `showsSenders` is false when the world asks not to show who wrote each message. */}
						{world.showsSenders === false ? '' : `${authorOf(message, world)}: `}
						{message.text ?? ''}
					</li>
				))}
			</ul>
		</>
	);
}

// Who wrote a message, in words: the person, the world itself, or a member with its role.
function authorOf(message, world) {
	if (message.fromMe) return 'You';
	if (message.fromId === world.id) return world.name;
	// `fromId` is a member's id, as in `members`.
	const member = (world.members ?? []).find((someone) => someone.id === message.fromId);
	return member ? `${member.name} (${member.role})` : message.from;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with two members. `from` makes one of them say the answer.
const arena = {
	name: 'Arena',
	members: [{ name: 'Ada', role: 'player' }, { name: 'Rita', role: 'referee', isMaster: true }],
	onMessage: () => ({ from: 'Rita', text: 'Ada, your move' }),
};

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

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

// Who wrote a message, in words: the person, the world itself, or a member with its role.
function authorOf(message, node) {
	if (message.fromMe) return 'You';
	if (message.fromId === node.id) return node.name;
	// `fromId` is a member's id, as in `members`.
	const member = (node.members ?? []).find((someone) => someone.id === message.fromId);
	return member ? `${member.name} (${member.role})` : message.from;
}

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		// `showsSenders` is false when the world asks not to show who wrote each message.
		item.textContent = node.showsSenders === false
			? message.text ?? ''
			: `${authorOf(message, node)}: ${message.text ?? ''}`;
		return item;
	}));
});
Live, on a fake world
Open

fromId può avere tre tipi di valore:

fromIdChi l'ha scritto
l'id di un membroQuel membro, che compare in members.
l'id del mondo (world.id)Il mondo stesso per le sue note e i suoi messaggi. Nella vista di un agente è l'id dell'agente.
nullLa persona (fromMe è true). La tua vista non riceve mai l'id della persona e ne trova il nickname in me.
  • Un membro può andarsene. I suoi vecchi messaggi conservano il suo fromId anche quando non è più in members. Per quei messaggi ripiega sul nome in message.from.
  • fromId è stato aggiunto nella webapp di novembre 2026. Una webapp più vecchia non lo passa e la tua vista ripiega su message.from.

Quando il mondo nasconde chi l'ha scritto ​

world.showsSenders vale false quando un mondo chiede di non mostrare chi ha scritto ogni messaggio. In quel caso mostra i messaggi senza nomi e senza immagini dei loro autori come fa l'esempio. Una webapp precedente a novembre 2026 non passa showsSenders. Con il controllo node.showsSenders === false la tua vista continua allora a mostrare i nomi.

showsSenders esprime un desiderio del proprietario e non filtra niente. I messaggi portano ancora from e fromId mentre members elenca ancora i membri. La tua vista può mostrare comunque la lista dei membri senza andare contro quel desiderio perché la webapp mostra la stessa lista nella sua vista.

Apri la scheda di un membro ​

world.openProfile(id) chiede alla webapp di aprire sopra la tua vista la sua scheda del profilo di un membro. Accetta l'id di un membro o world.id per la scheda del mondo stesso. La Promise si risolve con true quando la scheda viene mostrata e con false per qualsiasi altro id o per un membro che non si è ancora presentato (type 'unknown').

js
function authorButton(message, node) {
  const author = (node.members ?? []).find((member) => member.id === message.fromId);
  const button = document.createElement('button');
  button.textContent = author?.name ?? message.from;
  button.disabled = !message.fromId; // the person's own messages: no card to open
  button.onclick = () => world.openProfile(message.fromId);
  return button;
}
  • Apri una scheda solo a un clic della persona. Una scheda che la persona non ha chiesto copre la vista.
  • La tua vista non riceve niente dalla scheda che la persona legge e chiude nella webapp.
  • Con un mondo finto non compare nessuna scheda e openProfile si risolve con true per un id conosciuto.
  • Con una webapp più vecchia del kit openProfile viene rifiutata con 'not-allowed-verb'. In quel caso nascondi i pulsanti che aprono le schede.

world.openProfile(id) ha tutti i dettagli.

Le persone in un mondo finto ​

Un mondo finto accetta members, roles e myRole:

js
const arena = {
  name: 'Arena',
  roles: [{ name: 'player', description: 'Plays the game' }, { name: 'referee' }],
  members: [
    { name: 'Ada', role: 'player', data: { score: (time) => Math.floor(time / 1000) % 10 } },
    { name: 'Rita', role: 'referee', isMaster: true },
  ],
  myRole: 'player',
};
  • I data di ogni membro accettano gli stessi valori dei data del mondo (valori fissi, funzioni del tempo o { every, value } come in I dati in un mondo finto).
  • I membri finti sono agenti sempre online. L'onMessage del mondo risponde alla persona. Una risposta che indica un membro in from ({ from: 'Ada', text: 'Your move' }) arriva come messaggio di quel membro e porta l'id di Ada in fromId.
  • Con showsSenders: false il mondo finto chiede di non mostrare chi ha scritto ogni messaggio.
  • myRole e i ruoli restano fissi per tutta la vita del mondo finto. Per provare un altro ruolo cambia myRole e ricarica.

A che cosa stare attenti ​

  • Leggi members ?? [] e roles ?? [] perché la vista di un agente non ha né l'uno né l'altro.
  • Leggi name ?? 'Someone' per un membro che non si è ancora presentato.
  • Confronta status === 'online' e con 'connecting' o 'offline' considera il membro assente.
  • Ordina una copia e mai members stesso.
  • Il ruolo della persona è myRole e la persona non è in members.
  • L'autore di un messaggio è il suo fromId confrontato con members (null per la persona).
  • showsSenders === false vuol dire niente nomi né immagini accanto ai messaggi.

Prossimi passi ​

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