@dialtribe/chat-client
v0.5.1
Published
Official DialTribe Chat SDK for React - Chat components, hooks, and real-time messaging
Maintainers
Readme
@dialtribe/chat-client
React SDK for Dialtribe chat: live rooms, private messages (DMs), and a drop-in messages rail. Your app keeps its own users. You tell Dialtribe who the signed-in user is, and the SDK renders everyone from the identity your backend supplied. DMs are isolated to your app.
yarn add @dialtribe/chat-clientHow it fits together
Your backend mints a session token for the signed-in user with your Dialtribe secret key:
POST https://dialtribe.com/api/public/v1/sessions Authorization: Bearer dt_sk_... { "permissions": ["chat:read", "chat:write"], "user_id": "u_123", "metadata": { "name": "Sarah", "avatarUrl": "https://cdn.example.com/sarah.png" }, "ttl": 3600 }user_idis your own user id.name(max 100 chars) andavatarUrl(max 500 chars) are what other users see. Chat roles (host,mod,vip) come frompermissions.Your frontend hands that token to the provider through a callback. The SDK calls it on connect and again whenever the token is rejected, so return a fresh one once the old one expires.
DM policy stays yours. When a user blocks someone or changes who can DM them, push it from your backend:
PUT https://dialtribe.com/api/public/v1/chat/users/u_123 Authorization: Bearer dt_sk_... { "dmPermission": "invite", "blockedUserIds": ["u_9"] }dmPermissionisopen,invite(default),private, orclosed. A blocked user's requests look sent to them but never arrive.
Quick start: the messages rail
import { DialtribeChatProvider, DialtribeMessages } from "@dialtribe/chat-client";
import "@dialtribe/chat-client/styles.css";
export function App({ user }: { user: { id: string } | null }) {
if (!user) return <YourApp />;
return (
<DialtribeChatProvider
key={user.id}
serverUrl="https://chatws.dialtribe.com"
getSessionToken={() => fetch("/api/chat-token").then((r) => r.text())}
>
<YourApp />
<DialtribeMessages placement="push" theme={{ accent: "#ef4444" }} />
</DialtribeChatProvider>
);
}Mount the provider only while someone is signed in, keyed by their user id. Signing out or switching accounts then drops the old connection, inbox and token rather than showing one user's messages to the next.
- Desktop: a rail pinned to the right edge (or the left, with
side="left") holding the inbox, your contexts, recent DMs and unread badges, with a panel that opens beside it.placement="push"pads the page so nothing is covered;"overlay"floats over it. For your own fixed-position elements the root element exposes--dtc-messages-inset(the width), plus--dtc-messages-sideanddata-dtc-messages-side(leftorright). - Mobile: a floating button with a total badge. Tap it, or swipe in from the right edge, to open; swipe right or press Escape to close.
Start a DM from your own UI (a profile's "Message" button):
import { useDialtribeMessages } from "@dialtribe/chat-client";
function MessageButton({ user }: { user: { id: string; name: string } }) {
const messages = useDialtribeMessages();
return <button onClick={() => messages.messageUser(user.id, { name: user.name })}>Message</button>;
}messageUser opens the thread right away. It rejects with
ChatRequestError code dm-not-allowed when the recipient doesn't accept DMs.
<DialtribeMessages> props
| Prop | Default | |
|------|---------|--|
| side | "right" | Which screen edge the rail docks to: "left" or "right" |
| placement | "push" | "push" or "overlay" (desktop) |
| openPlacement | "push" | With placement="push": whether the open panel also pushes ("push") or overlays ("overlay"). The collapsed rail always pushes |
| items | [] | Your own rail entries with your own panels (RailItem[], see below) |
| inboxRowClose | true | An X on inbox conversations that removes them from the user's inbox (see hideDM) |
| contexts | [] | Extra rail entries, e.g. live shows: { roomId, label, avatarUrl?, badge? } |
| theme | | { accent, background, surface, text, textMuted, border } |
| labels | English | Override any string (MessagesLabels) to localize |
| confirm | built-in dialog | (options) => Promise<boolean>: show the mute and archive confirmations in your own modal (ConfirmOptions: title, body, confirmLabel, cancelLabel) |
| panelWidth | 380 | Desktop panel width in px |
| railDmLimit | 5 | Recent DMs shown as rail icons |
| mobileBreakpoint | 768 | Below this width the rail becomes the floating button |
| notifications | false | Show the Dialtribe Notifications inbox: a bell above Messages with an unread badge (see below). Pass { onOpen(item) } to route clicks yourself; return true when you navigated |
Your own rail items
Use the rail as your app's general-purpose rail: each item is your trigger (shown with the rail-button chrome, active ring and badge) plus your panel (any React, no header imposed).
<DialtribeMessages
items={[{
id: "account",
placement: "footer", // "top" (default) above the inbox, "bottom" below the DMs,
// "footer" pinned to the bottom edge (doesn't scroll)
label: "Account",
trigger: ({ active }) => <ProfileAvatar active={active} />,
panel: ({ close }) => <AccountMenu onDone={close} />,
badge: 0,
}]}
/>Don't put a <button> inside trigger: the rail wraps it in one. Clicking an
active trigger closes the panel, and useDialtribeMessages().openItem("account")
opens it from anywhere. On mobile the item lives in the drawer like everything
else.
Notifications
notifications adds your users' in-app notifications to the rail. Your backend
sends them to Dialtribe with your secret key; the rail reads them with the same
session token as chat, and new ones arrive live on the existing connection.
// Your server
await fetch("https://dialtribe.com/api/public/v1/notifications", {
method: "POST",
headers: { Authorization: `Bearer ${DIALTRIBE_SECRET_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
eventType: "chat.mention",
recipients: ["123"], // your user ids, up to 1,000 per call
dedupeKey: "mention:msg_9981", // re-sending never notifies anyone twice
title: "milkbox mentioned you",
body: "hey @you, listen to this",
url: "https://yourapp.com/rooms/42",
actor: { userId: "1", name: "milkbox", avatarUrl: "https://..." },
groupKey: "kudos:msg_9981", // optional: repeats show as one row
}),
});<DialtribeMessages notifications={{ onOpen: (item) => { router.push(item.url); return true; } }} />The provider's apiUrl (default https://dialtribe.com) is where notifications
are read from.
Hooks
All hooks must be under <DialtribeChatProvider>, which owns one connection
for the whole app.
useChatRooms()
The signed-in user's DMs, live:
const {
rooms, // every DM, newest first (DmRoomSummary[])
requests, // incoming requests not yet answered
totalUnread, // across unmuted, accepted DMs
requestDM, acceptDM, ignoreDM, closeDM, reopenDM, hideDM,
addParticipant, setMuted, setArchived, markRead, setVisible, refresh,
} = useChatRooms();A request id is the DM's room id. Ignoring is silent: the requester keeps seeing "Request sent". Adding someone to a 1:1 starts a new group conversation.
hideDM(roomId) removes a conversation from this user's inbox only. Nothing is
deleted and the other person sees no change; it comes back when a newer message
arrives or when the user messages or reopens it. closeDM is different: it
closes the conversation for everyone and makes it read-only.
setArchived(roomId, true) archives a conversation for this user only: it
leaves their rail, stays in their inbox under Archived (isArchived on each
room), and its unread still counts toward totalUnread. New messages don't
unarchive it. In <DialtribeMessages> each conversation's menu (the kebab
next to the close X) offers Mute notifications and Archive conversation, each
behind a confirmation.
useDialtribeChat({ roomId })
One room (a DM or a show room): messages, config, typingUsers, status,
error, plus sendMessage, loadOlderMessages, reactions, and host/mod
actions. Actions return promises and reject with ChatRequestError
(rate-limited carries retryAfterMs). Components showing the same room share
one subscription.
useDialtribeMessages()
Drive the rail: open, close, toggle, openInbox, openRoom(roomId), openItem(itemId),
openNotifications(), messageUser(userId, hint?), isOpen, view.
useDialtribeNotifications()
{ items, unreadCount, status, hasMore, loadingMore, error } plus refresh,
loadMore, markRead(ids), markAllRead, markSeen, click(ids). Use it to
build your own notifications UI, or render <NotificationsPanel labels={...} />
anywhere under the provider.
useChatConnection()
{ state, self, error }, where self is the signed-in user as your backend
described them.
Building your own UI
<ChatRoomProvider roomId={roomId}>
<ChatPanel showAvatars showModActions={isHost} />
</ChatRoomProvider>ChatPanel, ChatMessageItem, ChatInput and Avatar are exported. Outside
React, ChatClient is the framework-agnostic core the hooks are built on.
Theming
Everything is styled with dtc- classes and CSS variables: --dtc-accent,
--dtc-bg, --dtc-surface, --dtc-text, --dtc-text-muted, --dtc-border,
--dtc-danger. Set them on any ancestor, or use the theme prop.
Testing
yarn test:integration runs real clients against a local chat-ws + Centrifugo
(sessions sess_alice, sess_bob, sess_carol for users alice, bob and carol
of one app). Configure with CHAT_SERVER_URL, CENTRIFUGO_API_URL and
CENTRIFUGO_API_KEY. Start from an empty chat database and a fresh chat-ws.
