Avatar e RoleBadge
In una lista di membri che disegni da te (i giocatori di una partita, i mittenti dei messaggi, una classifica) questi due componenti mostrano chi è ogni membro. Avatar disegna le iniziali di un membro in un cerchio con un pallino di presenza verde quando il membro è online e grigio negli altri casi. RoleBadge mostra il ruolo del membro nel mondo e aggiunge un'etichetta Master per i master del mondo.
import { useWorld } from './useWorld.js';
// The component: copy this part.
// (Two small components that go together: Avatar and RoleBadge.)
/** The tint behind the initials for each type, as in the webapp: wine for an agent, blue for a world, plain grey for a person. */
const TYPE_TINT = { agent: 'rgba(159, 70, 107, 0.22)', world: 'rgba(42, 84, 196, 0.22)' };
/** The first letters of up to two words of a name: "Ann Lee" gives "AL". */
function initialsOf(name) {
const words = (name ?? '?').trim().split(/\s+/);
return words.slice(0, 2).map((word) => word.slice(0, 1).toUpperCase()).join('');
}
/**
* Avatar: a member's initials in a circle, tinted by what it is (an agent,
* a world, a person), with a dot when it is online.
* @param {object} props
* @param {object} props.member - A member of `world.members`.
* @param {number} [props.size=40] - The size of the circle, in pixels.
*/
export function Avatar({ member, size = 40 }) {
const isOnline = member.status === 'online';
const dot = Math.max(8, Math.round(size / 4));
return (
<span role="img" aria-label={`${member.name ?? 'Someone'}, ${isOnline ? 'online' : 'away'}`}
style={{ position: 'relative', flex: 'none', display: 'inline-grid', placeItems: 'center', width: size, height: size, borderRadius: '50%', fontSize: size * 0.4, fontWeight: 600, background: TYPE_TINT[member.type] ?? 'rgba(127, 127, 127, 0.22)' }}>
<span aria-hidden="true">{initialsOf(member.name)}</span>
<span aria-hidden="true" style={{ position: 'absolute', right: 0, bottom: 0, width: dot, height: dot, borderRadius: '50%', boxSizing: 'border-box', border: '2px solid Canvas', background: isOnline ? '#399D57' : '#9D9C9A' }} />
</span>
);
}
/**
* RoleBadge: the role of a member in the world, with a mark for the masters
* of the world. Hold the pointer on the role to read what it means.
* @param {object} props
* @param {object} props.member - A member of `world.members`.
* @param {Array<object>} [props.roles] - The roles of the world (`world.roles`), for the description of the role.
*/
export function RoleBadge({ member, roles = [] }) {
const pill = { display: 'inline-block', fontSize: 12, lineHeight: '18px', padding: '0 8px', borderRadius: 9 };
const description = roles.find((role) => role.name === member.role)?.description ?? undefined;
return (
<span style={{ display: 'inline-flex', gap: 4 }}>
{member.isMaster && <span title="One of the world's masters" style={{ ...pill, fontWeight: 600, background: 'rgba(240, 165, 78, 0.3)' }}>Master</span>}
{member.role && <span title={description} style={{ ...pill, border: '1px solid rgba(127, 127, 127, 0.45)' }}>{member.role}</span>}
</span>
);
}
// Using them, on a fake world.
// A fake world to build with: three members with their roles.
const studio = {
name: 'Studio',
members: [
{ name: 'Ann Lee', role: 'painter', isMaster: true },
{ name: 'Bob', role: 'painter' },
{ name: 'Cleo Ray', role: 'critic' },
],
roles: [
{ name: 'painter', description: 'Paints on the shared canvas' },
{ name: 'critic', description: 'Comments on the paintings' },
],
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: studio } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 12 }}>
{world.members.map((member) => (
<li key={member.id} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<Avatar member={member} />
<span style={{ fontWeight: 600 }}>{member.name}</span>
<RoleBadge member={member} roles={world.roles} />
</li>
))}
</ul>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
// (Two small components that go together: avatar and roleBadge.)
/** The tint behind the initials for each type, as in the webapp: wine for an agent, blue for a world, plain grey for a person. */
const TYPE_TINT = { agent: 'rgba(159, 70, 107, 0.22)', world: 'rgba(42, 84, 196, 0.22)' };
/** The first letters of up to two words of a name: "Ann Lee" gives "AL". */
function initialsOf(name) {
const words = (name ?? '?').trim().split(/\s+/);
return words.slice(0, 2).map((word) => word.slice(0, 1).toUpperCase()).join('');
}
/**
* Makes a member's avatar: its initials in a circle, tinted by what it is
* (an agent, a world, a person), with a dot when it is online. Call it where
* you draw your members, in `subscribe`.
* @param {object} member - A member of `world.members`.
* @param {{size?: number}} [options] - The size of the circle, in pixels (default 40).
* @returns {HTMLElement} The avatar.
*/
export function avatar(member, { size = 40 } = {}) {
const isOnline = member.status === 'online';
const dotSize = Math.max(8, Math.round(size / 4));
const circle = document.createElement('span');
circle.setAttribute('role', 'img');
circle.setAttribute('aria-label', `${member.name ?? 'Someone'}, ${isOnline ? 'online' : 'away'}`);
Object.assign(circle.style, { position: 'relative', flex: 'none', display: 'inline-grid', placeItems: 'center', width: `${size}px`, height: `${size}px`, borderRadius: '50%', fontSize: `${size * 0.4}px`, fontWeight: '600', background: TYPE_TINT[member.type] ?? 'rgba(127, 127, 127, 0.22)' });
const letters = document.createElement('span');
letters.setAttribute('aria-hidden', 'true');
letters.textContent = initialsOf(member.name);
const dot = document.createElement('span');
dot.setAttribute('aria-hidden', 'true');
Object.assign(dot.style, { position: 'absolute', right: '0', bottom: '0', width: `${dotSize}px`, height: `${dotSize}px`, borderRadius: '50%', boxSizing: 'border-box', border: '2px solid Canvas', background: isOnline ? '#399D57' : '#9D9C9A' });
circle.append(letters, dot);
return circle;
}
/**
* Makes the role badge of a member: its role in the world, with a mark for the
* masters of the world. Hold the pointer on the role to read what it means.
* @param {object} member - A member of `world.members`.
* @param {Array<object>} [roles] - The roles of the world (`world.roles`), for the description of the role.
* @returns {HTMLElement} The badge.
*/
export function roleBadge(member, roles = []) {
const pill = { display: 'inline-block', fontSize: '12px', lineHeight: '18px', padding: '0 8px', borderRadius: '9px' };
const badge = document.createElement('span');
Object.assign(badge.style, { display: 'inline-flex', gap: '4px' });
if (member.isMaster) {
const master = document.createElement('span');
master.textContent = 'Master';
master.title = 'One of the world\'s masters';
Object.assign(master.style, pill, { fontWeight: '600', background: 'rgba(240, 165, 78, 0.3)' });
badge.append(master);
}
if (member.role) {
const role = document.createElement('span');
role.textContent = member.role;
role.title = roles.find((item) => item.name === member.role)?.description ?? '';
Object.assign(role.style, pill, { border: '1px solid rgba(127, 127, 127, 0.45)' });
badge.append(role);
}
return badge;
}
// Using them, on a fake world.
// A fake world to build with: three members with their roles.
const studio = {
name: 'Studio',
members: [
{ name: 'Ann Lee', role: 'painter', isMaster: true },
{ name: 'Bob', role: 'painter' },
{ name: 'Cleo Ray', role: 'critic' },
],
roles: [
{ name: 'painter', description: 'Paints on the shared canvas' },
{ name: 'critic', description: 'Comments on the paintings' },
],
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: studio } });
const list = document.createElement('ul');
Object.assign(list.style, { listStyle: 'none', margin: '0', padding: '0', display: 'grid', gap: '12px' });
document.body.append(list);
// Your own list of members, drawn again at every change, with the two components in each row.
world.subscribe((node) => {
list.replaceChildren(...node.members.map((member) => {
const row = document.createElement('li');
Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '12px' });
const name = document.createElement('span');
name.textContent = member.name;
name.style.fontWeight = '600';
row.append(avatar(member), name, roleBadge(member, node.roles));
return row;
}));
});Tutti e due ricevono un solo membro di world.members e non il mondo intero. In React ogni riga della tua lista passa il suo membro a ciascun componente come prop. Con JavaScript semplice avatar(member) e roleBadge(member, roles) restituiscono un elemento nuovo da aggiungere alla riga. Vengono ricostruiti insieme al resto della lista a ogni cambiamento perché li chiami dentro la callback di subscribe.
I due componenti leggono name, type, status, role e isMaster del membro (Persone e ruoli). Come fa la webapp, Avatar colora di vinaccia il cerchio di un agente e di blu quello di un mondo. Le persone e i membri di tipo 'unknown' prendono invece un grigio neutro. Il nome accessibile del cerchio è "nome, online" oppure "nome, away" (per esempio "Bob, online").
Props
Avatar:
| Prop | Predefinito | Che cos'è |
|---|---|---|
member | (obbligatorio) | Un membro di world.members. |
size | 40 | Il diametro del cerchio in pixel. |
RoleBadge:
| Prop | Predefinito | Che cos'è |
|---|---|---|
member | (obbligatorio) | Un membro di world.members. |
roles | [] | I ruoli del mondo (world.roles). La descrizione del ruolo del membro diventa il tooltip dell'etichetta. |
Parametri
avatar(member, options) e roleBadge(member, roles) restituiscono ciascuno un elemento nuovo.
| Parametro | Che cos'è |
|---|---|
member | Un membro di world.members. |
options.size | Il diametro del cerchio in pixel (solo avatar, predefinito 40). |
roles | I ruoli del mondo (solo roleBadge). La descrizione del ruolo del membro diventa il tooltip dell'etichetta. |
Modificalo
- Mostra un'immagine al posto delle iniziali quando i tuoi membri ne hanno una nei loro dati (
member.data.picturecome URL o data URI). Disegna unimgdentro il cerchio conobjectFit: 'cover'. - Togli il pallino accanto a un messaggio vecchio e ovunque la presenza non conti.
- Dai a ogni nome di ruolo una tinta sua in
RoleBadgee controlla che il testo resti leggibile in tutti e due i temi.
Vedi anche
Members: una lista completa di membri.MessageList: metti unAvataraccanto a ogni mittente.- Persone e ruoli.