@dialtribe/chat-client 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -328,6 +328,19 @@ var InboxStore = class extends Store {
328
328
  this.patchRoom(roomId, (room) => ({ ...room, isMuted: muted }));
329
329
  await this.client.dm("chat-dm-mute", { roomId, muted });
330
330
  }
331
+ /**
332
+ * Archive or unarchive for the signed-in user only (optimistic). The room
333
+ * leaves the rail but stays in the inbox; new messages don't unarchive it.
334
+ */
335
+ async setArchived(roomId, archived) {
336
+ this.patchRoom(roomId, (room) => ({ ...room, isArchived: archived }));
337
+ try {
338
+ await this.client.dm("chat-dm-archive", { roomId, archived });
339
+ } catch (err) {
340
+ this.patchRoom(roomId, (room) => ({ ...room, isArchived: !archived }));
341
+ throw err;
342
+ }
343
+ }
331
344
  /** Mark a room read now (optimistic). */
332
345
  async markRead(roomId) {
333
346
  this.patchRoom(roomId, (room) => room.unreadCount === 0 ? room : { ...room, unreadCount: 0 });
@@ -453,6 +466,156 @@ var InboxStore = class extends Store {
453
466
  }
454
467
  };
455
468
 
469
+ // src/client/NotificationsStore.ts
470
+ var NotificationsStore = class extends Store {
471
+ constructor(client) {
472
+ super({ status: "idle", items: [], unreadCount: 0, hasMore: false, loadingMore: false, error: null });
473
+ this.client = client;
474
+ this.refs = 0;
475
+ this.unlisten = [];
476
+ this.refreshTimer = null;
477
+ this.nextCursor = null;
478
+ }
479
+ acquire() {
480
+ this.refs += 1;
481
+ if (this.refs > 1) return;
482
+ this.unlisten = [
483
+ this.client.on("connected", () => this.scheduleRefresh(0)),
484
+ this.client.on("user", (event) => this.onUserEvent(event))
485
+ ];
486
+ void this.client.start();
487
+ this.scheduleRefresh(0);
488
+ }
489
+ release() {
490
+ this.refs = Math.max(0, this.refs - 1);
491
+ if (this.refs > 0) return;
492
+ for (const off of this.unlisten) off();
493
+ this.unlisten = [];
494
+ if (this.refreshTimer) clearTimeout(this.refreshTimer);
495
+ }
496
+ // ===========================================================================
497
+ // Actions
498
+ // ===========================================================================
499
+ /** Reload the first page and the unread count. */
500
+ async refresh() {
501
+ if (this.getSnapshot().status === "idle") this.update({ status: "loading" });
502
+ try {
503
+ const page = await this.client.api("/notifications/inbox?limit=30");
504
+ this.nextCursor = page.nextCursor;
505
+ this.update({
506
+ status: "ready",
507
+ items: page.items,
508
+ unreadCount: page.unreadCount,
509
+ hasMore: page.nextCursor !== null,
510
+ error: null
511
+ });
512
+ } catch (err) {
513
+ this.update({
514
+ status: "error",
515
+ error: err instanceof ChatRequestError ? err : new ChatRequestError("network", "Could not load notifications")
516
+ });
517
+ }
518
+ }
519
+ /** Append the next (older) page. */
520
+ async loadMore() {
521
+ const snap = this.getSnapshot();
522
+ if (!this.nextCursor || snap.loadingMore) return;
523
+ this.update({ loadingMore: true });
524
+ try {
525
+ const page = await this.client.api(
526
+ `/notifications/inbox?limit=30&cursor=${encodeURIComponent(this.nextCursor)}`
527
+ );
528
+ this.nextCursor = page.nextCursor;
529
+ const have = new Set(this.getSnapshot().items.map((i) => i.id));
530
+ this.update({
531
+ items: [...this.getSnapshot().items, ...page.items.filter((i) => !have.has(i.id))],
532
+ hasMore: page.nextCursor !== null,
533
+ unreadCount: page.unreadCount
534
+ });
535
+ } finally {
536
+ this.update({ loadingMore: false });
537
+ }
538
+ }
539
+ /** Mark items read (optimistic). */
540
+ async markRead(ids) {
541
+ const unread = ids.filter((id) => this.getSnapshot().items.some((i) => i.id === id && !i.readAt));
542
+ if (unread.length === 0) return;
543
+ this.applyRead(unread, Math.max(0, this.getSnapshot().unreadCount - unread.length));
544
+ const { unreadCount } = await this.client.api("/notifications/inbox", {
545
+ method: "POST",
546
+ body: { action: "read", ids: unread }
547
+ });
548
+ this.update({ unreadCount });
549
+ }
550
+ /** Mark everything read (optimistic). */
551
+ async markAllRead() {
552
+ this.applyRead(null, 0);
553
+ const { unreadCount } = await this.client.api("/notifications/inbox", {
554
+ method: "POST",
555
+ body: { action: "read-all" }
556
+ });
557
+ this.update({ unreadCount });
558
+ }
559
+ /** Record that the list was shown (for stats; doesn't change unread). */
560
+ async markSeen() {
561
+ const unseen = this.getSnapshot().items.filter((i) => !i.seenAt).map((i) => i.id);
562
+ if (unseen.length === 0) return;
563
+ const now = (/* @__PURE__ */ new Date()).toISOString();
564
+ const set = new Set(unseen);
565
+ this.update({ items: this.getSnapshot().items.map((i) => set.has(i.id) ? { ...i, seenAt: now } : i) });
566
+ await this.client.api("/notifications/inbox", { method: "POST", body: { action: "seen", ids: unseen } });
567
+ }
568
+ /** Record a click (also marks read). Pass every id in a grouped row. */
569
+ async click(ids) {
570
+ if (ids.length === 0) return;
571
+ const now = (/* @__PURE__ */ new Date()).toISOString();
572
+ const set = new Set(ids);
573
+ const newlyRead = this.getSnapshot().items.filter((i) => set.has(i.id) && !i.readAt).length;
574
+ this.update({
575
+ items: this.getSnapshot().items.map(
576
+ (i) => set.has(i.id) ? { ...i, clickedAt: i.clickedAt ?? now, readAt: i.readAt ?? now } : i
577
+ ),
578
+ unreadCount: Math.max(0, this.getSnapshot().unreadCount - newlyRead)
579
+ });
580
+ const { unreadCount } = await this.client.api("/notifications/inbox", {
581
+ method: "POST",
582
+ body: { action: "click", ids }
583
+ });
584
+ this.update({ unreadCount });
585
+ }
586
+ // ===========================================================================
587
+ // Live updates
588
+ // ===========================================================================
589
+ onUserEvent(event) {
590
+ if (event.type === "notification.created") {
591
+ const items = this.getSnapshot().items;
592
+ if (items.some((i) => i.id === event.notification.id)) return;
593
+ this.update({
594
+ items: [event.notification, ...items],
595
+ unreadCount: typeof event.unreadCount === "number" ? event.unreadCount : this.getSnapshot().unreadCount + (event.notification.readAt ? 0 : 1)
596
+ });
597
+ } else if (event.type === "notification.read") {
598
+ this.applyRead(event.ids, event.unreadCount);
599
+ }
600
+ }
601
+ applyRead(ids, unreadCount) {
602
+ const now = (/* @__PURE__ */ new Date()).toISOString();
603
+ const set = ids ? new Set(ids) : null;
604
+ this.update({
605
+ items: this.getSnapshot().items.map((i) => !i.readAt && (!set || set.has(i.id)) ? { ...i, readAt: now } : i),
606
+ unreadCount
607
+ });
608
+ }
609
+ scheduleRefresh(delayMs) {
610
+ if (this.refs === 0) return;
611
+ if (this.refreshTimer) clearTimeout(this.refreshTimer);
612
+ this.refreshTimer = setTimeout(() => {
613
+ this.refreshTimer = null;
614
+ void this.refresh();
615
+ }, delayMs);
616
+ }
617
+ };
618
+
456
619
  // src/client/ChatClient.ts
457
620
  var ConnectionStore = class extends Store {
458
621
  set(patch) {
@@ -472,7 +635,9 @@ var ChatClient = class {
472
635
  this.generation = 0;
473
636
  this.rooms = /* @__PURE__ */ new Map();
474
637
  this.inboxStore = null;
638
+ this.notificationsStore = null;
475
639
  this.serverUrl = options.serverUrl.replace(/\/$/, "");
640
+ this.apiUrl = (options.apiUrl ?? "https://dialtribe.com").replace(/\/$/, "");
476
641
  }
477
642
  // ===========================================================================
478
643
  // Lifecycle
@@ -514,6 +679,11 @@ var ChatClient = class {
514
679
  this.inboxStore ?? (this.inboxStore = new InboxStore(this));
515
680
  return this.inboxStore;
516
681
  }
682
+ /** The signed-in user's notifications (created on first use). */
683
+ get notifications() {
684
+ this.notificationsStore ?? (this.notificationsStore = new NotificationsStore(this));
685
+ return this.notificationsStore;
686
+ }
517
687
  get self() {
518
688
  return this.connection.getSnapshot().self;
519
689
  }
@@ -633,6 +803,13 @@ var ChatClient = class {
633
803
  users(roomId) {
634
804
  return this.request(`/rooms/${encodeURIComponent(roomId)}/users`);
635
805
  }
806
+ /**
807
+ * Authenticated JSON request to the Dialtribe API (apiUrl), with the same
808
+ * session token and 401 retry as chat-ws requests. `path` is under /api/public/v1.
809
+ */
810
+ api(path, init = {}) {
811
+ return this.request(path, init, `${this.apiUrl}/api/public/v1`);
812
+ }
636
813
  /** A DM action on POST /dm (see DMS.md). */
637
814
  dm(action, fields = {}) {
638
815
  return this.request("/dm", { method: "POST", body: { action, ...fields } });
@@ -642,8 +819,8 @@ var ChatClient = class {
642
819
  * token on 401. Throws ChatRequestError for transport failures and for
643
820
  * `{ ok: false, error }` bodies.
644
821
  */
645
- async request(path, init = {}) {
646
- const attempt = async (token) => fetch(this.serverUrl + path, {
822
+ async request(path, init = {}, base = this.serverUrl) {
823
+ const attempt = async (token) => fetch(base + path, {
647
824
  method: init.method ?? "GET",
648
825
  headers: {
649
826
  Authorization: `Bearer ${token}`,
@@ -704,17 +881,20 @@ var MessagesUiStore = class extends Store {
704
881
  openRoom(roomId) {
705
882
  this.update({ open: true, view: { kind: "room", roomId } });
706
883
  }
884
+ openNotifications() {
885
+ this.update({ open: true, view: { kind: "notifications" } });
886
+ }
707
887
  openItem(itemId) {
708
888
  this.update({ open: true, view: { kind: "item", itemId } });
709
889
  }
710
890
  };
711
891
  var ClientContext = createContext(null);
712
892
  var MessagesUiContext = createContext(null);
713
- function DialtribeChatProvider({ children, getSessionToken, serverUrl, websocketUrl, websocket }) {
893
+ function DialtribeChatProvider({ children, getSessionToken, serverUrl, apiUrl, websocketUrl, websocket }) {
714
894
  const tokenRef = useRef(getSessionToken);
715
895
  tokenRef.current = getSessionToken;
716
896
  const [client] = useState(
717
- () => new ChatClient({ serverUrl, websocketUrl, websocket, getSessionToken: () => tokenRef.current() })
897
+ () => new ChatClient({ serverUrl, apiUrl, websocketUrl, websocket, getSessionToken: () => tokenRef.current() })
718
898
  );
719
899
  const [messagesUi] = useState(() => new MessagesUiStore());
720
900
  useEffect(() => {
@@ -795,6 +975,7 @@ function useChatRooms() {
795
975
  hideDM: inbox.hideDM.bind(inbox),
796
976
  addParticipant: inbox.addParticipant.bind(inbox),
797
977
  setMuted: inbox.setMuted.bind(inbox),
978
+ setArchived: inbox.setArchived.bind(inbox),
798
979
  markRead: inbox.markRead.bind(inbox),
799
980
  setVisible: inbox.setVisible.bind(inbox),
800
981
  refresh: inbox.refresh.bind(inbox)
@@ -819,6 +1000,7 @@ function useDialtribeMessages() {
819
1000
  openInbox: () => ui.openInbox(),
820
1001
  openRoom: (roomId) => ui.openRoom(roomId),
821
1002
  openItem: (itemId) => ui.openItem(itemId),
1003
+ openNotifications: () => ui.openNotifications(),
822
1004
  messageUser: async (userId, hint) => {
823
1005
  const result = await client.inbox.requestDM(userId, hint);
824
1006
  ui.openRoom(result.roomId);
@@ -829,6 +1011,26 @@ function useDialtribeMessages() {
829
1011
  );
830
1012
  return useMemo(() => ({ isOpen: snapshot.open, view: snapshot.view, ...actions }), [snapshot, actions]);
831
1013
  }
1014
+ function useDialtribeNotifications() {
1015
+ const store = useChatClient().notifications;
1016
+ useEffect(() => {
1017
+ store.acquire();
1018
+ return () => store.release();
1019
+ }, [store]);
1020
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
1021
+ const actions = useMemo(
1022
+ () => ({
1023
+ refresh: store.refresh.bind(store),
1024
+ loadMore: store.loadMore.bind(store),
1025
+ markRead: store.markRead.bind(store),
1026
+ markAllRead: store.markAllRead.bind(store),
1027
+ markSeen: store.markSeen.bind(store),
1028
+ click: store.click.bind(store)
1029
+ }),
1030
+ [store]
1031
+ );
1032
+ return useMemo(() => ({ ...snapshot, ...actions }), [snapshot, actions]);
1033
+ }
832
1034
 
833
1035
  // src/types/index.ts
834
1036
  function parseReactions(reactionsJson) {
@@ -1130,16 +1332,44 @@ var DEFAULT_LABELS = {
1130
1332
  reopen: "Reopen",
1131
1333
  closeConversation: "Close conversation",
1132
1334
  removeConversation: "Remove from inbox",
1133
- mute: "Mute",
1134
- unmute: "Unmute",
1335
+ mute: "Mute notifications",
1336
+ unmute: "Unmute notifications",
1337
+ archive: "Archive conversation",
1338
+ unarchive: "Unarchive conversation",
1339
+ archived: "Archived",
1340
+ moreOptions: "More options",
1341
+ muteConfirmTitle: (name) => `Mute notifications from ${name}?`,
1342
+ muteConfirmBody: "You won't get alerts or unread badges for this conversation. Messages still arrive.",
1343
+ muteConfirm: "Mute",
1344
+ archiveConfirmTitle: (name) => `Archive your conversation with ${name}?`,
1345
+ archiveConfirmBody: "It moves off your rail and into Archived in Messages. New messages still count toward your unread. Only you will see that it's archived.",
1346
+ archiveConfirm: "Archive",
1347
+ cancel: "Cancel",
1135
1348
  messagePlaceholder: "Message...",
1136
- openMessages: "Open messages"
1349
+ openMessages: "Open messages",
1350
+ notifications: "Notifications",
1351
+ noNotifications: "No notifications yet",
1352
+ markAllRead: "Mark all read",
1353
+ loadMore: "Load more",
1354
+ groupMore: (count) => `and ${count} more`,
1355
+ timeAgo: (date) => {
1356
+ const s = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1e3));
1357
+ if (s < 60) return "now";
1358
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
1359
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
1360
+ if (s < 604800) return `${Math.floor(s / 86400)}d`;
1361
+ return date.toLocaleDateString(void 0, { month: "short", day: "numeric" });
1362
+ }
1137
1363
  };
1138
1364
  function badgeText(count) {
1139
1365
  return count > 99 ? "99+" : String(count);
1140
1366
  }
1141
1367
  function MessagesInbox({ rooms, requests, labels, onOpenRoom, onRemoveRoom }) {
1142
- const conversations = rooms.filter((r) => r.myStatus === "accepted");
1368
+ const [showArchived, setShowArchived] = useState(false);
1369
+ const accepted = rooms.filter((r) => r.myStatus === "accepted");
1370
+ const conversations = accepted.filter((r) => !r.isArchived);
1371
+ const archived = accepted.filter((r) => r.isArchived);
1372
+ const archivedUnread = archived.reduce((sum, r) => sum + (r.isMuted ? 0 : r.unreadCount), 0);
1143
1373
  if (rooms.length === 0) return /* @__PURE__ */ jsx("div", { className: "dtc-empty", children: labels.noMessages });
1144
1374
  return /* @__PURE__ */ jsxs("div", { className: "dtc-inbox", children: [
1145
1375
  requests.length > 0 && /* @__PURE__ */ jsxs("section", { className: "dtc-inbox-section", children: [
@@ -1155,7 +1385,29 @@ function MessagesInbox({ rooms, requests, labels, onOpenRoom, onRemoveRoom }) {
1155
1385
  removeLabel: labels.removeConversation
1156
1386
  },
1157
1387
  room.roomId
1158
- )) })
1388
+ )) }),
1389
+ archived.length > 0 && /* @__PURE__ */ jsxs("section", { className: "dtc-inbox-section", children: [
1390
+ /* @__PURE__ */ jsxs(
1391
+ "button",
1392
+ {
1393
+ type: "button",
1394
+ className: "dtc-inbox-heading dtc-inbox-toggle",
1395
+ "aria-expanded": showArchived,
1396
+ onClick: () => setShowArchived((v) => !v),
1397
+ children: [
1398
+ /* @__PURE__ */ jsxs("span", { children: [
1399
+ labels.archived,
1400
+ " (",
1401
+ archived.length,
1402
+ ")"
1403
+ ] }),
1404
+ !showArchived && archivedUnread > 0 && /* @__PURE__ */ jsx("span", { className: "dtc-badge-count", children: badgeText(archivedUnread) }),
1405
+ /* @__PURE__ */ jsx("svg", { className: "dtc-inbox-toggle-icon", viewBox: "0 0 24 24", width: "14", height: "14", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M6 9l6 6 6-6" }) })
1406
+ ]
1407
+ }
1408
+ ),
1409
+ showArchived && archived.map((room) => /* @__PURE__ */ jsx(InboxRow, { room, onOpen: onOpenRoom }, room.roomId))
1410
+ ] })
1159
1411
  ] });
1160
1412
  }
1161
1413
  function InboxRow({
@@ -1188,7 +1440,78 @@ function InboxRow({
1188
1440
  )
1189
1441
  ] });
1190
1442
  }
1191
- function ConversationView({ roomId, labels, onBack }) {
1443
+ function ConversationMenu({ label, items }) {
1444
+ const [open, setOpen] = useState(false);
1445
+ const rootRef = useRef(null);
1446
+ const buttonRef = useRef(null);
1447
+ const menuRef = useRef(null);
1448
+ useEffect(() => {
1449
+ if (!open) return;
1450
+ menuRef.current?.querySelector("[role=menuitem]")?.focus();
1451
+ const onPointer = (e) => {
1452
+ if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false);
1453
+ };
1454
+ const onKey = (e) => {
1455
+ if (e.key !== "Escape") return;
1456
+ e.preventDefault();
1457
+ setOpen(false);
1458
+ buttonRef.current?.focus();
1459
+ };
1460
+ document.addEventListener("pointerdown", onPointer);
1461
+ window.addEventListener("keydown", onKey, true);
1462
+ return () => {
1463
+ document.removeEventListener("pointerdown", onPointer);
1464
+ window.removeEventListener("keydown", onKey, true);
1465
+ };
1466
+ }, [open]);
1467
+ const onMenuKey = (e) => {
1468
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
1469
+ e.preventDefault();
1470
+ const buttons = Array.from(menuRef.current?.querySelectorAll("[role=menuitem]") ?? []);
1471
+ const i = buttons.indexOf(document.activeElement);
1472
+ const next = e.key === "ArrowDown" ? (i + 1) % buttons.length : (i - 1 + buttons.length) % buttons.length;
1473
+ buttons[next]?.focus();
1474
+ };
1475
+ if (items.length === 0) return null;
1476
+ return /* @__PURE__ */ jsxs("div", { className: "dtc-menu-root", ref: rootRef, children: [
1477
+ /* @__PURE__ */ jsx(
1478
+ "button",
1479
+ {
1480
+ ref: buttonRef,
1481
+ type: "button",
1482
+ className: "dtc-icon-btn",
1483
+ "aria-label": label,
1484
+ title: label,
1485
+ "aria-haspopup": "menu",
1486
+ "aria-expanded": open,
1487
+ onClick: () => setOpen((v) => !v),
1488
+ children: /* @__PURE__ */ jsx(KebabIcon, {})
1489
+ }
1490
+ ),
1491
+ open && /* @__PURE__ */ jsx("div", { className: "dtc-menu", role: "menu", ref: menuRef, onKeyDown: onMenuKey, children: items.map((item) => /* @__PURE__ */ jsx(
1492
+ "button",
1493
+ {
1494
+ type: "button",
1495
+ role: "menuitem",
1496
+ className: "dtc-menu-item",
1497
+ onClick: () => {
1498
+ setOpen(false);
1499
+ item.onSelect();
1500
+ },
1501
+ children: item.label
1502
+ },
1503
+ item.id
1504
+ )) })
1505
+ ] });
1506
+ }
1507
+ function KebabIcon() {
1508
+ return /* @__PURE__ */ jsxs("svg", { viewBox: "0 0 24 24", width: "18", height: "18", fill: "currentColor", "aria-hidden": "true", children: [
1509
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "5", r: "1.8" }),
1510
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "1.8" }),
1511
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "19", r: "1.8" })
1512
+ ] });
1513
+ }
1514
+ function ConversationView({ roomId, labels, onBack, onClose, confirm }) {
1192
1515
  const inbox = useChatRooms();
1193
1516
  const room = inbox.rooms.find((r) => r.roomId === roomId);
1194
1517
  const { setVisible } = inbox;
@@ -1196,16 +1519,49 @@ function ConversationView({ roomId, labels, onBack }) {
1196
1519
  const isRequest = room?.myStatus === "pending";
1197
1520
  const isClosed = room?.state === "closed";
1198
1521
  const waitingOnThem = !isRequest && !!room && room.participants.length > 0 && room.participants.every((p) => p.status === "pending");
1522
+ const menuItems = [];
1523
+ if (room && !isRequest) {
1524
+ menuItems.push({
1525
+ id: "mute",
1526
+ label: room.isMuted ? labels.unmute : labels.mute,
1527
+ onSelect: async () => {
1528
+ if (room.isMuted) return void inbox.setMuted(roomId, false).catch(() => {
1529
+ });
1530
+ const ok = await confirm({
1531
+ title: labels.muteConfirmTitle(room.name),
1532
+ body: labels.muteConfirmBody,
1533
+ confirmLabel: labels.muteConfirm,
1534
+ cancelLabel: labels.cancel
1535
+ });
1536
+ if (ok) void inbox.setMuted(roomId, true).catch(() => {
1537
+ });
1538
+ }
1539
+ });
1540
+ menuItems.push({
1541
+ id: "archive",
1542
+ label: room.isArchived ? labels.unarchive : labels.archive,
1543
+ onSelect: async () => {
1544
+ if (room.isArchived) return void inbox.setArchived(roomId, false).catch(() => {
1545
+ });
1546
+ const ok = await confirm({
1547
+ title: labels.archiveConfirmTitle(room.name),
1548
+ body: labels.archiveConfirmBody,
1549
+ confirmLabel: labels.archiveConfirm,
1550
+ cancelLabel: labels.cancel
1551
+ });
1552
+ if (ok) void inbox.setArchived(roomId, true).catch(() => {
1553
+ });
1554
+ }
1555
+ });
1556
+ }
1199
1557
  return /* @__PURE__ */ jsxs("div", { className: "dtc-conversation", children: [
1200
1558
  /* @__PURE__ */ jsxs("div", { className: "dtc-conversation-header", children: [
1201
1559
  /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: onBack, "aria-label": labels.back, title: labels.back, children: /* @__PURE__ */ jsx(ChevronLeft, {}) }),
1202
1560
  room && /* @__PURE__ */ jsx(Avatar, { name: room.name, url: room.kind === "dm" ? room.participants[0]?.avatarUrl : null, size: 28 }),
1203
1561
  /* @__PURE__ */ jsx("span", { className: "dtc-conversation-title", children: room?.name ?? "" }),
1204
- room && !isRequest && /* @__PURE__ */ jsxs("span", { className: "dtc-conversation-actions", children: [
1205
- /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-text-btn", onClick: () => void inbox.setMuted(roomId, !room.isMuted).catch(() => {
1206
- }), children: room.isMuted ? labels.unmute : labels.mute }),
1207
- !isClosed && /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-text-btn", onClick: () => void inbox.closeDM(roomId).catch(() => {
1208
- }), children: labels.closeConversation })
1562
+ /* @__PURE__ */ jsxs("span", { className: "dtc-conversation-actions", children: [
1563
+ /* @__PURE__ */ jsx(ConversationMenu, { label: labels.moreOptions, items: menuItems }),
1564
+ /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: onClose, "aria-label": labels.close, title: labels.close, children: /* @__PURE__ */ jsx(CloseIcon, {}) })
1209
1565
  ] })
1210
1566
  ] }),
1211
1567
  isRequest && room && /* @__PURE__ */ jsxs("div", { className: "dtc-request-banner", role: "region", "aria-label": labels.requests, children: [
@@ -1244,9 +1600,99 @@ function ConversationView({ roomId, labels, onBack }) {
1244
1600
  ) })
1245
1601
  ] });
1246
1602
  }
1603
+ function CloseIcon() {
1604
+ return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "18", height: "18", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M18 6L6 18M6 6l12 12" }) });
1605
+ }
1247
1606
  function ChevronLeft() {
1248
1607
  return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "18", height: "18", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M15 18l-6-6 6-6" }) });
1249
1608
  }
1609
+ function groupRows(items) {
1610
+ const rows = [];
1611
+ const byKey = /* @__PURE__ */ new Map();
1612
+ for (const item of items) {
1613
+ const existing = item.groupKey ? byKey.get(item.groupKey) : void 0;
1614
+ if (existing) {
1615
+ existing.ids.push(item.id);
1616
+ existing.more += 1;
1617
+ existing.unread || (existing.unread = !item.readAt);
1618
+ continue;
1619
+ }
1620
+ const row = { lead: item, ids: [item.id], more: 0, unread: !item.readAt };
1621
+ rows.push(row);
1622
+ if (item.groupKey) byKey.set(item.groupKey, row);
1623
+ }
1624
+ return rows;
1625
+ }
1626
+ function NotificationsPanel({ labels, onClose, onOpen }) {
1627
+ const n = useDialtribeNotifications();
1628
+ const rows = useMemo(() => groupRows(n.items), [n.items]);
1629
+ const { status, markSeen } = n;
1630
+ useEffect(() => {
1631
+ if (status === "ready") void markSeen().catch(() => {
1632
+ });
1633
+ }, [status, markSeen]);
1634
+ const open = (row) => {
1635
+ void n.click(row.ids).catch(() => {
1636
+ });
1637
+ const handled = onOpen?.(row.lead);
1638
+ if (!handled && row.lead.url) window.location.assign(row.lead.url);
1639
+ };
1640
+ return /* @__PURE__ */ jsxs("div", { className: "dtc-notif", children: [
1641
+ /* @__PURE__ */ jsxs("div", { className: "dtc-panel-header", children: [
1642
+ /* @__PURE__ */ jsxs("span", { className: "dtc-panel-title", children: [
1643
+ labels.notifications,
1644
+ n.unreadCount > 0 && /* @__PURE__ */ jsx("span", { className: "dtc-badge-count dtc-notif-title-badge", children: badgeText(n.unreadCount) })
1645
+ ] }),
1646
+ n.unreadCount > 0 && /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-notif-markall", onClick: () => void n.markAllRead().catch(() => {
1647
+ }), children: labels.markAllRead }),
1648
+ onClose && /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: onClose, "aria-label": labels.close, title: labels.close, children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "18", height: "18", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M18 6L6 18M6 6l12 12" }) }) })
1649
+ ] }),
1650
+ n.status !== "ready" && rows.length === 0 ? /* @__PURE__ */ jsx("div", { className: "dtc-empty", children: n.status === "error" ? n.error?.message ?? "" : "" }) : rows.length === 0 ? /* @__PURE__ */ jsx("div", { className: "dtc-empty", children: labels.noNotifications }) : /* @__PURE__ */ jsxs("div", { className: "dtc-notif-list", children: [
1651
+ rows.map((row) => /* @__PURE__ */ jsxs(
1652
+ "button",
1653
+ {
1654
+ type: "button",
1655
+ className: `dtc-notif-row ${row.unread ? "dtc-notif-row-unread" : ""}`,
1656
+ onClick: () => open(row),
1657
+ children: [
1658
+ /* @__PURE__ */ jsx(
1659
+ Avatar,
1660
+ {
1661
+ name: row.lead.actor?.name ?? row.lead.title,
1662
+ url: row.lead.actor?.avatarUrl ?? row.lead.imageUrl,
1663
+ size: 40
1664
+ }
1665
+ ),
1666
+ /* @__PURE__ */ jsxs("span", { className: "dtc-notif-text", children: [
1667
+ /* @__PURE__ */ jsx("span", { className: "dtc-notif-title", children: row.lead.title }),
1668
+ row.lead.body && /* @__PURE__ */ jsx("span", { className: "dtc-notif-body", children: row.lead.body }),
1669
+ /* @__PURE__ */ jsxs("span", { className: "dtc-notif-meta", children: [
1670
+ labels.timeAgo(new Date(row.lead.createdAt)),
1671
+ row.more > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
1672
+ " \xB7 ",
1673
+ labels.groupMore(row.more)
1674
+ ] })
1675
+ ] })
1676
+ ] }),
1677
+ row.unread && /* @__PURE__ */ jsx("span", { className: "dtc-notif-dot", "aria-hidden": "true" })
1678
+ ]
1679
+ },
1680
+ row.lead.id
1681
+ )),
1682
+ n.hasMore && /* @__PURE__ */ jsx(
1683
+ "button",
1684
+ {
1685
+ type: "button",
1686
+ className: "dtc-btn dtc-notif-more",
1687
+ disabled: n.loadingMore,
1688
+ onClick: () => void n.loadMore().catch(() => {
1689
+ }),
1690
+ children: labels.loadMore
1691
+ }
1692
+ )
1693
+ ] })
1694
+ ] });
1695
+ }
1250
1696
  var RAIL_WIDTH = 64;
1251
1697
  var EDGE_SWIPE_ZONE = 24;
1252
1698
  var SWIPE_DISTANCE = 60;
@@ -1261,7 +1707,9 @@ function DialtribeMessages({
1261
1707
  labels: labelOverrides,
1262
1708
  panelWidth = 380,
1263
1709
  railDmLimit = 5,
1264
- mobileBreakpoint = 768
1710
+ mobileBreakpoint = 768,
1711
+ confirm: hostConfirm,
1712
+ notifications = false
1265
1713
  }) {
1266
1714
  const labels = useMemo(() => ({ ...DEFAULT_LABELS, ...labelOverrides }), [labelOverrides]);
1267
1715
  const inbox = useChatRooms();
@@ -1269,8 +1717,24 @@ function DialtribeMessages({
1269
1717
  const isMobile = useMediaQuery(`(max-width: ${mobileBreakpoint - 1}px)`);
1270
1718
  const { isOpen, view } = ui;
1271
1719
  const pendingCount = inbox.requests.length;
1272
- const rollup = inbox.totalUnread + pendingCount;
1273
- const recentDms = inbox.rooms.filter((r) => r.myStatus === "accepted").slice(0, railDmLimit);
1720
+ const notifUnread = useNotificationsBadge(notifications !== false);
1721
+ const rollup = inbox.totalUnread + pendingCount + notifUnread;
1722
+ const notifOnOpen = typeof notifications === "object" ? notifications.onOpen : void 0;
1723
+ const recentDms = inbox.rooms.filter((r) => r.myStatus === "accepted" && !r.isArchived).slice(0, railDmLimit);
1724
+ const [builtInConfirm, setBuiltInConfirm] = useState(null);
1725
+ const confirmOpen = useRef(false);
1726
+ const confirm = useMemo(
1727
+ () => async (options) => {
1728
+ confirmOpen.current = true;
1729
+ try {
1730
+ return hostConfirm ? await hostConfirm(options) : await new Promise((resolve) => setBuiltInConfirm({ options, resolve }));
1731
+ } finally {
1732
+ confirmOpen.current = false;
1733
+ setBuiltInConfirm(null);
1734
+ }
1735
+ },
1736
+ [hostConfirm]
1737
+ );
1274
1738
  const activeRoomId = isOpen && view.kind === "room" ? view.roomId : null;
1275
1739
  const activeContext = contexts.find((c) => c.roomId === activeRoomId);
1276
1740
  const activeItemId = isOpen && view.kind === "item" ? view.itemId : null;
@@ -1284,15 +1748,18 @@ function DialtribeMessages({
1284
1748
  useEdgeSwipe(isMobile, isOpen, ui.open, ui.close, side);
1285
1749
  useEffect(() => {
1286
1750
  if (!isOpen) return;
1287
- const onKey = (e) => e.key === "Escape" && ui.close();
1751
+ const onKey = (e) => {
1752
+ if (e.key === "Escape" && !e.defaultPrevented && !confirmOpen.current) ui.close();
1753
+ };
1288
1754
  window.addEventListener("keydown", onKey);
1289
1755
  return () => window.removeEventListener("keydown", onKey);
1290
1756
  }, [isOpen, ui]);
1291
1757
  const select = (target) => {
1292
- const showing = isOpen && (target.kind === "inbox" ? view.kind === "inbox" : target.kind === "room" ? activeRoomId === target.roomId : activeItemId === target.itemId);
1758
+ const showing = isOpen && (target.kind === "inbox" ? view.kind === "inbox" : target.kind === "room" ? activeRoomId === target.roomId : target.kind === "notifications" ? view.kind === "notifications" : activeItemId === target.itemId);
1293
1759
  if (showing) ui.close();
1294
1760
  else if (target.kind === "inbox") ui.openInbox();
1295
1761
  else if (target.kind === "room") ui.openRoom(target.roomId);
1762
+ else if (target.kind === "notifications") ui.openNotifications();
1296
1763
  else ui.openItem(target.itemId);
1297
1764
  };
1298
1765
  const renderItemButton = (item) => {
@@ -1322,34 +1789,63 @@ function DialtribeMessages({
1322
1789
  /* @__PURE__ */ jsx(ChatIcon, {}),
1323
1790
  rollup > 0 && /* @__PURE__ */ jsx("span", { className: "dtc-badge-count dtc-badge-float", children: badgeText(rollup) })
1324
1791
  ] }),
1325
- isOpen && /* @__PURE__ */ jsx("div", { className: "dtc-messages-panel", role: "dialog", "aria-label": activeItem?.label ?? labels.messages, children: activeItem ? /* @__PURE__ */ jsx("div", { className: "dtc-item-panel", children: typeof activeItem.panel === "function" ? activeItem.panel({ close: ui.close }) : activeItem.panel }) : view.kind !== "room" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1326
- /* @__PURE__ */ jsxs("div", { className: "dtc-panel-header", children: [
1327
- /* @__PURE__ */ jsx("span", { className: "dtc-panel-title", children: labels.messages }),
1328
- /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: ui.close, "aria-label": labels.close, title: labels.close, children: /* @__PURE__ */ jsx(CloseIcon, {}) })
1329
- ] }),
1330
- /* @__PURE__ */ jsx(
1331
- MessagesInbox,
1792
+ isOpen && /* @__PURE__ */ jsxs("div", { className: "dtc-messages-panel", role: "dialog", "aria-label": activeItem?.label ?? labels.messages, children: [
1793
+ view.kind === "notifications" && notifications !== false ? /* @__PURE__ */ jsx(NotificationsPanel, { labels, onClose: ui.close, onOpen: notifOnOpen }) : activeItem ? /* @__PURE__ */ jsx("div", { className: "dtc-item-panel", children: typeof activeItem.panel === "function" ? activeItem.panel({ close: ui.close }) : activeItem.panel }) : view.kind !== "room" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1794
+ /* @__PURE__ */ jsxs("div", { className: "dtc-panel-header", children: [
1795
+ /* @__PURE__ */ jsx("span", { className: "dtc-panel-title", children: labels.messages }),
1796
+ /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: ui.close, "aria-label": labels.close, title: labels.close, children: /* @__PURE__ */ jsx(CloseIcon2, {}) })
1797
+ ] }),
1798
+ /* @__PURE__ */ jsx(
1799
+ MessagesInbox,
1800
+ {
1801
+ rooms: inbox.rooms,
1802
+ requests: inbox.requests,
1803
+ labels,
1804
+ onOpenRoom: ui.openRoom,
1805
+ onRemoveRoom: inboxRowClose ? (roomId) => void inbox.hideDM(roomId).catch(() => {
1806
+ }) : void 0
1807
+ }
1808
+ )
1809
+ ] }) : activeContext ? /* @__PURE__ */ jsxs("div", { className: "dtc-conversation", children: [
1810
+ /* @__PURE__ */ jsxs("div", { className: "dtc-conversation-header", children: [
1811
+ /* @__PURE__ */ jsx(Avatar, { name: activeContext.label, url: activeContext.avatarUrl, size: 28 }),
1812
+ /* @__PURE__ */ jsx("span", { className: "dtc-conversation-title", children: activeContext.label }),
1813
+ /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: ui.close, "aria-label": labels.close, title: labels.close, children: /* @__PURE__ */ jsx(CloseIcon2, {}) })
1814
+ ] }),
1815
+ /* @__PURE__ */ jsx(ChatRoomProvider, { roomId: activeContext.roomId, children: /* @__PURE__ */ jsx(ChatPanel, { showHeader: false, emptyLabel: labels.noMessages, placeholder: labels.messagePlaceholder }) })
1816
+ ] }) : /* @__PURE__ */ jsx(
1817
+ ConversationView,
1332
1818
  {
1333
- rooms: inbox.rooms,
1334
- requests: inbox.requests,
1819
+ roomId: view.roomId,
1335
1820
  labels,
1336
- onOpenRoom: ui.openRoom,
1337
- onRemoveRoom: inboxRowClose ? (roomId) => void inbox.hideDM(roomId).catch(() => {
1338
- }) : void 0
1821
+ onBack: ui.openInbox,
1822
+ onClose: ui.close,
1823
+ confirm
1824
+ },
1825
+ view.roomId
1826
+ ),
1827
+ builtInConfirm && /* @__PURE__ */ jsx(
1828
+ ConfirmDialog,
1829
+ {
1830
+ options: builtInConfirm.options,
1831
+ onAnswer: builtInConfirm.resolve
1339
1832
  }
1340
1833
  )
1341
- ] }) : activeContext ? /* @__PURE__ */ jsxs("div", { className: "dtc-conversation", children: [
1342
- /* @__PURE__ */ jsxs("div", { className: "dtc-conversation-header", children: [
1343
- /* @__PURE__ */ jsx(Avatar, { name: activeContext.label, url: activeContext.avatarUrl, size: 28 }),
1344
- /* @__PURE__ */ jsx("span", { className: "dtc-conversation-title", children: activeContext.label }),
1345
- /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-icon-btn", onClick: ui.close, "aria-label": labels.close, title: labels.close, children: /* @__PURE__ */ jsx(CloseIcon, {}) })
1346
- ] }),
1347
- /* @__PURE__ */ jsx(ChatRoomProvider, { roomId: activeContext.roomId, children: /* @__PURE__ */ jsx(ChatPanel, { showHeader: false, emptyLabel: labels.noMessages, placeholder: labels.messagePlaceholder }) })
1348
- ] }) : /* @__PURE__ */ jsx(ConversationView, { roomId: view.roomId, labels, onBack: ui.openInbox }, view.roomId) }),
1834
+ ] }),
1349
1835
  showRail && /* @__PURE__ */ jsxs("nav", { className: "dtc-rail", "aria-label": labels.messages, children: [
1350
1836
  /* @__PURE__ */ jsxs("div", { className: "dtc-rail-scroll", children: [
1351
1837
  topItems.map(renderItemButton),
1352
1838
  topItems.length > 0 && /* @__PURE__ */ jsx("span", { className: "dtc-rail-divider" }),
1839
+ notifications !== false && /* @__PURE__ */ jsx(
1840
+ RailButton,
1841
+ {
1842
+ label: labels.notifications,
1843
+ active: isOpen && view.kind === "notifications",
1844
+ badge: notifUnread,
1845
+ onClick: () => select({ kind: "notifications" }),
1846
+ children: /* @__PURE__ */ jsx(BellIcon, {})
1847
+ }
1848
+ ),
1353
1849
  /* @__PURE__ */ jsx(
1354
1850
  RailButton,
1355
1851
  {
@@ -1393,6 +1889,37 @@ function DialtribeMessages({
1393
1889
  }
1394
1890
  );
1395
1891
  }
1892
+ function ConfirmDialog({ options, onAnswer }) {
1893
+ const confirmRef = useRef(null);
1894
+ useEffect(() => {
1895
+ confirmRef.current?.focus();
1896
+ const onKey = (e) => {
1897
+ if (e.key !== "Escape") return;
1898
+ e.preventDefault();
1899
+ onAnswer(false);
1900
+ };
1901
+ window.addEventListener("keydown", onKey, true);
1902
+ return () => window.removeEventListener("keydown", onKey, true);
1903
+ }, [onAnswer]);
1904
+ return /* @__PURE__ */ jsx("div", { className: "dtc-confirm-backdrop", onClick: () => onAnswer(false), children: /* @__PURE__ */ jsxs(
1905
+ "div",
1906
+ {
1907
+ className: "dtc-confirm",
1908
+ role: "alertdialog",
1909
+ "aria-modal": "true",
1910
+ "aria-labelledby": "dtc-confirm-title",
1911
+ onClick: (e) => e.stopPropagation(),
1912
+ children: [
1913
+ /* @__PURE__ */ jsx("h3", { id: "dtc-confirm-title", className: "dtc-confirm-title", children: options.title }),
1914
+ options.body && /* @__PURE__ */ jsx("p", { className: "dtc-confirm-body", children: options.body }),
1915
+ /* @__PURE__ */ jsxs("div", { className: "dtc-confirm-actions", children: [
1916
+ /* @__PURE__ */ jsx("button", { type: "button", className: "dtc-btn", onClick: () => onAnswer(false), children: options.cancelLabel }),
1917
+ /* @__PURE__ */ jsx("button", { ref: confirmRef, type: "button", className: "dtc-btn dtc-btn-primary", onClick: () => onAnswer(true), children: options.confirmLabel })
1918
+ ] })
1919
+ ]
1920
+ }
1921
+ ) });
1922
+ }
1396
1923
  function RailButton({
1397
1924
  label,
1398
1925
  active,
@@ -1500,10 +2027,26 @@ function themeVars(theme) {
1500
2027
  function ChatIcon() {
1501
2028
  return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "20", height: "20", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }) });
1502
2029
  }
1503
- function CloseIcon() {
2030
+ function BellIcon() {
2031
+ return /* @__PURE__ */ jsxs("svg", { viewBox: "0 0 24 24", width: "20", height: "20", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
2032
+ /* @__PURE__ */ jsx("path", { d: "M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" }),
2033
+ /* @__PURE__ */ jsx("path", { d: "M13.73 21a2 2 0 0 1-3.46 0" })
2034
+ ] });
2035
+ }
2036
+ function useNotificationsBadge(enabled) {
2037
+ const store = useChatClient().notifications;
2038
+ useEffect(() => {
2039
+ if (!enabled) return;
2040
+ store.acquire();
2041
+ return () => store.release();
2042
+ }, [enabled, store]);
2043
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
2044
+ return enabled ? snapshot.unreadCount : 0;
2045
+ }
2046
+ function CloseIcon2() {
1504
2047
  return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "18", height: "18", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M18 6L6 18M6 6l12 12" }) });
1505
2048
  }
1506
2049
 
1507
- export { Avatar, ChatClient, ChatInput, ChatMessageItem, ChatPanel, ChatRequestError, ChatRoomProvider, DEFAULT_LABELS, DialtribeChatProvider, DialtribeMessages, parseReactions, useChatClient, useChatConnection, useChatRoomContext, useChatRooms, useDialtribeChat, useDialtribeMessages };
2050
+ export { Avatar, ChatClient, ChatInput, ChatMessageItem, ChatPanel, ChatRequestError, ChatRoomProvider, DEFAULT_LABELS, DialtribeChatProvider, DialtribeMessages, NotificationsPanel, parseReactions, useChatClient, useChatConnection, useChatRoomContext, useChatRooms, useDialtribeChat, useDialtribeMessages, useDialtribeNotifications };
1508
2051
  //# sourceMappingURL=index.mjs.map
1509
2052
  //# sourceMappingURL=index.mjs.map