@marktiderman/genesis-chat 0.7.0 → 0.9.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.
Files changed (53) hide show
  1. package/README.md +132 -3
  2. package/dist/{chunk-GBJ3YI4E.js → chunk-5XYDVUPS.js} +6 -3
  3. package/dist/chunk-5XYDVUPS.js.map +1 -0
  4. package/dist/{chunk-XQ2ULNHV.js → chunk-D4RPOYB7.js} +4 -4
  5. package/dist/chunk-D4RPOYB7.js.map +1 -0
  6. package/dist/{chunk-RYD6WJE5.js → chunk-O2QSBRSH.js} +3 -3
  7. package/dist/{chunk-RYD6WJE5.js.map → chunk-O2QSBRSH.js.map} +1 -1
  8. package/dist/{chunk-A4YJX7KT.js → chunk-ZQFREERR.js} +3 -3
  9. package/dist/{chunk-A4YJX7KT.js.map → chunk-ZQFREERR.js.map} +1 -1
  10. package/dist/{client-DUIG1hum.d.ts → client-DP7rhJ1U.d.ts} +17 -6
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +2 -2
  13. package/dist/native.d.ts +35 -16
  14. package/dist/native.js +168 -490
  15. package/dist/native.js.map +1 -1
  16. package/dist/{outbox-B9NAWQ58.d.ts → outbox-C4LnqpKT.d.ts} +1 -1
  17. package/dist/push.d.ts +2 -2
  18. package/dist/react.d.ts +4 -8
  19. package/dist/react.js +3 -3
  20. package/dist/server.d.ts +1 -1
  21. package/dist/server.js +1 -1
  22. package/dist/{thread-oPra7pkW.d.ts → thread-CSzdqNR_.d.ts} +1 -1
  23. package/dist/web.d.ts +201 -7
  24. package/dist/web.js +580 -56
  25. package/dist/web.js.map +1 -1
  26. package/migrations/0004_genesis_chat_tenants.sql +716 -0
  27. package/migrations/tests/0001_genesis_chat.test.sql +10 -2
  28. package/migrations/tests/0002_genesis_chat_coaching.test.sql +8 -0
  29. package/migrations/tests/0003_genesis_chat_search_threads.test.sql +8 -0
  30. package/migrations/tests/0004_genesis_chat_tenants.test.sql +259 -0
  31. package/package.json +18 -7
  32. package/src/__tests__/core.test.ts +12 -0
  33. package/src/__tests__/web-dock.test.tsx +465 -0
  34. package/src/__tests__/web-photo-viewer.test.tsx +43 -0
  35. package/src/__tests__/web.test.tsx +26 -0
  36. package/src/core/client.ts +5 -1
  37. package/src/core/types.ts +16 -0
  38. package/src/native/__tests__/photo-viewer.test.tsx +24 -5
  39. package/src/native/__tests__/thread-screen.test.tsx +40 -2
  40. package/src/native/message-bubble.tsx +1 -1
  41. package/src/native/photo-viewer.tsx +109 -422
  42. package/src/native/thread-screen.tsx +77 -207
  43. package/src/native/use-jump.ts +7 -1
  44. package/src/react/index.tsx +2 -1
  45. package/src/web/attachments.tsx +39 -55
  46. package/src/web/composer.tsx +5 -0
  47. package/src/web/dock.tsx +889 -0
  48. package/src/web/inbox.tsx +5 -0
  49. package/src/web/index.ts +23 -0
  50. package/src/web/memory-client.ts +1 -1
  51. package/src/web/thread.tsx +42 -3
  52. package/dist/chunk-GBJ3YI4E.js.map +0 -1
  53. package/dist/chunk-XQ2ULNHV.js.map +0 -1
@@ -0,0 +1,889 @@
1
+ /**
2
+ * @feat:chat-dock
3
+ * The chat dock: conversations that stay open while you move around the app. On a wide screen up
4
+ * to three windows sit bottom-right (fewer when the screen is narrower than three fit; the rest
5
+ * wait behind a "+N" menu), each with its own thread and composer, minimized to a bar or closed; a
6
+ * fourth replaces the one used longest ago. On a narrow screen the open ones share one side sheet
7
+ * with a switcher, and a bubble (with the unread count) brings it back. "Expand" opens the zone's
8
+ * own Messages page through `onExpand`.
9
+ *
10
+ * A minimized window and a sheet tab out of view keep their thread mounted but hidden, with
11
+ * read-marking paused: what you were typing, a reply and attachments wait for you, and nothing is
12
+ * marked read while it's out of sight.
13
+ *
14
+ * A conversation opens with `useChatDock().open(conversationId)`. Anything else that should live
15
+ * in the dock (a help desk messenger) opens with `openPanel({ id, title, render })`: the dock
16
+ * draws the window, the panel draws what's in it.
17
+ *
18
+ * Mount `ChatDockProvider` under `ChatProvider`, around the app, and `<ChatDock />` once: in
19
+ * AppShell's `dock` slot, which keeps it clear of the phone's bottom bar.
20
+ */
21
+ import {
22
+ createContext,
23
+ useCallback,
24
+ useContext,
25
+ useEffect,
26
+ useMemo,
27
+ useReducer,
28
+ useRef,
29
+ useState,
30
+ useSyncExternalStore,
31
+ type KeyboardEvent,
32
+ type ReactNode,
33
+ type RefObject,
34
+ } from "react";
35
+ import { ChevronDown, ChevronUp, Maximize2, MessageCircle, X } from "lucide-react";
36
+ import {
37
+ Button,
38
+ DropdownMenu,
39
+ DropdownMenuContent,
40
+ DropdownMenuItem,
41
+ DropdownMenuTrigger,
42
+ Sheet,
43
+ SheetContent,
44
+ SheetDescription,
45
+ SheetTitle,
46
+ UserAvatar,
47
+ cn,
48
+ } from "@marktiderman/genesis-ui";
49
+ import { useIsMobile } from "@marktiderman/genesis-ui/hooks";
50
+ import { createLocalStorageAdapter } from "@marktiderman/genesis-core/storage";
51
+ import type { ChatInboxItem } from "../core/types";
52
+ import { useChat, useInbox } from "../react/index";
53
+ import { inboxTitle } from "./inbox";
54
+ import type { ResolveUser } from "./format";
55
+ import { ChatThread, type ChatThreadHeaderProps, type ChatThreadProps } from "./thread";
56
+
57
+ // ---------------------------------------------------------------------------------------------
58
+ // State
59
+
60
+ /** A conversation in the dock. */
61
+ export interface ChatDockConversation {
62
+ type: "conversation";
63
+ /** The dock's id for it: the conversation's id. */
64
+ id: string;
65
+ conversationId: string;
66
+ /** The window's title; worked out from the conversation by default. */
67
+ title?: string;
68
+ minimized: boolean;
69
+ /** Brought back from storage (checked against the server once, then dropped if it's gone). */
70
+ restored?: boolean;
71
+ }
72
+
73
+ /** Anything else that lives in the dock (a help desk messenger): the dock draws the window, `render` its body. */
74
+ export interface ChatDockPanel {
75
+ type: "panel";
76
+ /** Opening the same id again brings that window back rather than adding a second. */
77
+ id: string;
78
+ title: string;
79
+ /** Its body, filling the window under the dock's title bar. */
80
+ render: () => ReactNode;
81
+ /** In place of the avatar in the title bar. */
82
+ icon?: ReactNode;
83
+ /** Unread count on the bar and the bubble. */
84
+ unread?: number;
85
+ /** Its own expand (its full page); wins over the dock's `onExpand`. */
86
+ onExpand?: () => void;
87
+ minimized: boolean;
88
+ }
89
+
90
+ export type ChatDockItem = ChatDockConversation | ChatDockPanel;
91
+
92
+ export interface ChatDockState {
93
+ /** In the order they show: the newest first (rightmost on a wide screen). */
94
+ items: ChatDockItem[];
95
+ /** The one the narrow screen's sheet shows. */
96
+ activeId: string | null;
97
+ /** Whether the narrow screen's sheet is open. */
98
+ sheetOpen: boolean;
99
+ /** When each was last used (opened, restored, switched to), for replacing the one used longest ago. */
100
+ used: Record<string, number>;
101
+ /** The one just opened or restored, whose composer takes focus. */
102
+ focusId: string | null;
103
+ /** Bumps on every use. */
104
+ clock: number;
105
+ }
106
+
107
+ /** What a panel can change while it's docked, without moving or opening it. */
108
+ export type ChatDockPanelPatch = Partial<Pick<ChatDockPanel, "title" | "unread" | "icon" | "render" | "onExpand">>;
109
+
110
+ export type ChatDockAction =
111
+ | { type: "open"; item: ChatDockItem }
112
+ | { type: "close"; id: string }
113
+ | { type: "minimize"; id: string; minimized: boolean }
114
+ | { type: "activate"; id: string }
115
+ | { type: "front"; id: string }
116
+ | { type: "sheet"; open: boolean }
117
+ | { type: "update"; id: string; patch: ChatDockPanelPatch }
118
+ | { type: "hydrate"; items: ChatDockItem[] }
119
+ | { type: "closeAll" };
120
+
121
+ export const emptyChatDock: ChatDockState = { items: [], activeId: null, sheetOpen: false, used: {}, focusId: null, clock: 0 };
122
+
123
+ const sameItem = (a: ChatDockItem, b: ChatDockItem) =>
124
+ (Object.keys({ ...a, ...b }) as (keyof ChatDockItem)[]).every((k) => k === "minimized" || a[k] === b[k]);
125
+
126
+ function touch(state: ChatDockState, id: string): Pick<ChatDockState, "used" | "clock"> {
127
+ const clock = state.clock + 1;
128
+ return { clock, used: { ...state.used, [id]: clock } };
129
+ }
130
+
131
+ function without<T>(record: Record<string, T>, id: string): Record<string, T> {
132
+ const { [id]: _gone, ...rest } = record;
133
+ return rest;
134
+ }
135
+
136
+ /**
137
+ * The dock's state machine, pure. Opening puts the item first, open, active and focused; past
138
+ * `max`, the one used longest ago goes (restoring or switching to one counts as using it). Actions
139
+ * that change nothing return the same state, so an effect that calls them every render settles.
140
+ */
141
+ export function chatDockReducer(state: ChatDockState, action: ChatDockAction, max = 3): ChatDockState {
142
+ const cap = Math.max(1, max);
143
+ switch (action.type) {
144
+ case "open": {
145
+ const at = state.items.findIndex((i) => i.id === action.item.id);
146
+ const current = state.items[at];
147
+ if (at === 0 && current && !current.minimized && sameItem(current, action.item) && state.activeId === current.id && state.sheetOpen && state.focusId === current.id) {
148
+ return state;
149
+ }
150
+ // First, so it's in view even when fewer fit than are open.
151
+ const item = { ...action.item, minimized: false };
152
+ let items = [item, ...state.items.filter((i) => i.id !== item.id)];
153
+ let used = { ...touch(state, item.id).used };
154
+ while (items.length > cap) {
155
+ const oldest = items.filter((i) => i.id !== item.id).reduce((a, b) => ((used[a.id] ?? 0) <= (used[b.id] ?? 0) ? a : b));
156
+ items = items.filter((i) => i.id !== oldest.id);
157
+ used = without(used, oldest.id);
158
+ }
159
+ return { items, activeId: item.id, sheetOpen: true, used, focusId: item.id, clock: state.clock + 1 };
160
+ }
161
+ case "close": {
162
+ const items = state.items.filter((i) => i.id !== action.id);
163
+ if (items.length === state.items.length) return state;
164
+ const activeId = state.activeId === action.id ? (items[0]?.id ?? null) : state.activeId;
165
+ return {
166
+ ...state,
167
+ items,
168
+ activeId,
169
+ sheetOpen: state.sheetOpen && items.length > 0,
170
+ used: without(state.used, action.id),
171
+ focusId: state.focusId === action.id ? null : state.focusId,
172
+ };
173
+ }
174
+ case "minimize": {
175
+ if (!state.items.some((i) => i.id === action.id && i.minimized !== action.minimized)) return state;
176
+ const items = state.items.map((i) => (i.id === action.id ? { ...i, minimized: action.minimized } : i));
177
+ // Restoring is using it: it focuses, and it's no longer the one to replace.
178
+ if (!action.minimized) return { ...state, items, ...touch(state, action.id), focusId: action.id };
179
+ return { ...state, items, focusId: state.focusId === action.id ? null : state.focusId };
180
+ }
181
+ case "activate": {
182
+ if (!state.items.some((i) => i.id === action.id)) return state;
183
+ if (state.activeId === action.id && state.focusId === action.id) return state;
184
+ return { ...state, activeId: action.id, ...touch(state, action.id), focusId: action.id };
185
+ }
186
+ case "front": {
187
+ const at = state.items.findIndex((i) => i.id === action.id);
188
+ if (at === -1) return state;
189
+ const item = { ...state.items[at]!, minimized: false };
190
+ const items = [item, ...state.items.filter((_, n) => n !== at)];
191
+ return { ...state, items, activeId: item.id, ...touch(state, item.id), focusId: item.id };
192
+ }
193
+ case "sheet": {
194
+ const sheetOpen = action.open && state.items.length > 0;
195
+ return sheetOpen === state.sheetOpen ? state : { ...state, sheetOpen };
196
+ }
197
+ case "update": {
198
+ const at = state.items.findIndex((i) => i.id === action.id && i.type === "panel");
199
+ if (at === -1) return state;
200
+ const panel = state.items[at] as ChatDockPanel;
201
+ const changed = (Object.keys(action.patch) as (keyof ChatDockPanelPatch)[]).some((k) => panel[k] !== action.patch[k]);
202
+ if (!changed) return state;
203
+ const items = state.items.slice();
204
+ items[at] = { ...panel, ...action.patch };
205
+ return { ...state, items };
206
+ }
207
+ case "hydrate": {
208
+ // Only into an empty dock: anything opened before storage was read wins.
209
+ if (state.items.length > 0 || action.items.length === 0) return state;
210
+ const items = action.items.slice(0, cap);
211
+ const used: Record<string, number> = {};
212
+ items.forEach((i, n) => (used[i.id] = items.length - n));
213
+ return { ...state, items, activeId: items[0]?.id ?? null, used, clock: Math.max(state.clock, items.length) };
214
+ }
215
+ case "closeAll":
216
+ return state.items.length === 0 ? state : emptyChatDock;
217
+ }
218
+ }
219
+
220
+ // ---------------------------------------------------------------------------------------------
221
+ // Storage
222
+
223
+ interface StoredItem {
224
+ conversationId: string;
225
+ title?: string;
226
+ }
227
+
228
+ const storage = createLocalStorageAdapter();
229
+ const storageName = (key: string, userId: string) => `${key}:${userId}`;
230
+
231
+ function readStored(key: string, userId: string, max: number): ChatDockItem[] {
232
+ try {
233
+ const raw = storage.getItem(storageName(key, userId));
234
+ const parsed: unknown = raw ? JSON.parse(raw) : null;
235
+ if (!Array.isArray(parsed)) return [];
236
+ return parsed
237
+ .filter((s): s is StoredItem => !!s && typeof (s as StoredItem).conversationId === "string" && (s as StoredItem).conversationId !== "")
238
+ .slice(0, Math.max(1, max))
239
+ .map((s) => ({
240
+ type: "conversation" as const,
241
+ id: s.conversationId,
242
+ conversationId: s.conversationId,
243
+ ...(typeof s.title === "string" ? { title: s.title } : {}),
244
+ // Brought back as bars: nothing opens over the page on load.
245
+ minimized: true,
246
+ restored: true,
247
+ }));
248
+ } catch {
249
+ return [];
250
+ }
251
+ }
252
+
253
+ function writeStored(key: string, userId: string, items: ChatDockItem[]) {
254
+ const stored: StoredItem[] = items
255
+ .filter((i): i is ChatDockConversation => i.type === "conversation")
256
+ .map((i) => ({ conversationId: i.conversationId, ...(i.title ? { title: i.title } : {}) }));
257
+ if (stored.length === 0) storage.removeItem(storageName(key, userId));
258
+ else storage.setItem(storageName(key, userId), JSON.stringify(stored));
259
+ }
260
+
261
+ /** Forgets what the dock kept for this person under `storageKey` (call it on sign-out on a shared browser). */
262
+ export function forgetChatDock(storageKey: string, userId: string): void {
263
+ storage.removeItem(storageName(storageKey, userId));
264
+ }
265
+
266
+ const noSubscribe = () => () => {};
267
+ /** False while hydrating server HTML (it must match), true once the client renders on its own. */
268
+ function useHydrated(): boolean {
269
+ return useSyncExternalStore(
270
+ noSubscribe,
271
+ () => true,
272
+ () => false,
273
+ );
274
+ }
275
+
276
+ // ---------------------------------------------------------------------------------------------
277
+ // Provider
278
+
279
+ export interface OpenConversationOptions {
280
+ /** The window's title; worked out from the conversation by default. */
281
+ title?: string;
282
+ /** Open it as a bar. */
283
+ minimized?: boolean;
284
+ }
285
+
286
+ export type OpenPanelInput = Omit<ChatDockPanel, "type" | "minimized"> & { minimized?: boolean };
287
+
288
+ export interface ChatDockApi {
289
+ items: ChatDockItem[];
290
+ activeId: string | null;
291
+ /** The one whose composer takes focus (just opened or restored). */
292
+ focusId: string | null;
293
+ /** Opens a conversation in the dock, or brings it back if it's there. */
294
+ open: (conversationId: string, opts?: OpenConversationOptions) => void;
295
+ /** Opens a panel of your own in the dock (the help desk messenger), or brings it back. */
296
+ openPanel: (panel: OpenPanelInput) => void;
297
+ /**
298
+ * Changes a docked panel in place (its unread count as it changes, its title) without moving,
299
+ * opening or restoring it. Nothing happens if that panel isn't docked, or nothing changed.
300
+ */
301
+ updatePanel: (id: string, patch: ChatDockPanelPatch) => void;
302
+ close: (id: string) => void;
303
+ closeAll: () => void;
304
+ minimize: (id: string) => void;
305
+ restore: (id: string) => void;
306
+ /** Shows this one in the narrow screen's sheet, without reordering. */
307
+ activate: (id: string) => void;
308
+ /** Moves one waiting behind "+N" into view, first. */
309
+ bringToFront: (id: string) => void;
310
+ /** Expands an item to its page (its own `onExpand`, else the dock's), and takes it out of the dock. */
311
+ expand: (id: string) => void;
312
+ /** Whether expanding means anything (a panel's own `onExpand` or the dock's). */
313
+ canExpand: (item: ChatDockItem) => boolean;
314
+ /** The narrow screen's sheet. */
315
+ sheetOpen: boolean;
316
+ setSheetOpen: (open: boolean) => void;
317
+ }
318
+
319
+ export interface ChatDockProviderProps {
320
+ /** How many windows at once. Default 3. */
321
+ max?: number;
322
+ /** "Expand": open the item on the zone's Messages page (route to it). Without it there's no expand button for conversations. */
323
+ onExpand?: (item: ChatDockItem) => void;
324
+ /**
325
+ * Keep the open conversations (not panels: they hold functions) across reloads, in this
326
+ * browser's localStorage under this key and the signed-in person's id, so the next person on a
327
+ * shared browser never sees them (`forgetChatDock` clears it on sign-out). They come back as
328
+ * bars, after hydration, and any that no longer exist are dropped. Off by default.
329
+ */
330
+ storageKey?: string;
331
+ children: ReactNode;
332
+ }
333
+
334
+ const DockContext = createContext<ChatDockApi | null>(null);
335
+
336
+ export function ChatDockProvider({ max = 3, onExpand, storageKey, children }: ChatDockProviderProps) {
337
+ const { userId, client } = useChat();
338
+ const [state, dispatch] = useReducer((s: ChatDockState, a: ChatDockAction) => chatDockReducer(s, a, max), emptyChatDock);
339
+ const hydrated = useHydrated();
340
+ // Read once storage is reachable without changing the server's HTML, and only then write, so
341
+ // the first (empty) render never wipes what was kept.
342
+ const [loadedFor, setLoadedFor] = useState<string | null>(null);
343
+ const storeKey = storageKey && userId ? `${storageKey}\u0000${userId}` : null;
344
+ useEffect(() => {
345
+ if (!hydrated || !storageKey || !userId || loadedFor === storeKey) return;
346
+ dispatch({ type: "hydrate", items: readStored(storageKey, userId, max) });
347
+ setLoadedFor(storeKey);
348
+ }, [hydrated, storageKey, userId, storeKey, loadedFor, max]);
349
+ useEffect(() => {
350
+ if (!storageKey || !userId || loadedFor !== storeKey) return;
351
+ writeStored(storageKey, userId, state.items);
352
+ }, [storageKey, userId, storeKey, loadedFor, state.items]);
353
+
354
+ // A conversation brought back from storage that no longer exists (or you've left) goes.
355
+ const restoredIds = state.items.filter((i): i is ChatDockConversation => i.type === "conversation" && !!i.restored).map((i) => i.conversationId).join(",");
356
+ useEffect(() => {
357
+ if (!restoredIds) return;
358
+ let live = true;
359
+ for (const id of restoredIds.split(",")) {
360
+ void client
361
+ .conversation(id)
362
+ .then((c) => {
363
+ if (live && !c) dispatch({ type: "close", id });
364
+ })
365
+ .catch(() => undefined);
366
+ }
367
+ return () => {
368
+ live = false;
369
+ };
370
+ }, [restoredIds, client]);
371
+
372
+ const expandRef = useRef(onExpand);
373
+ expandRef.current = onExpand;
374
+ const itemsRef = useRef(state.items);
375
+ itemsRef.current = state.items;
376
+
377
+ const open = useCallback((conversationId: string, opts: OpenConversationOptions = {}) => {
378
+ if (!conversationId) return;
379
+ const item: ChatDockConversation = { type: "conversation", id: conversationId, conversationId, minimized: false };
380
+ if (opts.title) item.title = opts.title;
381
+ dispatch({ type: "open", item });
382
+ if (opts.minimized) dispatch({ type: "minimize", id: conversationId, minimized: true });
383
+ }, []);
384
+ const openPanel = useCallback(({ minimized, ...panel }: OpenPanelInput) => {
385
+ if (!panel.id) return;
386
+ dispatch({ type: "open", item: { ...panel, type: "panel", minimized: false } });
387
+ if (minimized) dispatch({ type: "minimize", id: panel.id, minimized: true });
388
+ }, []);
389
+ const updatePanel = useCallback((id: string, patch: ChatDockPanelPatch) => dispatch({ type: "update", id, patch }), []);
390
+ const close = useCallback((id: string) => dispatch({ type: "close", id }), []);
391
+ const closeAll = useCallback(() => dispatch({ type: "closeAll" }), []);
392
+ const minimize = useCallback((id: string) => dispatch({ type: "minimize", id, minimized: true }), []);
393
+ const restore = useCallback((id: string) => dispatch({ type: "minimize", id, minimized: false }), []);
394
+ const activate = useCallback((id: string) => dispatch({ type: "activate", id }), []);
395
+ const bringToFront = useCallback((id: string) => dispatch({ type: "front", id }), []);
396
+ const setSheetOpen = useCallback((o: boolean) => dispatch({ type: "sheet", open: o }), []);
397
+ const hasExpand = !!onExpand;
398
+ const canExpand = useCallback((item: ChatDockItem) => (item.type === "panel" && !!item.onExpand) || hasExpand, [hasExpand]);
399
+ const expand = useCallback((id: string) => {
400
+ const item = itemsRef.current.find((i) => i.id === id);
401
+ if (!item) return;
402
+ const run = item.type === "panel" && item.onExpand ? item.onExpand : expandRef.current ? () => expandRef.current!(item) : null;
403
+ if (!run) return;
404
+ // Out of the dock first: the page it opens shows the same conversation, and two composers
405
+ // for one conversation side by side is one too many.
406
+ dispatch({ type: "close", id });
407
+ run();
408
+ }, []);
409
+
410
+ const api = useMemo<ChatDockApi>(
411
+ () => ({
412
+ items: state.items,
413
+ activeId: state.activeId,
414
+ focusId: state.focusId,
415
+ sheetOpen: state.sheetOpen,
416
+ open,
417
+ openPanel,
418
+ updatePanel,
419
+ close,
420
+ closeAll,
421
+ minimize,
422
+ restore,
423
+ activate,
424
+ bringToFront,
425
+ expand,
426
+ canExpand,
427
+ setSheetOpen,
428
+ }),
429
+ [state.items, state.activeId, state.focusId, state.sheetOpen, open, openPanel, updatePanel, close, closeAll, minimize, restore, activate, bringToFront, expand, canExpand, setSheetOpen],
430
+ );
431
+ return <DockContext.Provider value={api}>{children}</DockContext.Provider>;
432
+ }
433
+
434
+ /** The dock: open a conversation or a panel in it from anywhere under `ChatDockProvider`. */
435
+ export function useChatDock(): ChatDockApi {
436
+ const api = useContext(DockContext);
437
+ if (!api) throw new Error("useChatDock needs a ChatDockProvider above it (under ChatProvider).");
438
+ return api;
439
+ }
440
+
441
+ /** The dock when there is one, else null: for a button that opens in the dock when the app has one, and navigates when it doesn't. */
442
+ export function useOptionalChatDock(): ChatDockApi | null {
443
+ return useContext(DockContext);
444
+ }
445
+
446
+ // ---------------------------------------------------------------------------------------------
447
+ // Rendering
448
+
449
+ export interface ChatDockLabels {
450
+ minimize: string;
451
+ restore: string;
452
+ expand: string;
453
+ close: string;
454
+ /** The narrow screen's bubble. */
455
+ openDock: string;
456
+ /** The sheet's name for screen readers. */
457
+ sheetTitle: string;
458
+ sheetDescription: string;
459
+ /** "3 unread". */
460
+ unread: (n: number) => string;
461
+ /** The live announcement of everything unread in the dock. */
462
+ unreadTotal: (n: number) => string;
463
+ /** "+2": the windows that don't fit, and its menu's name. */
464
+ more: (n: number) => string;
465
+ moreLabel: (n: number) => string;
466
+ /** A conversation whose title isn't known yet. */
467
+ conversation: string;
468
+ }
469
+
470
+ export const defaultChatDockLabels: ChatDockLabels = {
471
+ minimize: "Minimize",
472
+ restore: "Open",
473
+ expand: "Open in Messages",
474
+ close: "Close",
475
+ openDock: "Open conversations",
476
+ sheetTitle: "Conversations",
477
+ sheetDescription: "Your open conversations.",
478
+ unread: (n) => `${n} unread`,
479
+ unreadTotal: (n) => (n > 0 ? `${n} unread in your open conversations` : ""),
480
+ more: (n) => `+${n}`,
481
+ moreLabel: (n) => `${n} more conversation${n === 1 ? "" : "s"}`,
482
+ conversation: "Conversation",
483
+ };
484
+
485
+ export interface ChatDockProps {
486
+ resolveUser: ResolveUser;
487
+ /** Passed to every docked conversation's ChatThread. */
488
+ threadProps?: Partial<Omit<ChatThreadProps, "conversationId" | "resolveUser" | "onBack" | "title" | "markRead" | "autoFocus">>;
489
+ labels?: Partial<ChatDockLabels>;
490
+ /** The narrow screen's bubble when the sheet is closed. Default true. */
491
+ bubble?: boolean;
492
+ className?: string;
493
+ }
494
+
495
+ /** A window's width and the gap between windows, in px (22rem and 0.75rem), and the dock's side padding. */
496
+ const WINDOW_PX = 352;
497
+ const GAP_PX = 12;
498
+ const PAD_PX = 32;
499
+ /** Room for the "+N" button beside the windows. */
500
+ const MORE_PX = 56;
501
+
502
+ function subscribeWidth(cb: () => void) {
503
+ window.addEventListener("resize", cb);
504
+ return () => window.removeEventListener("resize", cb);
505
+ }
506
+ /** The viewport's width (the server renders as wide). */
507
+ function useViewportWidth(): number {
508
+ return useSyncExternalStore(
509
+ subscribeWidth,
510
+ () => window.innerWidth,
511
+ () => 1440,
512
+ );
513
+ }
514
+
515
+ /** How many of `count` windows fit side by side at `width`, leaving room for "+N" when some don't. */
516
+ export function chatDockWindowsThatFit(width: number, count: number): number {
517
+ const fits = (room: number) => Math.max(1, Math.floor((room - PAD_PX + GAP_PX) / (WINDOW_PX + GAP_PX)));
518
+ const all = fits(width);
519
+ return count <= all ? count : fits(width - MORE_PX);
520
+ }
521
+
522
+ function conversationTitle(item: ChatDockConversation, inbox: Map<string, ChatInboxItem>, resolveUser: ResolveUser, labels: ChatDockLabels): string {
523
+ if (item.title) return item.title;
524
+ const row = inbox.get(item.conversationId);
525
+ return row ? inboxTitle(row, resolveUser, () => labels.conversation) : labels.conversation;
526
+ }
527
+
528
+ function itemTitle(item: ChatDockItem, inbox: Map<string, ChatInboxItem>, resolveUser: ResolveUser, labels: ChatDockLabels): string {
529
+ return item.type === "panel" ? item.title : conversationTitle(item, inbox, resolveUser, labels);
530
+ }
531
+
532
+ function itemUnread(item: ChatDockItem, inbox: Map<string, ChatInboxItem>): number {
533
+ if (item.type === "panel") return item.unread ?? 0;
534
+ const row = inbox.get(item.conversationId);
535
+ return row && !row.muted ? row.unread : 0;
536
+ }
537
+
538
+ interface HeaderInfo {
539
+ title: string;
540
+ subtitle: string | null;
541
+ otherUserId: string | null;
542
+ }
543
+
544
+ interface TitleBarProps {
545
+ item: ChatDockItem;
546
+ title: string;
547
+ avatar: ReactNode;
548
+ subtitle: string | null;
549
+ unread: number;
550
+ labels: ChatDockLabels;
551
+ /** On the narrow screen: no minimize (the sheet closes instead). */
552
+ inSheet: boolean;
553
+ toggleRef?: RefObject<HTMLButtonElement | null>;
554
+ }
555
+
556
+ function DockTitleBar({ item, title, avatar, subtitle, unread, labels, inSheet, toggleRef }: TitleBarProps) {
557
+ const dock = useChatDock();
558
+ const toggle = () => (item.minimized ? dock.restore(item.id) : dock.minimize(item.id));
559
+ const titleText = (
560
+ <span className="min-w-0 flex-1 text-left">
561
+ <span className="block truncate text-sm font-semibold leading-tight">{title}</span>
562
+ {subtitle ? <span className="block truncate text-xs text-muted-foreground">{subtitle}</span> : null}
563
+ </span>
564
+ );
565
+ return (
566
+ <div className="flex min-h-12 shrink-0 items-center gap-1 border-b bg-background px-2 py-1.5" data-testid="genesis-chat-dock-titlebar">
567
+ {inSheet ? (
568
+ <div className="flex min-w-0 flex-1 items-center gap-2 px-1">
569
+ {avatar}
570
+ {titleText}
571
+ </div>
572
+ ) : (
573
+ <button
574
+ ref={toggleRef}
575
+ type="button"
576
+ onClick={toggle}
577
+ aria-expanded={!item.minimized}
578
+ aria-label={`${title}${unread > 0 ? `, ${labels.unread(unread)}` : ""}. ${item.minimized ? labels.restore : labels.minimize}`}
579
+ className="flex min-h-9 min-w-0 flex-1 items-center gap-2 rounded-md px-1 text-left hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
580
+ data-testid="genesis-chat-dock-toggle"
581
+ >
582
+ {avatar}
583
+ {titleText}
584
+ {unread > 0 ? (
585
+ <span className="inline-flex h-5 min-w-5 shrink-0 items-center justify-center rounded-full bg-primary px-1.5 text-[11px] font-semibold text-primary-foreground" aria-hidden>
586
+ {unread > 99 ? "99+" : unread}
587
+ </span>
588
+ ) : null}
589
+ {item.minimized ? <ChevronUp className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden /> : <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />}
590
+ </button>
591
+ )}
592
+ {dock.canExpand(item) ? (
593
+ <Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => dock.expand(item.id)} aria-label={labels.expand} title={labels.expand} data-testid="genesis-chat-dock-expand">
594
+ <Maximize2 />
595
+ </Button>
596
+ ) : null}
597
+ <Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => dock.close(item.id)} aria-label={labels.close} title={labels.close} data-testid="genesis-chat-dock-close">
598
+ <X />
599
+ </Button>
600
+ </div>
601
+ );
602
+ }
603
+
604
+ interface ItemProps {
605
+ item: ChatDockItem;
606
+ inbox: Map<string, ChatInboxItem>;
607
+ resolveUser: ResolveUser;
608
+ threadProps: ChatDockProps["threadProps"];
609
+ labels: ChatDockLabels;
610
+ inSheet: boolean;
611
+ /** Whether its body is on screen (not minimized, or the sheet's active tab with the sheet open). */
612
+ visible: boolean;
613
+ /** Its composer takes focus (it was just opened or restored). */
614
+ focus: boolean;
615
+ toggleRef?: RefObject<HTMLButtonElement | null>;
616
+ }
617
+
618
+ /**
619
+ * One docked item: the title bar (always the same element, so focus on it survives minimizing)
620
+ * and the body under it, kept mounted while hidden.
621
+ */
622
+ function DockItemView({ item, inbox, resolveUser, threadProps, labels, inSheet, visible, focus, toggleRef }: ItemProps) {
623
+ const unread = itemUnread(item, inbox);
624
+ // What the thread worked out for its header (title, "typing…"), shown in the dock's bar.
625
+ const [header, setHeader] = useState<HeaderInfo | null>(null);
626
+ const Report = useMemo(
627
+ () =>
628
+ function ReportHeader({ title, activity, subtitle, otherUserId }: ChatThreadHeaderProps) {
629
+ const sub = activity ?? subtitle;
630
+ useEffect(() => {
631
+ setHeader((h) => (h && h.title === title && h.subtitle === sub && h.otherUserId === otherUserId ? h : { title, subtitle: sub, otherUserId }));
632
+ }, [title, sub, otherUserId]);
633
+ return null;
634
+ },
635
+ [],
636
+ );
637
+
638
+ if (item.type === "panel") {
639
+ return (
640
+ <>
641
+ <DockTitleBar
642
+ item={item}
643
+ title={item.title}
644
+ avatar={item.icon ? <span className="flex h-8 w-8 shrink-0 items-center justify-center">{item.icon}</span> : <UserAvatar name={item.title} size="sm" />}
645
+ subtitle={null}
646
+ unread={unread}
647
+ labels={labels}
648
+ inSheet={inSheet}
649
+ toggleRef={toggleRef}
650
+ />
651
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto" hidden={!visible} data-testid="genesis-chat-dock-panel">
652
+ {item.render()}
653
+ </div>
654
+ </>
655
+ );
656
+ }
657
+
658
+ const row = inbox.get(item.conversationId);
659
+ const title = item.title ?? header?.title ?? conversationTitle(item, inbox, resolveUser, labels);
660
+ const otherId = header?.otherUserId ?? row?.otherUserId ?? null;
661
+ const other = otherId ? resolveUser(otherId) : null;
662
+ return (
663
+ <>
664
+ <DockTitleBar
665
+ item={item}
666
+ title={title}
667
+ avatar={<UserAvatar name={title} src={other?.avatarUrl} size="sm" />}
668
+ subtitle={visible ? (header?.subtitle ?? null) : null}
669
+ unread={visible ? 0 : unread}
670
+ labels={labels}
671
+ inSheet={inSheet}
672
+ toggleRef={toggleRef}
673
+ />
674
+ <div className="flex min-h-0 flex-1 flex-col" hidden={!visible} data-testid="genesis-chat-dock-body">
675
+ <ChatThread
676
+ {...threadProps}
677
+ conversationId={item.conversationId}
678
+ resolveUser={resolveUser}
679
+ {...(item.title ? { title: item.title } : {})}
680
+ // Out of sight it keeps its draft, and reads nothing.
681
+ markRead={visible}
682
+ autoFocus={visible && focus}
683
+ className={cn("min-h-0 flex-1", threadProps?.className)}
684
+ slots={{ ...threadProps?.slots, header: Report }}
685
+ />
686
+ </div>
687
+ </>
688
+ );
689
+ }
690
+
691
+ function isEscape(e: KeyboardEvent<HTMLElement>): boolean {
692
+ // Not while an input method is composing (Escape cancels the composition there), and not when
693
+ // something inside (a menu, the emoji picker) already handled it.
694
+ return e.key === "Escape" && !e.defaultPrevented && !e.nativeEvent.isComposing && e.keyCode !== 229;
695
+ }
696
+
697
+ function DockWindow(props: Omit<ItemProps, "inSheet" | "visible" | "toggleRef">) {
698
+ const dock = useChatDock();
699
+ const { item } = props;
700
+ const toggleRef = useRef<HTMLButtonElement | null>(null);
701
+ const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
702
+ if (!isEscape(e) || item.minimized) return;
703
+ e.preventDefault();
704
+ dock.minimize(item.id);
705
+ // The composer it was in is about to hide: focus stays in the window, on its bar.
706
+ toggleRef.current?.focus();
707
+ };
708
+ return (
709
+ <section
710
+ aria-label={itemTitle(item, props.inbox, props.resolveUser, props.labels)}
711
+ onKeyDown={onKeyDown}
712
+ className={cn(
713
+ "pointer-events-auto flex w-[22rem] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-t-xl border border-b-0 bg-background shadow-xl",
714
+ // An open window is at most 26rem tall, and never more than 60% of the screen's height,
715
+ // so the page under it stays in view.
716
+ item.minimized ? "h-auto" : "h-[min(26rem,60dvh)]",
717
+ )}
718
+ data-testid="genesis-chat-dock-window"
719
+ data-minimized={item.minimized || undefined}
720
+ >
721
+ <DockItemView {...props} inSheet={false} visible={!item.minimized} toggleRef={toggleRef} />
722
+ </section>
723
+ );
724
+ }
725
+
726
+ function SheetSwitcher({ items, activeId, inbox, resolveUser, labels }: { items: ChatDockItem[]; activeId: string; inbox: Map<string, ChatInboxItem>; resolveUser: ResolveUser; labels: ChatDockLabels }) {
727
+ const dock = useChatDock();
728
+ const tabs = useRef<(HTMLButtonElement | null)[]>([]);
729
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
730
+ const at = items.findIndex((i) => i.id === activeId);
731
+ const to = e.key === "ArrowRight" ? at + 1 : e.key === "ArrowLeft" ? at - 1 : e.key === "Home" ? 0 : e.key === "End" ? items.length - 1 : null;
732
+ if (to === null) return;
733
+ e.preventDefault();
734
+ const next = items[(to + items.length) % items.length]!;
735
+ dock.activate(next.id);
736
+ tabs.current[items.indexOf(next)]?.focus();
737
+ };
738
+ return (
739
+ <div role="tablist" aria-label={labels.sheetTitle} onKeyDown={onKeyDown} className="flex shrink-0 gap-1 overflow-x-auto border-b px-2 py-1.5" data-testid="genesis-chat-dock-switcher">
740
+ {items.map((i, n) => {
741
+ const selected = i.id === activeId;
742
+ const count = selected ? 0 : itemUnread(i, inbox);
743
+ return (
744
+ <button
745
+ key={i.id}
746
+ ref={(el) => {
747
+ tabs.current[n] = el;
748
+ }}
749
+ type="button"
750
+ role="tab"
751
+ id={`genesis-chat-dock-tab-${i.id}`}
752
+ aria-selected={selected}
753
+ aria-controls={`genesis-chat-dock-panel-${i.id}`}
754
+ tabIndex={selected ? 0 : -1}
755
+ onClick={() => dock.activate(i.id)}
756
+ className={cn(
757
+ "flex min-h-9 max-w-[10rem] shrink-0 items-center gap-1.5 rounded-full px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
758
+ selected ? "bg-accent font-medium text-accent-foreground" : "text-muted-foreground hover:bg-accent/60",
759
+ )}
760
+ >
761
+ <span className="truncate">{itemTitle(i, inbox, resolveUser, labels)}</span>
762
+ {count > 0 ? (
763
+ <span className="inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold text-primary-foreground" aria-label={labels.unread(count)}>
764
+ {count > 99 ? "99+" : count}
765
+ </span>
766
+ ) : null}
767
+ </button>
768
+ );
769
+ })}
770
+ </div>
771
+ );
772
+ }
773
+
774
+ /**
775
+ * The dock's windows (wide screens) or its sheet and bubble (narrow). Render it once, under
776
+ * `ChatDockProvider`: in AppShell's `dock` slot, or anywhere fixed positioning is free.
777
+ */
778
+ export function ChatDock({ resolveUser, threadProps, labels: labelOverrides, bubble = true, className }: ChatDockProps) {
779
+ const dock = useChatDock();
780
+ const narrow = useIsMobile();
781
+ const width = useViewportWidth();
782
+ const labels = useMemo(() => ({ ...defaultChatDockLabels, ...labelOverrides }), [labelOverrides]);
783
+ // The same query the inbox uses, so titles and unread counts come from its cache and stay live.
784
+ const { items: inboxItems } = useInbox();
785
+ const inbox = useMemo(() => new Map(inboxItems.map((i) => [i.conversationId, i])), [inboxItems]);
786
+
787
+ if (dock.items.length === 0) return null;
788
+
789
+ const active = dock.items.find((i) => i.id === dock.activeId) ?? dock.items[0]!;
790
+ const seen = (i: ChatDockItem) => (narrow ? dock.sheetOpen && i.id === active.id : !i.minimized);
791
+ const unreadTotal = dock.items.reduce((n, i) => n + (seen(i) ? 0 : itemUnread(i, inbox)), 0);
792
+ const announce = (
793
+ <span className="sr-only" aria-live="polite" data-testid="genesis-chat-dock-announce">
794
+ {labels.unreadTotal(unreadTotal)}
795
+ </span>
796
+ );
797
+
798
+ if (narrow) {
799
+ return (
800
+ <>
801
+ {announce}
802
+ {bubble && !dock.sheetOpen ? (
803
+ <div className={cn("pointer-events-none flex justify-end p-4", className)}>
804
+ <button
805
+ type="button"
806
+ onClick={() => dock.setSheetOpen(true)}
807
+ aria-label={`${labels.openDock}${unreadTotal > 0 ? `, ${labels.unread(unreadTotal)}` : ""}`}
808
+ aria-haspopup="dialog"
809
+ className="pointer-events-auto relative flex h-14 w-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
810
+ data-testid="genesis-chat-dock-bubble"
811
+ >
812
+ <MessageCircle className="h-6 w-6" aria-hidden />
813
+ {unreadTotal > 0 ? (
814
+ <span className="absolute -right-0.5 -top-0.5 inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[11px] font-semibold text-destructive-foreground ring-2 ring-background" aria-hidden>
815
+ {unreadTotal > 99 ? "99+" : unreadTotal}
816
+ </span>
817
+ ) : null}
818
+ </button>
819
+ </div>
820
+ ) : null}
821
+ <Sheet open={dock.sheetOpen} onOpenChange={dock.setSheetOpen}>
822
+ <SheetContent side="right" showCloseButton={false} className="flex w-full flex-col gap-0 p-0 sm:max-w-md" data-testid="genesis-chat-dock-sheet">
823
+ <SheetTitle className="sr-only">{labels.sheetTitle}</SheetTitle>
824
+ <SheetDescription className="sr-only">{labels.sheetDescription}</SheetDescription>
825
+ {dock.items.length > 1 ? <SheetSwitcher items={dock.items} activeId={active.id} inbox={inbox} resolveUser={resolveUser} labels={labels} /> : null}
826
+ {/* Every one stays mounted, so switching tabs keeps each one's draft. */}
827
+ {dock.items.map((i) => (
828
+ <div
829
+ key={i.id}
830
+ role={dock.items.length > 1 ? "tabpanel" : undefined}
831
+ id={`genesis-chat-dock-panel-${i.id}`}
832
+ aria-labelledby={dock.items.length > 1 ? `genesis-chat-dock-tab-${i.id}` : undefined}
833
+ hidden={i.id !== active.id}
834
+ className="flex min-h-0 flex-1 flex-col"
835
+ >
836
+ <DockItemView
837
+ item={i}
838
+ inbox={inbox}
839
+ resolveUser={resolveUser}
840
+ threadProps={threadProps}
841
+ labels={labels}
842
+ inSheet
843
+ visible={dock.sheetOpen && i.id === active.id}
844
+ focus={dock.focusId === i.id}
845
+ />
846
+ </div>
847
+ ))}
848
+ </SheetContent>
849
+ </Sheet>
850
+ </>
851
+ );
852
+ }
853
+
854
+ // As many as fit side by side; the rest wait behind "+N".
855
+ const shown = dock.items.slice(0, chatDockWindowsThatFit(width, dock.items.length));
856
+ const waiting = dock.items.slice(shown.length);
857
+ return (
858
+ <div className={cn("pointer-events-none flex flex-row-reverse items-end gap-3 px-4", className)} data-testid="genesis-chat-dock">
859
+ {announce}
860
+ {shown.map((item) => (
861
+ <DockWindow key={item.id} item={item} inbox={inbox} resolveUser={resolveUser} threadProps={threadProps} labels={labels} focus={dock.focusId === item.id} />
862
+ ))}
863
+ {waiting.length > 0 ? (
864
+ <DropdownMenu>
865
+ <DropdownMenuTrigger asChild>
866
+ <Button
867
+ type="button"
868
+ variant="secondary"
869
+ className="pointer-events-auto mb-1 h-11 min-w-11 rounded-full shadow-lg"
870
+ style={{ width: MORE_PX - GAP_PX }}
871
+ aria-label={labels.moreLabel(waiting.length)}
872
+ data-testid="genesis-chat-dock-more"
873
+ >
874
+ {labels.more(waiting.length)}
875
+ </Button>
876
+ </DropdownMenuTrigger>
877
+ <DropdownMenuContent align="end" side="top">
878
+ {waiting.map((i) => (
879
+ <DropdownMenuItem key={i.id} onSelect={() => dock.bringToFront(i.id)}>
880
+ {itemTitle(i, inbox, resolveUser, labels)}
881
+ {itemUnread(i, inbox) > 0 ? ` (${labels.unread(itemUnread(i, inbox))})` : ""}
882
+ </DropdownMenuItem>
883
+ ))}
884
+ </DropdownMenuContent>
885
+ </DropdownMenu>
886
+ ) : null}
887
+ </div>
888
+ );
889
+ }