Skip to main content

Chat

Chat is a messaging surface between people: a conversation log, delivery and read receipts, editing and deleting a message within a time window, replies, file attachments, and an optional conversation list. It is controlled — your app owns the messages and talks to the server; the component shows them and reports what the user does. It fills its container, so the same anatomy works inside a Drawer, a Card, or any sized region of a page.

Usage​

import { Chat } from '@takeoff-ui/react-spar';
<Chat>
<Chat.ConversationList>
<Chat.Conversation />
</Chat.ConversationList>
<Chat.Thread>
<Chat.Header>
<Chat.Title />
</Chat.Header>
<Chat.Pinned />
<Chat.Messages>
<Chat.Message>
<Chat.MessageActions />
</Chat.Message>
</Chat.Messages>
<Chat.Empty />
<Chat.Composer />
</Chat.Thread>
</Chat>

Chat.ConversationList and Chat.Thread are only needed for the split layout; a single conversation uses the thread parts directly under Chat.

Playground​

Send a message to watch it go from sending (clock) to sent (one tick), delivered (two ticks) and read (two coloured ticks). Hover one of your messages for Edit and Delete, or press ↑ in the empty field to edit your last message. Edits stay open for 15 minutes and deletes for an hour. Any message can be answered with Reply.


function PlaygroundDemo() {
  const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60000);
  const [messages, setMessages] = useState([
    { id: '1', senderId: 'ayse', text: 'Hi! Is the crew list for TK1979 ready?', createdAt: minutesAgo(32), status: 'read' },
    { id: '2', senderId: 'me', text: 'Almost — waiting for one confirmation.', createdAt: minutesAgo(30), status: 'read' },
    { id: '3', senderId: 'me', text: 'I will send it in 10 minutes.', createdAt: minutesAgo(29), status: 'read' },
    { id: '4', senderId: 'ayse', text: 'Great, thanks 🙏', createdAt: minutesAgo(2), status: 'delivered' },
  ]);
  const [typing, setTyping] = useState([]);

  const update = (id, patch) =>
    setMessages((list) => list.map((message) => (message.id === id ? { ...message, ...patch } : message)));

  // Stand-in for your server: the message is sent, delivered, read, then answered.
  const handleSend = (text, attachments, { replyTo }) => {
    const id = String(Date.now());
    // Keep a copy of what is quoted, for when the original is not loaded.
    const reply = replyTo && { id: replyTo.id, senderId: replyTo.senderId, text: replyTo.text };
    setMessages((list) => [...list, { id, senderId: 'me', text, createdAt: new Date(), status: 'sending', replyTo: reply }]);
    setTimeout(() => update(id, { status: 'sent' }), 500);
    setTimeout(() => update(id, { status: 'delivered' }), 1200);
    setTimeout(() => {
      update(id, { status: 'read' });
      setTyping(['ayse']);
    }, 2200);
    setTimeout(() => {
      setTyping([]);
      setMessages((list) => [
        ...list,
        { id: id + '-reply', senderId: 'ayse', text: 'Got it 👍', createdAt: new Date(), status: 'delivered' },
      ]);
    }, 4000);
  };

  return (
    <Card className="h-130 w-full max-w-110 overflow-hidden">
      <Chat
        messages={messages}
        currentUserId="me"
        participants={[{ id: 'me', name: 'You' }, { id: 'ayse', name: 'Ayşe Yılmaz' }]}
        typing={typing}
        editWindow={15 * 60000}
        deleteWindow={60 * 60000}
        onSend={handleSend}
        onEdit={(message, text) => update(message.id, { text, editedAt: new Date() })}
        onDelete={(message) => update(message.id, { deleted: true })}
        onRead={(read) => read.forEach((message) => update(message.id, { status: 'read' }))}
      >
        <Chat.Header>
          <Chat.Title>Ayşe Yılmaz</Chat.Title>
          <Badge variant="success" appearance="filledLight">Online</Badge>
        </Chat.Header>
        <Chat.Messages />
        <Chat.Empty>Say hello 👋</Chat.Empty>
        <Chat.Composer />
      </Chat>
    </Card>
  );
}

render(<PlaygroundDemo />);

Data model​

A message is a plain object; update it immutably when the server answers.

interface ChatMessage {
id: string;
senderId: string; // equals `currentUserId` for the user's own messages
text: string;
createdAt: Date | string | number;
editedAt?: Date | string | number; // shows "Edited"
deleted?: boolean; // shows "This message was deleted"
status?: 'sending' | 'sent' | 'delivered' | 'read' | 'failed';
attachments?: ChatAttachment[]; // the same entries Upload uses
replyTo?: { id: string; senderId?: string; text?: string }; // the message it answers
}
You want to…Do this
Send a messageHandle onSend(text): append it with status: 'sending', then move it to sent / delivered / read as the server reports.
Show whether the other side read itSet the status of the user's own messages. read draws the coloured double tick.
Mark incoming messages readHandle onRead(messages). It fires once per message when an unread incoming message is on screen while the page is visible. Tell the server, then set their status to read. It needs IntersectionObserver; without it nothing is reported.
Let users edit or delete for a whilePass onEdit / onDelete and editWindow / deleteWindow in milliseconds. The actions disappear when the window closes, and an edit in progress ends with it. Enforce the same limit on the server.
Let users take back a deleteDeleted messages offer Undo for undoWindow (5 seconds by default) and onDelete runs only after it, or when the chat unmounts. Pass undoWindow={0} to delete at once.
Let users send filesSet allowAttachments on Chat.Composer. onSend(text, attachments) gets the files; put them on the message and update each one's status / progress, then its url, as it uploads.
Let users answer a messageReply is on by default. onSend gets the answered message as details.replyTo; store { id, senderId, text } of it on the new message's replyTo.
Pin messagesPass pinnedIds and onPinChange, and place Chat.Pinned under the header.
Show who is typingPass typing with the participant ids.
Load historySet hasOlder and handle onLoadOlder; prepend the older messages. The reader stays on the same message.

Conversation list​

With a Chat.ConversationList the chat shows the list beside the thread. When the chat is narrower than 640px — a drawer, a phone — it shows one pane at a time: the list until a conversation is opened, then the thread with a back button in its header. Drive the open conversation with conversationId and onConversationChange, and swap messages with it.

function ConversationsDemo() {
const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60000);
const [conversationId, setConversationId] = useState('ops');
const [threads, setThreads] = useState({
ops: [
{ id: 'o1', senderId: 'mehmet', text: 'Gate changed to F4.', createdAt: minutesAgo(12), status: 'read' },
{ id: 'o2', senderId: 'me', text: 'Noted, informing the crew.', createdAt: minutesAgo(10), status: 'read' },
],
ayse: [{ id: 'a1', senderId: 'ayse', text: 'Can you check the roster?', createdAt: minutesAgo(3), status: 'delivered' }],
zeynep: [],
});
const conversations = [
{ id: 'ops', title: 'Ops team', preview: 'Noted, informing the crew.', updatedAt: minutesAgo(10) },
{ id: 'ayse', title: 'Ayşe Yılmaz', preview: 'Can you check the roster?', updatedAt: minutesAgo(3), unreadCount: threads.ayse.some((m) => m.status !== 'read') ? 1 : 0 },
{ id: 'zeynep', title: 'Zeynep Demir', preview: 'No messages yet' },
];
const messages = conversationId ? threads[conversationId] : [];
const setThread = (fn) => setThreads((all) => ({ ...all, [conversationId]: fn(all[conversationId]) }));
return (
<Card className="h-130 w-full overflow-hidden">
<Chat
messages={messages}
currentUserId="me"
participants={[{ id: 'me', name: 'You' }, { id: 'ayse', name: 'Ayşe Yılmaz' }, { id: 'mehmet', name: 'Mehmet Kaya' }]}
conversationId={conversationId}
onConversationChange={setConversationId}
onSend={(text) => setThread((list) => [...list, { id: String(Date.now()), senderId: 'me', text, createdAt: new Date(), status: 'sent' }])}
onRead={(read) => setThread((list) => list.map((m) => (read.some((r) => r.id === m.id) ? { ...m, status: 'read' } : m)))}
>
<Chat.ConversationList>
{conversations.map((conversation) => (
<Chat.Conversation key={conversation.id} conversation={conversation} />
))}
</Chat.ConversationList>
<Chat.Thread>
<Chat.Header>
<Chat.Title>{conversations.find((c) => c.id === conversationId)?.title ?? 'Chat'}</Chat.Title>
</Chat.Header>
<Chat.Messages />
<Chat.Empty>{conversationId ? 'No messages yet' : 'Pick a conversation'}</Chat.Empty>
<Chat.Composer />
</Chat.Thread>
</Chat>
</Card>
);
}
render(<ConversationsDemo />);

In a Drawer​

Chat takes the height of its container, so a Drawer.Body without padding is enough. Escape leaves message editing without closing the drawer.

function DrawerDemo() {
const [messages, setMessages] = useState([
{ id: '1', senderId: 'support', text: 'Hello! How can we help with your booking?', createdAt: new Date(), status: 'read' },
]);
return (
<Drawer placement="right">
<Drawer.Trigger as={Button}>Open chat</Drawer.Trigger>
<Drawer.Overlay />
<Drawer.Panel>
<Drawer.Header>
<Drawer.Title>Support</Drawer.Title>
<Drawer.Close />
</Drawer.Header>
<Drawer.Body className="p-0">
<Chat
messages={messages}
currentUserId="me"
onSend={(text) => setMessages((list) => [...list, { id: String(Date.now()), senderId: 'me', text, createdAt: new Date(), status: 'sent' }])}
>
<Chat.Messages />
<Chat.Composer />
</Chat>
</Drawer.Body>
</Drawer.Panel>
</Drawer>
);
}
render(<DrawerDemo />);

Group chat​

With more than one other participant, incoming messages show their author's name and avatar. Consecutive messages from one person within five minutes are grouped.

function GroupDemo() {
const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60000);
const participants = [
{ id: 'me', name: 'You' },
{ id: 'ayse', name: 'Ayşe Yılmaz' },
{ id: 'mehmet', name: 'Mehmet Kaya' },
];
const messages = [
{ id: '1', senderId: 'ayse', text: 'Briefing at 14:00 in room B.', createdAt: minutesAgo(20), status: 'read' },
{ id: '2', senderId: 'ayse', text: 'Please bring the updated manifests.', createdAt: minutesAgo(19), status: 'read' },
{ id: '3', senderId: 'mehmet', text: 'On my way.', createdAt: minutesAgo(5), status: 'read' },
{ id: '4', senderId: 'me', text: 'See you there.', createdAt: minutesAgo(1), status: 'delivered' },
];
return (
<Card className="h-110 w-full max-w-110 overflow-hidden">
<Chat messages={messages} currentUserId="me" participants={participants} typing={['mehmet']}>
<Chat.Header>
<Chat.Title>Cabin crew · TK1979</Chat.Title>
</Chat.Header>
<Chat.Messages />
<Chat.Composer />
</Chat>
</Card>
);
}
render(<GroupDemo />);

Replies​

Reply is in every message's menu while onSend is set (allowReplies={false} turns it off). The composer then shows the message being answered above the field, with a button (or Esc) to stop. onSend(text, attachments, { replyTo }) hands it over; put a reference to it on the new message's replyTo.

A reply quotes the original at the top of its bubble. While the original is in messages, the quote shows it as it is now — edited or deleted — and pressing the quote scrolls to it and highlights it for a moment. When it is not loaded, the quote falls back to the senderId and text stored on replyTo.

function RepliesDemo() {
const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60000);
const [messages, setMessages] = useState([
{ id: '1', senderId: 'ayse', text: 'Can you send me the gate info for TK1979?', createdAt: minutesAgo(40), status: 'read' },
{ id: '2', senderId: 'mehmet', text: 'Also: is the catering order final?', createdAt: minutesAgo(38), status: 'read' },
{ id: '3', senderId: 'ayse', text: 'Boarding starts 14:20.', createdAt: minutesAgo(30), status: 'read' },
{ id: '4', senderId: 'me', text: 'Gate F4, it changed this morning.', createdAt: minutesAgo(5), status: 'read', replyTo: { id: '1', senderId: 'ayse', text: 'Can you send me the gate info for TK1979?' } },
]);
return (
<Card className="h-120 w-full max-w-110 overflow-hidden">
<Chat
messages={messages}
currentUserId="me"
participants={[{ id: 'me', name: 'You' }, { id: 'ayse', name: 'Ayşe Yılmaz' }, { id: 'mehmet', name: 'Mehmet Kaya' }]}
onSend={(text, attachments, { replyTo }) =>
setMessages((list) => [
...list,
{
id: String(Date.now()),
senderId: 'me',
text,
createdAt: new Date(),
status: 'sent',
replyTo: replyTo && { id: replyTo.id, senderId: replyTo.senderId, text: replyTo.text },
},
])
}
>
<Chat.Header>
<Chat.Title>Ops team</Chat.Title>
</Chat.Header>
<Chat.Messages />
<Chat.Composer />
</Chat>
</Card>
);
}
render(<RepliesDemo />);

Attachments​

allowAttachments on Chat.Composer adds an attach button and takes files dropped on the composer or pasted into it. They wait above the field, each with a remove button, and go to onSend with the text — or on their own. accept, maxFileSize and maxFileCount limit what the composer takes; onFilesReject reports what it turned down, so you can tell the user.

A file is a ChatAttachment, the same entry Upload uses. On a message, uploaded images show as previews and other files as rows with a download button. A file that is still uploading shows its progress, and a failed one says so. Here the upload is simulated.

function AttachmentsDemo() {
const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60000);
const [messages, setMessages] = useState([
{
id: '1',
senderId: 'ayse',
text: 'Here is the updated roster.',
createdAt: minutesAgo(8),
status: 'read',
attachments: [{ id: 'f1', name: 'crew-roster-may.pdf', type: 'application/pdf', size: 248000, url: '#' }],
},
]);
const updateFile = (messageId, fileId, patch) =>
setMessages((list) =>
list.map((message) =>
message.id === messageId
? { ...message, attachments: message.attachments.map((file) => (file.id === fileId ? { ...file, ...patch } : file)) }
: message,
),
);
// Stand-in for your upload: progress in steps, then done.
const handleSend = (text, attachments) => {
const id = String(Date.now());
const files = attachments.map((file) => ({ ...file, status: 'uploading', progress: 0 }));
setMessages((list) => [...list, { id, senderId: 'me', text, createdAt: new Date(), status: 'sent', attachments: files }]);
files.forEach((file) => {
[25, 50, 75].forEach((progress, step) => setTimeout(() => updateFile(id, file.id, { progress }), 400 * (step + 1)));
setTimeout(() => updateFile(id, file.id, { status: 'completed' }), 1600);
});
};
return (
<Card className="h-130 w-full max-w-110 overflow-hidden">
<Chat
messages={messages}
currentUserId="me"
participants={[{ id: 'me', name: 'You' }, { id: 'ayse', name: 'Ayşe Yılmaz' }]}
onSend={handleSend}
>
<Chat.Header>
<Chat.Title>Ayşe Yılmaz</Chat.Title>
</Chat.Header>
<Chat.Messages />
<Chat.Composer allowAttachments accept="image/*,.pdf,.docx,.xlsx" maxFileSize={10 * 1024 * 1024} maxFileCount={5} />
</Chat>
</Card>
);
}
render(<AttachmentsDemo />);

Message actions​

A message's menu lists what applies to it, in this order:

  • Reply — on by default while onSend is set; allowReplies={false} turns it off.
  • Copy — on by default for messages with text; allowCopy={false} turns it off.
  • Pin / Unpin — set pinnedIds and onPinChange. Chat.Pinned shows the pinned messages in a bar: pressing it scrolls to the one shown and moves on to the one pinned before it.
  • Edit and Delete — on the user's own messages, with onEdit / onDelete, while their windows are open.

Compose Chat.MessageActions inside Chat.Message to add your own items after them — here Create task. The edit and delete windows are 30 seconds, so those two disappear shortly after a message is sent.

const toaster = createToaster({ placement: 'top-end' });
function ActionsDemo() {
const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60000);
const [messages, setMessages] = useState([
{ id: '1', senderId: 'ayse', text: 'New boarding time for TK1979 is 14:20.', createdAt: minutesAgo(20), status: 'read' },
{ id: '2', senderId: 'mehmet', text: 'Seat 14C is broken, can someone report it to maintenance?', createdAt: minutesAgo(2), status: 'read' },
{ id: '3', senderId: 'me', text: 'On it.', createdAt: minutesAgo(1), status: 'read' },
]);
const [pinnedIds, setPinnedIds] = useState(['1']);
const update = (id, patch) => setMessages((list) => list.map((m) => (m.id === id ? { ...m, ...patch } : m)));
// Your own action: a maintenance task made from the message.
const createTask = (message) =>
toaster.success({ title: 'Task created', description: message.text });
return (
<Card className="h-120 w-full max-w-110 overflow-hidden">
<Chat
messages={messages}
currentUserId="me"
participants={[{ id: 'me', name: 'You' }, { id: 'ayse', name: 'Ayşe Yılmaz' }, { id: 'mehmet', name: 'Mehmet Kaya' }]}
editWindow={30000}
deleteWindow={30000}
pinnedIds={pinnedIds}
onPinChange={(message, pinned) => setPinnedIds((ids) => (pinned ? [...ids, message.id] : ids.filter((id) => id !== message.id)))}
onSend={(text) => setMessages((list) => [...list, { id: String(Date.now()), senderId: 'me', text, createdAt: new Date(), status: 'sent' }])}
onEdit={(message, text) => update(message.id, { text, editedAt: new Date() })}
onDelete={(message) => update(message.id, { deleted: true })}
>
<Chat.Header>
<Chat.Title>Ops team</Chat.Title>
</Chat.Header>
<Chat.Pinned />
<Chat.Messages>
{(message) => (
<Chat.Message message={message}>
<Chat.MessageActions>
<Dropdown.Separator />
<Dropdown.Item onSelect={() => createTask(message)}>
<BuildIconOutlinedRounded aria-hidden="true" />
Create task
</Dropdown.Item>
</Chat.MessageActions>
</Chat.Message>
)}
</Chat.Messages>
<Chat.Composer />
</Chat>
<Toaster toaster={toaster} />
</Card>
);
}
render(<ActionsDemo />);

Localization​

Every visible string and accessible name comes from labels; locale formats times and dates. {names}, {name} and {count} are placeholders. Set them once for the whole app through TakeoffSparProvider's components.Chat.defaultProps.labels.

function LocalizationDemo() {
const labels = {
placeholder: 'Mesaj yazın…',
send: 'Gönder',
save: 'Değişiklikleri kaydet',
editing: 'Mesaj düzenleniyor',
cancelEdit: 'Düzenlemeyi iptal et',
messageActions: 'Mesaj işlemleri',
edit: 'Düzenle',
delete: 'Sil',
undo: 'Geri al',
copy: 'Kopyala',
copied: 'Kopyalandı',
pin: 'Sabitle',
unpin: 'Sabitlemeyi kaldır',
pinned: 'Sabitlenmiş mesaj',
pinnedPosition: '{index}/{count}',
reply: 'Yanıtla',
replyingTo: '{name} kişisine yanıt',
cancelReply: 'Yanıtı iptal et',
inReplyTo: 'Yanıtlanan mesaj',
you: 'Siz',
originalMessage: 'Asıl mesaj',
attach: 'Dosya ekle',
attachments: 'Gönderilecek dosyalar',
removeAttachment: '{name} dosyasını kaldır',
downloadAttachment: '{name} dosyasını indir',
openAttachment: '{name} dosyasını aç',
uploading: 'Yükleniyor…',
uploadFailed: 'Yüklenemedi',
uploadProgress: '{name} yükleme durumu',
edited: 'Düzenlendi',
deleted: 'Bu mesaj silindi',
today: 'Bugün',
yesterday: 'Dün',
sending: 'Gönderiliyor',
sent: 'Gönderildi',
delivered: 'İletildi',
read: 'Okundu',
failed: 'İletilemedi',
retry: 'Tekrar dene',
typing: '{names} yazıyor…',
typingMany: '{names} yazıyor…',
messages: 'Mesajlar',
};
const [messages, setMessages] = useState([
{ id: '1', senderId: 'ayse', text: 'Merhaba!', createdAt: new Date(Date.now() - 86400000), status: 'read' },
{ id: '2', senderId: 'me', text: 'Merhaba, nasılsın?', createdAt: new Date(), status: 'read', editedAt: new Date() },
]);
return (
<Card className="h-100 w-full max-w-110 overflow-hidden">
<Chat
messages={messages}
currentUserId="me"
locale="tr-TR"
labels={labels}
onSend={(text) => setMessages((list) => [...list, { id: String(Date.now()), senderId: 'me', text, createdAt: new Date(), status: 'sent' }])}
onEdit={(message, text) => setMessages((list) => list.map((m) => (m.id === message.id ? { ...m, text, editedAt: new Date() } : m)))}
>
<Chat.Messages />
<Chat.Composer allowAttachments />
</Chat>
</Card>
);
}
render(<LocalizationDemo />);

Accessibility​

  • The log is a role="log" region, so screen readers announce new messages. It is focusable for keyboard scrolling.
  • Delivery status icons carry a text alternative ("Sent", "Read", …).
  • Enter sends, Shift+Enter adds a line, and Enter during an IME composition does not send.
  • ↑ in an empty field edits your last editable message; Esc leaves editing. While editing, the field is named "Editing message".
  • The message menu button sits next to the top of the bubble and appears on hover and keyboard focus. A right click on the bubble opens the same menu (unless text in it is selected, so it can still be copied), and on touch screens a long press opens it.
  • Copy confirms with a "Copied" note under the message, which a polite status region also reads out.
  • The pinned bar is a button named after the pinned message ("Pinned message · 2 of 3 …"); a pinned message's meta line carries a pin with the text "Pinned message".
  • A quote is read as "In reply to" its author and text; when the original is loaded it is a button that scrolls to it. While answering, the field is named "Replying to" the author, and Esc stops answering.
  • The attach button is named "Attach files", and the files waiting to be sent are a group named "Files to send", each with a remove button named after the file ("Remove report.pdf"). Files can also be dropped on the composer or pasted into the field.
  • After Delete, focus moves to the message's Undo button; once the undo window ends, it moves on to the composer.

API Reference​

Chat​

Props​

NameTypeDefaultDescription
messagesChatMessage[]-The conversation, oldest first.
currentUserIdstring-The signed-in user. Messages whose senderId matches are drawn as the user's own.
participantsChatParticipant[]-Everyone in the conversation, for names and avatars. With more than one other participant the chat is drawn as a group: incoming messages show their author's name and avatar.
allowRepliesbooleantrueReply in every message's menu, while onSend is set. The composer then shows what is being answered, and onSend gets it as details.replyTo — store it on the new message's replyTo.
pinnedIdsstring[]-Ids of the pinned messages, oldest pin first. Pair with onPinChange.
allowCopybooleantrueCopy in the menu of every message with text. It also works in a readOnly or disabled chat, since it changes nothing.
editWindownumber-How long after createdAt a message can still be edited, in milliseconds. Leave it unset for no limit. The Edit action disappears once it passes.
deleteWindownumber-How long after createdAt a message can still be deleted, in milliseconds. Leave it unset for no limit. The Delete action disappears once it passes.
undoWindownumber5000How long a deleted message can still be restored, in milliseconds. Until then it shows as deleted with an Undo button, and onDelete is called when the time is up — or right away if the chat unmounts first. 0 calls onDelete at once.
typingstring[]-Ids of the participants who are typing right now. Shows the typing line at the end of the log.
hasOlderboolean-Shows a Load older messages button at the top of the log. Scrolling to the top loads them too.
isLoadingOlderboolean-Older messages are loading: the button shows a spinner and the log is marked busy.
conversationIdstring | null-The open conversation (controlled), for chats with a Chat.ConversationList. null means none is open. Pair with onConversationChange.
defaultConversationIdstring | null-The conversation open at first (uncontrolled).
disabledboolean-Turns the composer and the message actions (except Copy) off, e.g. while offline.
readOnlyboolean-View-only conversation: no composer, and Copy is the only message action.
localestringthe browser's localeBCP 47 locale for times and dates, e.g. 'tr-TR'.
labelsPartial<ChatLabels>-Texts of the chat, e.g. a translation. Anything left out stays in English.
childrenReact.ReactNode-The parts: Chat.Header, Chat.Messages, Chat.Empty, Chat.Composer, and optionally Chat.ConversationList + Chat.Thread.
classNamesPartial<Record<"root", string>>-
slotPropsPartial<Record<"root", React.HTMLAttributes<HTMLElement>>>-
classNamestring-Appends custom classes to the root slot.

Events​

NameTypeDefaultDescription
onSend(text: string, attachments: ChatAttachment[], details: ChatSendDetails) => void-Called when the user sends a message, with its trimmed text and the files added in the composer (Chat.Composer's allowAttachments). The text is empty when only files are sent. Each file carries a fresh id and its file; upload it and put it on the message as an attachment.
onEdit(message: ChatMessage, text: string) => void-Called with the message and its new trimmed text when an edit is saved. Setting it turns on the Edit action for the user's own messages.
onDelete(message: ChatMessage) => void-Called when the user deletes one of their messages, once undoWindow has passed without an undo. Setting it turns on the Delete action.
onRead(messages: ChatMessage[]) => void-Called with incoming messages that are not 'read' yet once they are on screen while the page is visible — mark them read on the server and set their status to 'read'. A message is reported once. Needs IntersectionObserver; where it is missing (e.g. jsdom) nothing is reported, so mock it in tests.
onPinChange(message: ChatMessage, pinned: boolean) => void-Called when the user pins or unpins a message. Setting it turns on Pin / Unpin in every message's menu; Chat.Pinned shows the pinned ones.
onRetry(message: ChatMessage) => void-Called from the Retry button under a 'failed' message. The button is shown only when this is set.
onLoadOlder() => void-Called to load older messages. Prepend them to messages; the reader's place in the log is kept.
onConversationChange(id: string | null) => void-Called when the user opens a conversation, or goes back to the list (null).

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.
data-layoutAlways (single | split)split while a Chat.ConversationList is mounted: list and thread side by side.
data-viewAlways (list | thread)Which pane a narrow split chat shows — the list until a conversation is open.
data-disabledWhen disabledStyling hook for the disabled state.
data-readonlyWhen readOnlyStyling hook for the view-only state.

Chat.ConversationList​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Conversation​

Props​

NameTypeDefaultDescription
conversationChatConversation-The conversation this item opens.
classNamesPartial<Record<ChatConversationSlot, string>>-
slotPropsPartial<Record<ChatConversationSlot, React.HTMLAttributes<HTMLElement>>>-
classNamestring-Appends custom classes to the root slot.

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.
data-selectedWhen it is the open conversationSelected treatment; aria-current="true" is set too.
data-unreadWhen unreadCount is above zeroUnread treatment (bold title).

Chat.Thread​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Header​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Title​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Pinned​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Messages​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Message​

Props​

NameTypeDefaultDescription
messageChatMessage-The message this row renders.
childrenReact.ReactNode-Replaces the text inside the bubble. A composed Chat.MessageActions becomes the row's menu.
classNamesPartial<Record<ChatMessageSlot, string>>-
slotPropsPartial<Record<ChatMessageSlot, React.HTMLAttributes<HTMLElement>>>-
classNamestring-Appends custom classes to the root slot.

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.
data-ownOn the current user's messagesAligns the row to the end and colours the bubble.
data-statusWhen the message has a statusDelivery state: sending | sent | delivered | read | failed.
data-deletedWhen deleted, or deleted and waiting out undoWindowDeleted-message treatment.
data-deletingWhile a delete can still be undoneDims the message until onDelete runs.
data-groupedWhen it continues the previous message’s groupTighter spacing; hides the repeated avatar.
data-editingWhile the composer edits or answers itOutlines the message the composer is working on.
data-pinnedWhen its id is in pinnedIdsShows the pin in the meta line.
data-highlightedFor a moment after a quote jumps to itFlashes the bubble so the eye finds it.

Chat.MessageActions​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Empty​

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.

Chat.Composer​

Props​

NameTypeDefaultDescription
valuestring-The draft (controlled). Pair with onValueChange.
defaultValuestring-The draft at first (uncontrolled).
maxLengthnumber-Longest message the user can send.
placeholderstring-Placeholder of the text field. Defaults to labels.placeholder.
startContentReact.ReactNode-Controls before the text field, e.g. an attach button.
endContentReact.ReactNode-Controls between the text field and the send button, e.g. an emoji picker.
allowAttachmentsboolean-Lets the user add files: an attach button, dropping files on the composer, and pasting them. They go to onSend with the text.
acceptstring-File types the composer takes, as in an <input type="file"> accept, e.g. 'image/*,.pdf'.
maxFileSizenumber-Largest file the composer takes, in bytes.
maxFileCountnumber-Most files one message can carry.
classNamesPartial<Record<ChatComposerSlot, string>>-
slotPropsPartial<Record<ChatComposerSlot, React.HTMLAttributes<HTMLElement>>>-
classNamestring-Appends custom classes to the root slot.

Events​

NameTypeDefaultDescription
onValueChange(value: string) => void-Called with the draft on every change, including when it is cleared after sending.
onFilesReject(rejections: UploadRejection[]) => void-Called with the files the composer turned down (type, size or count) — the composer shows nothing for them, so tell the user, e.g. with a toast.

Data attributes​

AttributeApplied whenPurpose
data-slot="root"AlwaysStable selector for wrapper styling on the root slot.
data-editingWhile a message is being editedEditing treatment of the composer.
data-drag-stateWhile files are dragged over it (allowAttachments)accept | reject — the drop-target treatment; reject for types outside accept or while editing.

Type Definitions​

NameDefinition
ChatMessage{ id: string; senderId: string; text: string; createdAt: ChatTimestamp; editedAt?: ChatTimestamp; deleted?: boolean; status?: ChatMessageStatus; attachments?: ChatAttachment[]; replyTo?: ChatReply }
ChatParticipant{ id: string; name: string; avatar?: string | ReactNode }
ChatLabels{ conversations: string; back: string; messages: string; loadOlder: string; today: string; yesterday: string; typing: string; typingMany: string; jumpToLatest: string; newMessages: string; placeholder: string; send: string; save: string; editing: string; cancelEdit: string; messageActions: string; edit: string; delete: string; undo: string; edited: string; deleted: string; sending: string; sent: string; delivered: string; read: string; failed: string; retry: string; unread: string; copy: string; pin: string; unpin: string; pinned: string; pinnedPosition: string; copied: string; reply: string; replyingTo: string; cancelReply: string; inReplyTo: string; you: string; originalMessage: string; attach: string; attachments: string; removeAttachment: string; downloadAttachment: string; openAttachment: string; uploading: string; uploadFailed: string; uploadProgress: string }
ChatAttachment{ id: string; file?: File; name?: string; size?: number; type?: string; url?: string; thumbUrl?: string; status?: UploadFileStatus; progress?: number; error?: string }
ChatSendDetails{ replyTo?: ChatMessage }
ChatConversation{ id: string; title: string; avatar?: string | ReactNode; preview?: ReactNode; updatedAt?: ChatTimestamp; unreadCount?: number }
ChatConversationSlot'root' | 'avatar' | 'body' | 'title' | 'preview' | 'time' | 'unread'
ChatHeaderSlot'root' | 'back'
ChatPinnedSlot'root' | 'jump' | 'label' | 'text' | 'unpin'
ChatMessagesSlot'root' | 'viewport' | 'content' | 'loadOlder' | 'divider' | 'typing' | 'typingDots' | 'jump'
ChatMessageSlot| 'root' | 'avatar' | 'body' | 'author' | 'bubble' | 'text' | 'meta' | 'time' | 'edited' | 'status' | 'retry' | 'undo' | 'attachments' | 'image' | 'quote' | 'quoteAuthor' | 'quoteText' | 'copied' | 'pinned'
ChatComposerSlot'root' | 'editing' | 'cancel' | 'replying' | 'cancelReply' | 'controls' | 'send' | 'upload' | 'attach' | 'attachments'
UploadRejection| { file: File; code: 'file-invalid-type'; /** The accept list the file failed to match. */ accept: string; } | { file: File; code: 'file-too-large'; /** The maxFileSize (bytes) the file exceeded. _/ maxFileSize: number; } | { file: File; code: 'too-many-files'; /** How many files were allowed — maxFileCount, or 1 without multiple. _/ maxFileCount: number; }