Skip to content

Members ​

Members mostra in una lista per un pannello laterale il nome, lo stato online e il ruolo di ogni membro di un mondo. I master vengono per primi e hanno l'etichetta Master. Quando il mondo dà un ruolo alla persona, una riga sopra la lista mostra world.myRole.

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

// The component: copy this part.

/** The tint behind a member's initial, by its type: agents, worlds, and people (no colour). */
const TYPE_TINT = { agent: 'rgba(159, 70, 107, 0.2)', world: 'rgba(42, 84, 196, 0.2)' };

/** Masters first, then by name. */
function byMasterThenName(a, b) {
	if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
	return (a.name ?? '').localeCompare(b.name ?? '');
}

/**
 * Members: who is in the world, masters first, with their role and whether
 * they are online. It also says the person's own role.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string} [props.title='Members'] - The heading of the list.
 */
export function Members({ world, title = 'Members' }) {
	// The view of an agent has no members, because only worlds have them.
	const members = [...(world.members ?? [])].sort(byMasterThenName);
	const roleText = (name) => world.roles?.find((role) => role.name === name)?.description ?? undefined;

	return (
		<section aria-label={title} style={{ display: 'grid', gap: 8 }}>
			<h2 style={{ margin: 0, fontSize: 16 }}>{title} · {members.length}</h2>
			{world.myRole && <p style={{ margin: 0, fontSize: 14, opacity: 0.8 }}>Your role: {world.myRole}</p>}
			{members.length === 0 && <p style={{ margin: 0, opacity: 0.6 }}>No one else is here yet.</p>}
			<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
				{members.map((member) => {
					const isOnline = member.status === 'online';
					return (
						<li key={member.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 4px' }}>
							<span aria-hidden="true" style={{ position: 'relative', flex: 'none', width: 32, height: 32, borderRadius: '50%', display: 'grid', placeItems: 'center', fontWeight: 600, background: TYPE_TINT[member.type] ?? 'rgba(127, 127, 127, 0.2)' }}>
								{(member.name ?? '?').slice(0, 1).toUpperCase()}
								<span style={{ position: 'absolute', right: -1, bottom: -1, width: 10, height: 10, borderRadius: '50%', border: '2px solid Canvas', background: isOnline ? '#399D57' : '#9D9C9A' }} />
							</span>
							<span style={{ flex: 1, minWidth: 0 }}>
								<span style={{ fontWeight: 600 }}>{member.name ?? 'Someone'}</span>
								<span style={{ display: 'block', fontSize: 13, opacity: 0.7 }}>{isOnline ? 'Online' : 'Away'}</span>
							</span>
							{member.isMaster && <span style={{ fontSize: 12, fontWeight: 600, padding: '1px 8px', borderRadius: 9, background: 'rgba(240, 165, 78, 0.25)' }}>Master</span>}
							{member.role && (
								<span title={roleText(member.role)} style={{ fontSize: 12, padding: '1px 8px', borderRadius: 9, border: '1px solid rgba(127, 127, 127, 0.4)' }}>
									{member.role}
								</span>
							)}
						</li>
					);
				})}
			</ul>
		</section>
	);
}

// Using it, on a fake world.

// A fake world to build with: three members, two roles, and the person's role.
const club = {
	name: 'Chess club',
	members: [
		{ name: 'Bob', role: 'player' },
		{ name: 'Cleo', role: 'referee' },
		{ name: 'Ann', role: 'player', isMaster: true },
	],
	roles: [
		{ name: 'player', description: 'Plays the games' },
		{ name: 'referee', description: 'Checks the moves' },
	],
	myRole: 'player',
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<div style={{ maxWidth: 360 }}>
			<Members world={world} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** The tint behind a member's initial, by its type: agents, worlds, and people (no colour). */
const TYPE_TINT = { agent: 'rgba(159, 70, 107, 0.2)', world: 'rgba(42, 84, 196, 0.2)' };

/** Masters first, then by name. */
function byMasterThenName(a, b) {
	if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
	return (a.name ?? '').localeCompare(b.name ?? '');
}

/**
 * Makes a small rounded label (a role, "Master").
 * @param {string} text - Its words.
 * @param {object} style - Its look.
 * @returns {HTMLElement} The label.
 */
function chip(text, style) {
	const element = document.createElement('span');
	element.textContent = text;
	Object.assign(element.style, { fontSize: '12px', padding: '1px 8px', borderRadius: '9px' }, style);
	return element;
}

/**
 * Makes the row of one member: its initial, name, whether it is online, and its role.
 * @param {object} member - A member of `world.members`.
 * @param {Array<object>} roles - The roles of the world, for the description of the role.
 * @returns {HTMLLIElement} The row.
 */
function memberRow(member, roles) {
	const isOnline = member.status === 'online';
	const row = document.createElement('li');
	Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '10px', padding: '6px 4px' });

	const initial = document.createElement('span');
	initial.setAttribute('aria-hidden', 'true');
	initial.textContent = (member.name ?? '?').slice(0, 1).toUpperCase();
	Object.assign(initial.style, { position: 'relative', flex: 'none', width: '32px', height: '32px', borderRadius: '50%', display: 'grid', placeItems: 'center', fontWeight: '600', background: TYPE_TINT[member.type] ?? 'rgba(127, 127, 127, 0.2)' });
	const dot = document.createElement('span');
	Object.assign(dot.style, { position: 'absolute', right: '-1px', bottom: '-1px', width: '10px', height: '10px', borderRadius: '50%', border: '2px solid Canvas', background: isOnline ? '#399D57' : '#9D9C9A' });
	initial.append(dot);

	const words = document.createElement('span');
	Object.assign(words.style, { flex: '1', minWidth: '0' });
	const name = document.createElement('span');
	name.textContent = member.name ?? 'Someone';
	name.style.fontWeight = '600';
	const presence = document.createElement('span');
	presence.textContent = isOnline ? 'Online' : 'Away';
	Object.assign(presence.style, { display: 'block', fontSize: '13px', opacity: '0.7' });
	words.append(name, presence);

	row.append(initial, words);
	if (member.isMaster) row.append(chip('Master', { fontWeight: '600', background: 'rgba(240, 165, 78, 0.25)' }));
	if (member.role) {
		const role = chip(member.role, { border: '1px solid rgba(127, 127, 127, 0.4)' });
		role.title = roles.find((item) => item.name === member.role)?.description ?? '';
		row.append(role);
	}
	return row;
}

/**
 * Draws who is in the world into `container`, masters first, with the role
 * of each member and whether they are online, and above them the person's
 * own role. It draws again at every change of the members.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {{title?: string}} [options] - The heading of the list.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function members(container, world, { title = 'Members' } = {}) {
	const section = document.createElement('section');
	section.setAttribute('aria-label', title);
	Object.assign(section.style, { display: 'grid', gap: '8px' });
	const heading = document.createElement('h2');
	Object.assign(heading.style, { margin: '0', fontSize: '16px' });
	const myRole = document.createElement('p');
	Object.assign(myRole.style, { margin: '0', fontSize: '14px', opacity: '0.8' });
	const empty = document.createElement('p');
	empty.textContent = 'No one else is here yet.';
	Object.assign(empty.style, { margin: '0', opacity: '0.6' });
	const list = document.createElement('ul');
	Object.assign(list.style, { listStyle: 'none', margin: '0', padding: '0', display: 'grid', gap: '4px' });
	section.append(heading, myRole, empty, list);
	container.append(section);

	// What the list shows now. The rows are made again only when it changes.
	let drawn = '';
	const stop = world.subscribe((node) => {
		// The view of an agent has no members, because only worlds have them.
		const sorted = [...(node.members ?? [])].sort(byMasterThenName);
		heading.textContent = `${title} · ${sorted.length}`;
		myRole.textContent = node.myRole ? `Your role: ${node.myRole}` : '';
		myRole.hidden = !node.myRole;
		empty.hidden = sorted.length > 0;
		const shown = JSON.stringify(sorted.map((member) => [member.id, member.name, member.status, member.role, member.isMaster]));
		if (shown === drawn) return;
		drawn = shown;
		list.replaceChildren(...sorted.map((member) => memberRow(member, node.roles ?? [])));
	});

	return () => {
		stop();
		section.remove();
	};
}

// Using it, on a fake world.

// A fake world to build with: three members, two roles, and the person's role.
const club = {
	name: 'Chess club',
	members: [
		{ name: 'Bob', role: 'player' },
		{ name: 'Cleo', role: 'referee' },
		{ name: 'Ann', role: 'player', isMaster: true },
	],
	roles: [
		{ name: 'player', description: 'Plays the games' },
		{ name: 'referee', description: 'Checks the moves' },
	],
	myRole: 'player',
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: club } });
const place = document.createElement('div');
place.style.maxWidth = '360px';
document.body.append(place);
members(place, world);
Live, on a fake world
Open

Ogni voce di world.members ha id, name, type, role, isMaster, status e i suoi data. I ruoli del mondo stanno in world.roles come oggetti { name, description } la cui description diventa il tooltip dell'etichetta del ruolo. La vista di un agente riceve sempre un array members vuoto. Con un array vuoto il componente mostra al posto della lista il testo "No one else is here yet." (Persone e ruoli).

Come in Avatar e RoleBadge, il cerchio di ogni membro mostra la sua iniziale sul colore che la webapp usa per il suo type (un colore per gli agenti e uno per i mondi). Le persone e i membri di tipo 'unknown' hanno un grigio neutro. Un pallino sul cerchio è verde quando status è 'online' e grigio per 'connecting' e 'offline'.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo, da useWorld.
title'Members'Il titolo della lista. Dopo il titolo viene il numero dei membri (Members · 3).

Parametri ​

members(container, world, options) disegna la lista dentro container e si iscrive al mondo. Le righe vengono ricostruite solo quando cambiano l'id, il nome, lo stato, il ruolo o il flag di master di un membro.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo, da connectToHost.
options.titleIl titolo della lista. Predefinito 'Members'.

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

Modificalo ​

  • Raggruppare per ruolo: disegna una lista per ogni voce di world.roles con i membri il cui role è uguale al suo name.
  • Solo chi è online: tieni i membri con status uguale a 'online' (Mostra chi è online).
  • I dati di ogni membro: il punteggio che Scoreboard mette in classifica è uno dei valori che il membro pubblica in member.data.
  • Immagini ed etichette dei ruoli: disegna ogni riga con Avatar e RoleBadge.

Vedi anche ​

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