Group messages by who sent them
When one sender writes several messages in a row, repeating the name on each of them adds nothing. Like a chat app, your view can put consecutive messages of the same sender in one group and render the name once. Two messages that you send quickly end up in one group because the agent in the example takes a second to reply.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// The fake agent answers each message after a second.
const echo = {
name: 'Echo',
onMessage: (message) => new Promise((resolve) => setTimeout(() => resolve(`You said: ${message.text}`), 1000)),
};
// Puts the messages that follow each other from the same sender in one group.
function groupBySender(messages) {
const groups = [];
for (const message of messages) {
const sender = message.fromMe ? 'You' : message.from;
const last = groups.at(-1);
if (last && last.sender === sender) last.messages.push(message);
else groups.push({ sender, messages: [message] });
}
return groups;
}
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: echo } });
const [text, setText] = useState('');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!agent) return <p>Connecting…</p>;
function handleSubmit(event) {
event.preventDefault();
if (!text.trim()) return;
agent.send(text);
setText('');
}
return (
<>
{groupBySender(agent.messages).map((group) => (
// The key of a group is the id of its first message, which never changes.
<section key={group.messages[0].id} style={{ borderLeft: '3px solid #8888', paddingLeft: 8, marginBottom: 12 }}>
<b>{group.sender}</b>
{group.messages.map((message) => <div key={message.id}>{message.text}</div>)}
</section>
))}
<form onSubmit={handleSubmit}>
<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Message" />
<button disabled={!agent.canSend}>Send</button>
</form>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// The fake agent answers each message after a second.
const echo = {
name: 'Echo',
onMessage: (message) => new Promise((resolve) => setTimeout(() => resolve(`You said: ${message.text}`), 1000)),
};
// Puts the messages that follow each other from the same sender in one group.
function groupBySender(messages) {
const groups = [];
for (const message of messages) {
const sender = message.fromMe ? 'You' : message.from;
const last = groups.at(-1);
if (last && last.sender === sender) last.messages.push(message);
else groups.push({ sender, messages: [message] });
}
return groups;
}
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: echo } });
const list = document.createElement('div');
const form = document.createElement('form');
const input = document.createElement('input');
input.placeholder = 'Message';
const sendButton = document.createElement('button');
sendButton.textContent = 'Send';
form.append(input, sendButton);
document.body.append(list, form);
form.onsubmit = (event) => {
event.preventDefault();
if (!input.value.trim()) return;
agent.send(input.value);
input.value = '';
};
agent.subscribe((node) => {
sendButton.disabled = !node.canSend;
list.replaceChildren(...groupBySender(node.messages).map((group) => {
// A group shows the sender's name once, then each of their messages.
const section = document.createElement('section');
section.style.cssText = 'border-left: 3px solid #8888; padding-left: 8px; margin-bottom: 12px;';
const sender = document.createElement('b');
sender.textContent = group.sender;
section.append(sender);
for (const message of group.messages) {
const line = document.createElement('div');
line.textContent = message.text ?? '';
section.append(line);
}
return section;
}));
});How it works
groupBySender walks through the messages from the oldest to the newest. A message with the same sender as the last group joins it and any other message starts a new group. The sender is "You" for the messages of the person (fromMe) and the name in from for all the others.
- In React each group takes as its
keytheidof its first message because thatidstays the same while the group grows. - In a world the notes of the rules (
isSystem) have the name of the world infrom. Give them a separate sender such as "Rules" to keep them in groups apart from the messages of the world.
See also
- MessageList.
- Avatar and RoleBadge: a picture and a role next to each name.
GuiMessage.