MemberName
MemberName sostituisce il semplice from di un messaggio con un pulsante che nomina il mittente. Il pulsante mostra il nome e il ruolo di un membro. Per un messaggio del mondo o una nota delle sue regole mostra invece il nome del mondo. Un clic chiede alla webapp di mostrare sopra la tua vista la scheda del profilo di quel membro o del mondo. Quando il mondo chiede di non mostrare i mittenti, MemberName non disegna niente.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/**
* MemberName: who wrote a message, as a button that opens their profile card
* in the webapp. A member shows with their role and a note of the world with
* the name of the world. It shows nothing when the world asks not to show who
* wrote each message.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {object} props.message - A message of `world.messages`.
* @param {(isShown: boolean) => void} [props.onOpen] - Called after a click: true when the webapp showed the card.
*/
export function MemberName({ world, message, onOpen }) {
// Show nothing when the world asks not to show who wrote each message, and show the names when an older webapp gives no `showsSenders`.
if (world.showsSenders === false) return null;
if (message.fromMe) return <strong>You</strong>;
// Who wrote it: a member (`fromId` is an id of `members`), or the world itself, for its notes.
const member = (world.members ?? []).find((one) => one.id === message.fromId);
const isWorld = Boolean(message.fromId) && message.fromId === world.id;
const name = member?.name ?? (isWorld ? world.name : message.from) ?? 'Someone';
// No id to open (an older webapp gives no `fromId`): show the name only.
if (!member && !isWorld) return <strong>{name}</strong>;
const open = async () => {
// The webapp shows its own card over the view and gives the view only true or false.
const isShown = await world.openProfile(message.fromId).catch(() => false);
onOpen?.(isShown);
};
return (
<button type="button" onClick={open} title={`Show the profile of ${name}`}
style={{ font: 'inherit', fontWeight: 600, padding: 0, border: 0, background: 'none', color: 'inherit', textDecoration: 'underline', cursor: 'pointer' }}>
{name}
{member?.role && (
<span style={{ marginLeft: 6, fontSize: 12, fontWeight: 400, padding: '1px 8px', borderRadius: 9, border: '1px solid rgba(127, 127, 127, 0.4)', display: 'inline-block', textDecoration: 'none' }}>
{member.role}
</span>
)}
</button>
);
}
// Using it, on a fake world.
// A fake world to build with: two members, and answers from Otto or from the world itself.
const bookClub = {
name: 'Book club',
members: [
{ name: 'Otto', role: 'host', isMaster: true },
{ name: 'Mia', role: 'reader' },
],
roles: [{ name: 'host' }, { name: 'reader' }],
// `from` names the member who answers. Without it, the world answers with a note of its rules.
onMessage: (message) => (message.text === 'hello'
? { from: 'Otto', text: 'Welcome to the club!' }
: 'We meet on Friday at six.'),
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: bookClub } });
const [opened, setOpened] = useState('');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// While building, the fake world shows no card: write the result in the page instead.
const onOpen = (isShown) => setOpened(isShown ? 'Profile shown: in the webapp, the card opens over the view.' : 'No profile to show.');
return (
<div style={{ display: 'grid', gap: 10, maxWidth: 480 }}>
<div style={{ display: 'flex', gap: 8 }}>
<button type="button" disabled={!world.canSend} onClick={() => world.send('hello')}>Say hello</button>
<button type="button" disabled={!world.canSend} onClick={() => world.send('When do we meet?')}>Ask when we meet</button>
</div>
{world.messages.map((message) => (
<p key={message.id} style={{ margin: 0 }}>
<MemberName world={world} message={message} onOpen={onOpen} />: {message.text}
</p>
))}
<p role="status" style={{ margin: 0, fontSize: 14, opacity: 0.8 }}>{opened}</p>
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/**
* Makes the name of who wrote a message, as a button that opens their
* profile card in the webapp. A member shows with their role and a note of
* the world with the name of the world. It returns null when the world asks
* not to show who wrote each message.
* @param {object} message - A message of `world.messages`.
* @param {object} world - The world: the newest one, from `subscribe`.
* @param {{onOpen?: (isShown: boolean) => void}} [options] - Called after a click: true when the webapp showed the card.
* @returns {HTMLElement|null} The element, or null when no name is shown.
*/
export function memberName(message, world, { onOpen } = {}) {
// Show nothing when the world asks not to show who wrote each message, and show the names when an older webapp gives no `showsSenders`.
if (world.showsSenders === false) return null;
const plain = document.createElement('strong');
if (message.fromMe) {
plain.textContent = 'You';
return plain;
}
// Who wrote it: a member (`fromId` is an id of `members`), or the world itself, for its notes.
const member = (world.members ?? []).find((one) => one.id === message.fromId);
const isWorld = Boolean(message.fromId) && message.fromId === world.id;
const name = member?.name ?? (isWorld ? world.name : message.from) ?? 'Someone';
// No id to open (an older webapp gives no `fromId`): show the name only.
if (!member && !isWorld) {
plain.textContent = name;
return plain;
}
const button = document.createElement('button');
button.type = 'button';
button.title = `Show the profile of ${name}`;
button.textContent = name;
Object.assign(button.style, { font: 'inherit', fontWeight: '600', padding: '0', border: '0', background: 'none', color: 'inherit', textDecoration: 'underline', cursor: 'pointer' });
if (member?.role) {
const role = document.createElement('span');
role.textContent = member.role;
Object.assign(role.style, { marginLeft: '6px', fontSize: '12px', fontWeight: '400', padding: '1px 8px', borderRadius: '9px', border: '1px solid rgba(127, 127, 127, 0.4)', display: 'inline-block', textDecoration: 'none' });
button.append(role);
}
button.onclick = async () => {
// The webapp shows its own card over the view and gives the view only true or false.
const isShown = await world.openProfile(message.fromId).catch(() => false);
onOpen?.(isShown);
};
return button;
}
// Using it, on a fake world.
// A fake world to build with: two members, and answers from Otto or from the world itself.
const bookClub = {
name: 'Book club',
members: [
{ name: 'Otto', role: 'host', isMaster: true },
{ name: 'Mia', role: 'reader' },
],
roles: [{ name: 'host' }, { name: 'reader' }],
// `from` names the member who answers. Without it, the world answers with a note of its rules.
onMessage: (message) => (message.text === 'hello'
? { from: 'Otto', text: 'Welcome to the club!' }
: 'We meet on Friday at six.'),
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: bookClub } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '10px', maxWidth: '480px' });
const buttons = document.createElement('div');
Object.assign(buttons.style, { display: 'flex', gap: '8px' });
const hello = document.createElement('button');
hello.textContent = 'Say hello';
hello.onclick = () => world.send('hello');
const when = document.createElement('button');
when.textContent = 'Ask when we meet';
when.onclick = () => world.send('When do we meet?');
buttons.append(hello, when);
const list = document.createElement('div');
Object.assign(list.style, { display: 'grid', gap: '10px' });
const opened = document.createElement('p');
opened.setAttribute('role', 'status');
Object.assign(opened.style, { margin: '0', fontSize: '14px', opacity: '0.8' });
page.append(buttons, list, opened);
document.body.append(page);
// While building, the fake world shows no card: write the result in the page instead.
const onOpen = (isShown) => {
opened.textContent = isShown ? 'Profile shown: in the webapp, the card opens over the view.' : 'No profile to show.';
};
// Draws the messages again when they change.
let shownCount = -1;
world.subscribe((node) => {
hello.disabled = !node.canSend;
when.disabled = !node.canSend;
if (node.messages.length === shownCount) return;
shownCount = node.messages.length;
list.replaceChildren(...node.messages.map((message) => {
const line = document.createElement('p');
line.style.margin = '0';
const name = memberName(message, node, { onOpen });
if (name) line.append(name, ': ');
line.append(message.text ?? '');
return line;
}));
});Il fromId di un messaggio identifica il mittente e prende uno di tre valori:
- l'
iddi un membro cheMemberNamecerca inworld.membersper trovare il nome e ilrole - l'id del mondo (
world.id) per i suoi messaggi e per le note delle sue regole (nella vista di un agente l'id dell'agente) nullper i messaggi della persona (cheMemberNameetichetta come "You").
Quando fromId manca (in una webapp più vecchia) o non corrisponde né a un membro né al mondo, MemberName mostra il nome di from come testo semplice senza niente da cliccare.
Un clic chiama world.openProfile(id). La webapp mostra la sua scheda sopra la tua vista e la Promise si risolve con true. Si risolve con false per un id che non appartiene né al mondo né a un membro e per un membro che non ha ancora una scheda perché è noto solo per il suo ruolo (type: 'unknown'). La tua vista non riceve niente dalla scheda. Un mondo finto non mostra nessuna scheda anche se il suo openProfile si risolve con true per l'id del mondo o di un membro. Per rendere visibile il clic durante lo sviluppo l'esempio scrive Profile shown nella pagina.
I messaggi della persona non hanno un id di proposito. La tua vista conosce la persona solo attraverso world.me con il nickname e i campi che la persona ha scelto di condividere quando ha accettato la tua vista.
Quando il mondo nasconde i mittenti. Un mondo con un voto segreto o una revisione anonima può chiedere di non mostrare chi ha scritto ogni messaggio. In quel caso world.showsSenders è false e MemberName non restituisce niente. Anche i tuoi componenti non dovrebbero mostrare nomi o immagini accanto ai messaggi. Uno showsSenders assente in una webapp più vecchia vale come true.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo o l'agente restituito da useWorld. |
message | (obbligatorio) | Un messaggio di world.messages. |
onOpen | nessuno | Una callback chiamata dopo un clic con true quando la webapp ha mostrato la scheda e con false negli altri casi. |
Parametri
memberName(message, world, options) restituisce un nuovo elemento o null quando non viene mostrato nessun nome. Passagli il node ricevuto dalla callback di subscribe in corso. In uno snapshot più vecchio del mondo mancano i membri appena entrati.
| Parametro | Che cos'è |
|---|---|
message | Un messaggio di world.messages. |
world | Il mondo o l'agente come node passato da subscribe. |
options.onOpen | Una callback chiamata dopo un clic con true quando la webapp ha mostrato la scheda e con false negli altri casi. |
Modificalo
- Aggiungi un'immagine al nome con un
Avatardel membro dentro il pulsante. - Togli il ruolo rimuovendo il suo
span. - Nomina il mittente una volta per gruppo di messaggi. Mostra il nome solo quando il messaggio precedente ha un
fromIddiverso (Raggruppa i messaggi per mittente). - Mostra più della scheda della webapp in un tuo pannello costruito dai
datadel membro. La scheda della webapp resta comunque l'unico posto con il profilo completo.
Vedi anche
world.openProfile: il suo argomento e il suo risultato.Members: tutti quelli che sono nel mondo con il loro ruolo.- Persone e ruoli.