@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
@@ -1,21 +1,19 @@
1
1
  /**
2
2
  * @feat:chat
3
- * One conversation: a list oldest first, top to bottom, the order it reads in
4
- * with VoiceOver (FlashList's bottom-anchored chat mode when the app gave it,
5
- * else FlatList), that opens at the newest message, follows new ones while
6
- * you are at the bottom, goes to the bottom when you send, and keeps its
7
- * place while earlier ones load at the top; day separators, the "New messages" line,
3
+ * One conversation, on genesis-ui-native's `NativeThreadList`: oldest first,
4
+ * top to bottom, the order it reads in with VoiceOver (FlashList's
5
+ * bottom-anchored chat mode when the app gave it, else FlatList), opening at
6
+ * the newest message, following new ones while you are at the bottom, going
7
+ * to the bottom when you send, and keeping its place while earlier ones load
8
+ * at the top; day separators, the "New messages" line,
8
9
  * grouped bubbles with names and avatars in groups, who is typing or
9
10
  * recording, retry and delete on a send that failed, the long-press sheet and
10
11
  * swipe to reply, a message's photos in the full-screen viewer, and the composer above
11
12
  * the keyboard (or, when your role couldn't be read, Retry). Render it as the screen's only content, under the
12
13
  * navigator's header with `useChatThreadStackOptions` (an opaque bar).
13
14
  *
14
- * Not inverted: FlashList 2 keeps the first visible row in place when rows
15
- * change and only follows new rows at the bottom (`autoscrollToBottomThreshold`;
16
- * it declares `autoscrollToTopThreshold` but never reads it), so in an inverted list a new message
17
- * at index 0 was pushed under the composer. Inverted, VoiceOver also read
18
- * each day's heading after its messages.
15
+ * A row is keyed by the message's client id (it keeps its row when the
16
+ * server's copy lands) and gone to by the server's id (`jumpId`).
19
17
  *
20
18
  * Organising: a topic bar when the conversation has topics (the list shows the topic chosen; a
21
19
  * closed one takes no posts from members), the away line under the header, scheduled send
@@ -23,9 +21,9 @@
23
21
  * message (a search result), and moderation's markers.
24
22
  */
25
23
  import { useCallback, useEffect, useMemo, useRef, useState, type ComponentType } from "react";
26
- import { AccessibilityInfo, FlatList, KeyboardAvoidingView, Platform, Pressable, View, type LayoutChangeEvent, type NativeScrollEvent, type NativeSyntheticEvent } from "react-native";
24
+ import { KeyboardAvoidingView, Platform, View } from "react-native";
27
25
  import { SafeAreaView } from "react-native-safe-area-context";
28
- import { NativeEmptyState, NativeSkeleton, NativeText, useGenesisModules, useToast } from "@marktiderman/genesis-ui-native/components";
26
+ import { NativeEmptyState, NativeText, NativeThreadList, useGenesisModules, useToast, type NativeThreadListHandle, type ThreadRowInfo } from "@marktiderman/genesis-ui-native/components";
29
27
  import { useReducedMotion, useThemeRoles } from "@marktiderman/genesis-ui-native/hooks";
30
28
  import { activityLine } from "../core/thread";
31
29
  import type { ChatMessage, PendingFile } from "../core/types";
@@ -40,7 +38,7 @@ import { ChatAwayLine, useAwayLine } from "./availability";
40
38
  import { fill } from "./copy";
41
39
  import { ChatScheduledBar, ChatScheduleSheet, useScheduleSend } from "./schedule-sheet";
42
40
  import { canManageTopics, ChatTopicBar, topicClosedFor } from "./topics";
43
- import { rowIndexOf, useJumpToMessage, type JumpTarget } from "./use-jump";
41
+ import type { JumpTarget } from "./use-jump";
44
42
  import type { MessageActionId } from "./actions";
45
43
  import { ChatComposer } from "./composer";
46
44
  import { composerDisabledReason, filesFromAssets, replyTargetFor } from "./composer-state";
@@ -51,7 +49,7 @@ import { attachmentPaths } from "./media";
51
49
  import { ChatPhotoViewer, galleryFor, type ChatPhoto } from "./photo-viewer";
52
50
  import { MessageActionsSheet } from "./message-actions-sheet";
53
51
  import { displayBody, MessageBubble } from "./message-bubble";
54
- import { haptic } from "./modules";
52
+ import { haptic, type KeyboardAvoidingLike } from "./modules";
55
53
  import { pauseChatPlayback } from "./voice-player";
56
54
  import { buildThreadRows, type ThreadRow } from "./rows";
57
55
 
@@ -102,32 +100,10 @@ export interface ChatThreadScreenSlots {
102
100
  attachment?: ChatAttachmentSlot | null;
103
101
  }
104
102
 
105
- /** The list props chat passes; FlashList v2 and FlatList both take them. */
106
- interface ChatListProps {
107
- ref?: unknown;
108
- data: readonly ThreadRow[];
109
- renderItem: (info: { item: ThreadRow; index: number }) => React.ReactElement | null;
110
- keyExtractor: (row: ThreadRow) => string;
111
- getItemType?: (row: ThreadRow) => string;
112
- inverted?: boolean;
113
- onStartReached?: () => void;
114
- onStartReachedThreshold?: number;
115
- ListHeaderComponent?: React.ReactElement | null;
116
- ListFooterComponent?: React.ReactElement | null;
117
- keyboardShouldPersistTaps?: "handled";
118
- keyboardDismissMode?: "interactive" | "on-drag";
119
- contentContainerStyle?: Record<string, unknown>;
120
- maintainVisibleContentPosition?: Record<string, unknown>;
121
- onScroll?: (e: NativeSyntheticEvent<NativeScrollEvent>) => void;
122
- scrollEventThrottle?: number;
123
- onContentSizeChange?: (width: number, height: number) => void;
124
- onLayout?: (e: LayoutChangeEvent) => void;
125
- extraData?: unknown;
126
- onScrollToIndexFailed?: (info: { index: number; averageItemLength: number }) => void;
127
- testID?: string;
128
- }
129
-
130
- /** Points from the bottom that still count as "at the bottom" (FlatList, which follows by hand). */
103
+ /**
104
+ * Points from the bottom that still count as "at the bottom" (FlatList, which follows by hand).
105
+ * @deprecated Use genesis-ui-native's `THREAD_AT_BOTTOM_POINTS`. ChatThreadScreen is on NativeThreadList; this copy is removed in a later minor.
106
+ */
131
107
  export const AT_BOTTOM_POINTS = 120;
132
108
 
133
109
  /**
@@ -136,6 +112,7 @@ export const AT_BOTTOM_POINTS = 120;
136
112
  * a screen of it, keeps the first visible row in place when earlier ones load
137
113
  * at the top). FlatList: keeps its place when earlier rows load at the top;
138
114
  * the screen follows new rows itself (`followsByHand`).
115
+ * @deprecated Use genesis-ui-native's `threadListMode` (which anchors FlatList past the header, `minIndexForVisible: 1`). ChatThreadScreen is on NativeThreadList; this copy is removed in a later minor.
139
116
  */
140
117
  export function threadListMode(flash: boolean, reducedMotion: boolean): { followsByHand: boolean; maintainVisibleContentPosition: Record<string, unknown> } {
141
118
  if (flash) {
@@ -147,7 +124,10 @@ export function threadListMode(flash: boolean, reducedMotion: boolean): { follow
147
124
  return { followsByHand: true, maintainVisibleContentPosition: { minIndexForVisible: 0 } };
148
125
  }
149
126
 
150
- /** Whether a scroll position is at (or near) the bottom of its content. */
127
+ /**
128
+ * Whether a scroll position is at (or near) the bottom of its content.
129
+ * @deprecated Use genesis-ui-native's `threadNearBottom`. ChatThreadScreen is on NativeThreadList; this copy is removed in a later minor.
130
+ */
151
131
  export function nearBottom(m: { contentOffset: { y: number }; contentSize: { height: number }; layoutMeasurement: { height: number } }, slack = AT_BOTTOM_POINTS): boolean {
152
132
  return m.contentOffset.y + m.layoutMeasurement.height >= m.contentSize.height - slack;
153
133
  }
@@ -183,30 +163,9 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
183
163
  const colors = useThemeRoles();
184
164
  const reducedMotion = useReducedMotion();
185
165
  const genesis = useGenesisModules();
186
- const List = (genesis.list ?? FlatList) as unknown as ComponentType<ChatListProps>;
187
- const mode = threadListMode(Boolean(genesis.list), reducedMotion);
188
- const listRef = useRef<{
189
- scrollToEnd?: (o?: { animated?: boolean }) => void;
190
- scrollToIndex?: (o: { index: number; animated?: boolean; viewPosition?: number }) => void;
191
- scrollToOffset?: (o: { offset: number; animated?: boolean }) => void;
192
- } | null>(null);
193
- // FlatList follows by hand: at the bottom (or not yet scrolled), new rows and a shorter list keep it there.
194
- const atBottom = useRef(true);
195
- // FlatList opens at the top and is moved to the bottom a frame later: until it has been, the top
196
- // isn't "reached" (it would load an earlier page on every open).
197
- const placed = useRef(!mode.followsByHand);
198
- const toBottom = useCallback(
199
- (animated: boolean) => {
200
- const go = (a: boolean) => listRef.current?.scrollToEnd?.({ animated: a && !reducedMotion });
201
- requestAnimationFrame(() => {
202
- go(animated);
203
- placed.current = true;
204
- });
205
- // Once more after the new row has its size (FlashList measures it after the first pass).
206
- if (animated) setTimeout(() => go(true), 180);
207
- },
208
- [reducedMotion],
209
- );
166
+ const listRef = useRef<NativeThreadListHandle | null>(null);
167
+ // What you send is what you look at next, wherever the list was.
168
+ const toNewest = useCallback(() => listRef.current?.scrollToEnd({ animated: true }), []);
210
169
  const composer = useChatComposer(conversationId, threadRootId, userId);
211
170
  const { setReply } = composer;
212
171
  const [actionsFor, setActionsFor] = useState<ChatMessage | null>(null);
@@ -337,53 +296,31 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
337
296
  );
338
297
  const observer = conv.role === "observer";
339
298
  const { loadUntil } = conv;
340
- // The message being gone to, for FlatList's retry once it has measured that far (by id: rows may have moved).
341
- const jumpingTo = useRef<{ id: string; tries: number } | null>(null);
342
- const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
343
- useEffect(() => () => {
344
- if (retryTimer.current) clearTimeout(retryTimer.current);
345
- }, []);
346
- const rowsNow = useRef(rows);
347
- rowsNow.current = rows;
348
- const { highlightedId, jumping } = useJumpToMessage({
349
- target: jumpTo,
350
- rows,
351
- loading: conv.isLoading,
352
- has: useCallback((id: string) => byId.has(id), [byId]),
353
- loadUntil,
354
- scrollTo: (index, id) => {
355
- jumpingTo.current = { id, tries: 0 };
356
- const scroll = (at: number) => listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
357
- requestAnimationFrame(() => scroll(index));
358
- // Once more after the first layout: with the message already loaded (the thread was opened
359
- // before), the jump runs on the first frame, and FlashList's start-at-the-bottom placement,
360
- // which comes after it, would win and leave the thread at the bottom.
361
- if (retryTimer.current) clearTimeout(retryTimer.current);
362
- retryTimer.current = setTimeout(() => {
363
- const at = rowIndexOf(rowsNow.current, id);
364
- if (at >= 0) scroll(at);
365
- }, 250);
366
- },
367
- onStart: () => {
368
- atBottom.current = false;
369
- placed.current = true;
370
- },
371
- onLanded: (id) => {
372
- const m = byId.get(id);
373
- if (m) AccessibilityInfo.announceForAccessibility?.(fill(copy.jumpedTo, { name: nameOf(m.senderId), text: attachmentPreview(displayBody(m.body), m.attachments[0], attachmentKinds, Boolean(m.deletedAt)) }));
299
+ // A jump names the server's message id; its seq says how far back to load.
300
+ const jumpSeq = jumpTo?.seq;
301
+ const jumpMessageId = jumpTo?.messageId ?? null;
302
+ const onLoadUntil = useCallback(
303
+ (id: string) => {
304
+ if (id !== jumpMessageId || jumpSeq == null) return Promise.resolve(false);
305
+ return loadUntil(jumpSeq).catch(() => {
306
+ fail();
307
+ return false;
308
+ });
374
309
  },
375
- onGone: () => {
376
- toast.show({ title: copy.messageGone });
377
- // Back to where the thread opens: the newest messages.
378
- atBottom.current = true;
379
- toBottom(false);
310
+ [jumpMessageId, jumpSeq, loadUntil, fail],
311
+ );
312
+ const jumpAnnouncement = useCallback(
313
+ (row: ThreadRow) => {
314
+ const m = row.type === "message" && row.item.type === "message" ? row.item.message : null;
315
+ return m ? fill(copy.jumpedTo, { name: nameOf(m.senderId), text: attachmentPreview(displayBody(m.body), m.attachments[0], attachmentKinds, Boolean(m.deletedAt)) }) : "";
380
316
  },
381
- onError: fail,
382
- });
317
+ [copy.jumpedTo, nameOf, attachmentKinds],
318
+ );
319
+ const onJumpFailed = useCallback(() => toast.show({ title: copy.messageGone }), [toast, copy.messageGone]);
383
320
  const reattachable = useCallback((files: readonly PendingFile[]) => files.every((f) => !f.lost || f.kind === "image" || f.kind === "video"), []);
384
321
 
385
322
  const renderItem = useCallback(
386
- ({ item: row }: { item: ThreadRow }) => {
323
+ (row: ThreadRow, { highlighted }: ThreadRowInfo) => {
387
324
  if (row.type === "day") return <DaySeparator label={row.label} testID={`${testID}-day-${row.key}`} />;
388
325
  if (row.type === "unread") return <UnreadDivider label={copy.newMessages} testID={`${testID}-unread`} />;
389
326
  const m = row.item.type === "message" ? row.item.message : null;
@@ -405,7 +342,7 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
405
342
  onToggleReaction={allowed ? react : undefined}
406
343
  onOpenImage={onOpenImage}
407
344
  observer={observer}
408
- highlighted={Boolean(m && m.id === highlightedId)}
345
+ highlighted={highlighted}
409
346
  linkPreview={m ? previewToShow(previews[m.id]) : null}
410
347
  linkPreviewImages={linkPreviewImages}
411
348
  attachmentKinds={attachmentKinds}
@@ -416,7 +353,7 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
416
353
  />
417
354
  );
418
355
  },
419
- [testID, copy.newMessages, userId, urls, byId, group, reducedMotion, onLongPress, allowed, reply, onSwipeReply, onRetry, onDiscard, react, onOpenImage, picker, reattachable, onReattach, previews, linkPreviewImages, attachmentKinds, onOpenAttachment, attachmentSlot, cardActionTimeoutMs, observer, highlightedId],
356
+ [testID, copy.newMessages, userId, urls, byId, group, reducedMotion, onLongPress, allowed, reply, onSwipeReply, onRetry, onDiscard, react, onOpenImage, picker, reattachable, onReattach, previews, linkPreviewImages, attachmentKinds, onOpenAttachment, attachmentSlot, cardActionTimeoutMs, observer],
420
357
  );
421
358
 
422
359
  // ---- Video messages ----
@@ -445,10 +382,9 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
445
382
  (video: RecordedVideo) => {
446
383
  videoUploads.start({ conversationId, userId, video, extra: { replyToId: replyNow, threadRootId }, send: outbox.send, videoUpload, prepared: takePrepared(), openFile: modules.openFile });
447
384
  if (replyNow) setReply(null);
448
- atBottom.current = true;
449
- toBottom(true);
385
+ toNewest();
450
386
  },
451
- [conversationId, userId, replyNow, threadRootId, outbox, videoUpload, takePrepared, modules.openFile, setReply, toBottom],
387
+ [conversationId, userId, replyNow, threadRootId, outbox, videoUpload, takePrepared, modules.openFile, setReply, toNewest],
452
388
  );
453
389
 
454
390
  const activity = activityLine(conv.activity, (id) => nameOf(id));
@@ -470,13 +406,14 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
470
406
  setRetryingAccess(true);
471
407
  void Promise.resolve(refetchAccess()).finally(() => setRetryingAccess(false));
472
408
  }, [refetchAccess]);
473
- const KeyboardAvoiding = (modules.keyboardAvoidingView ?? KeyboardAvoidingView) as ComponentType<Record<string, unknown>>;
409
+ // Chat's own module, else the one the app gave Genesis (so it's passed once).
410
+ const keyboardModule = modules.keyboardAvoidingView ?? (genesis as { keyboardAvoidingView?: KeyboardAvoidingLike }).keyboardAvoidingView;
411
+ const KeyboardAvoiding = (keyboardModule ?? KeyboardAvoidingView) as ComponentType<Record<string, unknown>>;
474
412
  const offset = keyboardVerticalOffset ?? measuredTop;
475
- const keyboardProps = modules.keyboardAvoidingView
413
+ const keyboardProps = keyboardModule
476
414
  ? { behavior: "translate-with-padding", keyboardVerticalOffset: offset }
477
415
  : { behavior: Platform.OS === "ios" ? "padding" : undefined, keyboardVerticalOffset: offset };
478
416
 
479
- const empty = !conv.isLoading && rows.length === 0;
480
417
  return (
481
418
  <ChatPeopleScope userIds={peopleIds}>
482
419
  <SafeAreaView ref={rootRef as never} onLayout={measureTop} testID={testID} edges={["left", "right", "bottom"]} style={{ flex: 1, backgroundColor: colors.groupedBackground }}>
@@ -486,64 +423,26 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
486
423
  ) : null}
487
424
  <ChatAwayLine text={awayLine} testID={`${testID}-away`} />
488
425
  <View style={{ flex: 1 }}>
489
- {conv.isLoading ? (
490
- <LoadingThread testID={`${testID}-loading`} />
491
- ) : empty ? (
492
- <View style={{ flex: 1, justifyContent: "center" }}>
493
- <NativeEmptyState variant="first-run" title={copy.threadEmptyTitle} body={currentTopic?.closedAt ? copy.topicClosedNotice : copy.threadEmptyBody} testID={`${testID}-empty`} />
494
- </View>
495
- ) : (
496
- <List
497
- ref={listRef}
498
- testID={`${testID}-list`}
499
- data={rows}
500
- renderItem={renderItem}
501
- keyExtractor={(row) => row.key}
502
- getItemType={(row) => (row.type === "message" ? (row.mine ? "mine" : "theirs") : row.type)}
503
- onStartReached={() => {
504
- // Not while going to a message: its pages are loading, and new rows would move it.
505
- if (placed.current && !jumping && conv.hasEarlier && !conv.loadingEarlier) void conv.loadEarlier();
506
- }}
507
- onStartReachedThreshold={0.5}
508
- keyboardShouldPersistTaps="handled"
509
- keyboardDismissMode="interactive"
510
- contentContainerStyle={{ paddingVertical: 8 }}
511
- maintainVisibleContentPosition={mode.maintainVisibleContentPosition}
512
- extraData={highlightedId}
513
- onScrollToIndexFailed={({ index, averageItemLength }) => {
514
- // FlatList hasn't measured that far up yet: get near it, then try again (three times at most).
515
- listRef.current?.scrollToOffset?.({ offset: Math.max(0, index * averageItemLength - 200), animated: false });
516
- const target = jumpingTo.current;
517
- if (!target || target.tries >= 3) return;
518
- target.tries += 1;
519
- if (retryTimer.current) clearTimeout(retryTimer.current);
520
- retryTimer.current = setTimeout(() => {
521
- const at = rowIndexOf(rowsNow.current, target.id);
522
- if (at >= 0) listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
523
- }, 250);
524
- }}
525
- {...(mode.followsByHand
526
- ? {
527
- scrollEventThrottle: 32,
528
- onScroll: (e: NativeSyntheticEvent<NativeScrollEvent>) => {
529
- atBottom.current = nearBottom(e.nativeEvent);
530
- },
531
- onContentSizeChange: () => {
532
- if (atBottom.current) toBottom(false);
533
- },
534
- onLayout: () => {
535
- if (atBottom.current) toBottom(false);
536
- },
537
- }
538
- : {})}
539
- ListHeaderComponent={
540
- conv.hasEarlier ? (
541
- <EarlierAnchor loading={conv.loadingEarlier} label={copy.loadEarlier} onPress={() => void conv.loadEarlier()} testID={`${testID}-earlier`} />
542
- ) : null
543
- }
544
- ListFooterComponent={activity ? <ActivityLine text={activity} testID={`${testID}-activity`} /> : null}
545
- />
546
- )}
426
+ <NativeThreadList<ThreadRow>
427
+ ref={listRef}
428
+ testID={`${testID}-list`}
429
+ data={rows}
430
+ keyExtractor={threadRowKey}
431
+ jumpId={threadRowMessageId}
432
+ getItemType={threadRowType}
433
+ renderItem={renderItem}
434
+ loading={conv.isLoading}
435
+ hasEarlier={conv.hasEarlier}
436
+ onLoadEarlier={() => void conv.loadEarlier()}
437
+ loadingEarlier={conv.loadingEarlier}
438
+ earlierLabel={copy.loadEarlier}
439
+ jumpTo={jumpMessageId}
440
+ onLoadUntil={onLoadUntil}
441
+ jumpAnnouncement={jumpAnnouncement}
442
+ onJumpFailed={onJumpFailed}
443
+ footer={activity ? <ActivityLine text={activity} testID={`${testID}-activity`} /> : null}
444
+ empty={<NativeEmptyState variant="first-run" title={copy.threadEmptyTitle} body={currentTopic?.closedAt ? copy.topicClosedNotice : copy.threadEmptyBody} testID={`${testID}-empty`} />}
445
+ />
547
446
  </View>
548
447
  {scheduling && !threadRootId ? <ChatScheduledBar conversationId={conversationId} testID={`${testID}-scheduled`} /> : null}
549
448
  <VideoUploadTray conversationId={conversationId} userId={userId} testID={`${testID}-video-uploads`} />
@@ -560,9 +459,7 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
560
459
  role={conv.role}
561
460
  onSend={({ input, files }) => {
562
461
  void conv.send(input, files).catch(fail);
563
- // What you send is what you look at next, wherever the list was.
564
- atBottom.current = true;
565
- toBottom(true);
462
+ toNewest();
566
463
  }}
567
464
  signalTyping={conv.signalTyping}
568
465
  signalRecording={conv.signalRecording}
@@ -631,34 +528,7 @@ function ActivityLine({ text, testID }: { text: string; testID: string }) {
631
528
  );
632
529
  }
633
530
 
634
- function EarlierAnchor({ loading, label, onPress, testID }: { loading: boolean; label: string; onPress: () => void; testID: string }) {
635
- const colors = useThemeRoles();
636
- return (
637
- <View style={{ alignItems: "center", paddingVertical: 12 }}>
638
- {loading ? (
639
- <View testID={`${testID}-loading`} style={{ gap: 8, alignItems: "center" }}>
640
- <NativeSkeleton width={180} height={14} />
641
- <NativeSkeleton width={120} height={14} />
642
- </View>
643
- ) : (
644
- <Pressable testID={testID} accessibilityRole="button" accessibilityLabel={label} onPress={onPress} style={{ minHeight: 44, justifyContent: "center", paddingHorizontal: 16 }}>
645
- <NativeText preset="label" style={{ color: colors.tint }}>
646
- {label}
647
- </NativeText>
648
- </Pressable>
649
- )}
650
- </View>
651
- );
652
- }
653
-
654
- function LoadingThread({ testID }: { testID: string }) {
655
- return (
656
- <View testID={testID} style={{ flex: 1, justifyContent: "flex-end", padding: 16, gap: 10 }}>
657
- <NativeSkeleton width={200} height={36} className="rounded-2xl" />
658
- <View style={{ alignItems: "flex-end" }}>
659
- <NativeSkeleton width={160} height={36} className="rounded-2xl" />
660
- </View>
661
- <NativeSkeleton width={240} height={36} className="rounded-2xl" />
662
- </View>
663
- );
664
- }
531
+ const threadRowKey = (row: ThreadRow) => row.key;
532
+ /** A message row is gone to by the server's id; a day heading, the unread line and a message still sending can't be. */
533
+ const threadRowMessageId = (row: ThreadRow) => (row.type === "message" && row.item.type === "message" ? row.item.message.id : null);
534
+ const threadRowType = (row: ThreadRow) => (row.type === "message" ? (row.mine ? "mine" : "theirs") : row.type);
@@ -12,7 +12,10 @@ export interface JumpTarget {
12
12
  seq?: number;
13
13
  }
14
14
 
15
- /** The row a message is drawn in, or -1. */
15
+ /**
16
+ * The row a message is drawn in, or -1.
17
+ * @deprecated NativeThreadList finds a row by `jumpId`. Removed in a later minor, with `useJumpToMessage`.
18
+ */
16
19
  export function rowIndexOf(rows: readonly ThreadRow[], messageId: string): number {
17
20
  return rows.findIndex((r) => r.type === "message" && r.item.type === "message" && r.item.message.id === messageId);
18
21
  }
@@ -38,6 +41,9 @@ export interface UseJumpOptions {
38
41
 
39
42
  type Pending = JumpTarget & { phase: "new" | "loading" | "loaded" };
40
43
 
44
+ /**
45
+ * @deprecated Use genesis-ui-native's `NativeThreadList` (`jumpTo`, `jumpId`, `onLoadUntil`), or `useThreadJump` for a list of your own. ChatThreadScreen is on NativeThreadList; this copy is removed in a later minor.
46
+ */
41
47
  export function useJumpToMessage({ target, rows, loading, has, loadUntil, scrollTo, onStart, onLanded, onGone, onError }: UseJumpOptions) {
42
48
  const [pending, setPending] = useState<Pending | null>(target ? { ...target, phase: "new" } : null);
43
49
  const [highlightedId, setHighlightedId] = useState<string | null>(null);
@@ -33,6 +33,7 @@ import type {
33
33
  ScheduleInput,
34
34
  ScheduledMessage,
35
35
  SendInput,
36
+ StartConversationOptions,
36
37
  TopicInput,
37
38
  } from "../core/types";
38
39
 
@@ -668,7 +669,7 @@ export function useStartConversation() {
668
669
  const { client } = useChat();
669
670
  const queryClient = useQueryClient();
670
671
  return useCallback(
671
- async (kind: string, memberIds: string[], opts?: { title?: string; subjectType?: string; subjectId?: string }) => {
672
+ async (kind: string, memberIds: string[], opts?: StartConversationOptions) => {
672
673
  const id = await client.startConversation(kind, memberIds, opts);
673
674
  void queryClient.invalidateQueries({ queryKey: ["genesis-chat", "inbox"] });
674
675
  return id;
@@ -5,18 +5,9 @@
5
5
  * form, a lesson) through the `attachment` slot, a generic card by default.
6
6
  * Pending uploads draw from their local previews with a spinner.
7
7
  */
8
- import { useCallback, useState, type ComponentType, type KeyboardEvent } from "react";
9
- import { ChevronLeft, ChevronRight, Download, FileText, Link2, Paperclip } from "lucide-react";
10
- import {
11
- Button,
12
- Dialog,
13
- DialogContent,
14
- DialogDescription,
15
- DialogTitle,
16
- Spinner,
17
- VisuallyHidden,
18
- cn,
19
- } from "@marktiderman/genesis-ui";
8
+ import { useMemo, useState, type ComponentType } from "react";
9
+ import { Download, FileText, Link2, Paperclip } from "lucide-react";
10
+ import { Button, Lightbox as GenesisLightbox, Spinner, cn, type GalleryItem } from "@marktiderman/genesis-ui";
20
11
  import type { ChatAttachment, ChatMessage } from "../core/types";
21
12
  import type { ChatAttachmentKind, ChatCardContext } from "../react/index";
22
13
  import { ChatAttachmentCard, type ChatAttachmentCardProps } from "./cards";
@@ -156,7 +147,7 @@ export function ImageGrid({ images, className }: ImageGridProps) {
156
147
  );
157
148
  })}
158
149
  </div>
159
- <Lightbox images={images} index={open} onIndexChange={setOpen} />
150
+ <ChatLightbox images={images} index={open} onIndexChange={setOpen} />
160
151
  </>
161
152
  );
162
153
  }
@@ -168,53 +159,46 @@ export interface LightboxProps {
168
159
  onIndexChange: (index: number | null) => void;
169
160
  }
170
161
 
171
- /** A photo full size, with the previous and next ones on the arrow keys. */
172
- export function Lightbox({ images, index, onIndexChange }: LightboxProps) {
173
- const img = index === null ? null : images[index];
174
- const go = useCallback(
175
- (delta: number) => {
176
- if (index === null || images.length < 2) return;
177
- onIndexChange((index + delta + images.length) % images.length);
178
- },
179
- [images.length, index, onIndexChange],
162
+ /** A message's photos full size: genesis-ui's `Lightbox` (arrow keys, a counter, focus kept on the arrows), fed chat's attachments. */
163
+ function ChatLightbox({ images, index, onIndexChange }: LightboxProps) {
164
+ // Only photos with a link open: one still uploading has nothing to show full size. `at` maps
165
+ // between the viewer's positions and `images`' indexes.
166
+ const at = useMemo(() => images.flatMap((img, i) => (img.url ? [i] : [])), [images]);
167
+ const items = useMemo<GalleryItem[]>(
168
+ () =>
169
+ at.map((i) => {
170
+ const img = images[i]!;
171
+ return {
172
+ id: img.key,
173
+ src: img.url!,
174
+ alt: img.name ?? "Photo",
175
+ ...(img.width ? { width: img.width } : {}),
176
+ ...(img.height ? { height: img.height } : {}),
177
+ };
178
+ }),
179
+ [images, at],
180
180
  );
181
- const onKey = (e: KeyboardEvent) => {
182
- if (e.key === "ArrowRight") {
183
- e.preventDefault();
184
- go(1);
185
- } else if (e.key === "ArrowLeft") {
186
- e.preventDefault();
187
- go(-1);
188
- }
189
- };
181
+ const shown = index === null ? -1 : at.indexOf(index);
190
182
  return (
191
- <Dialog open={img != null} onOpenChange={(o) => !o && onIndexChange(null)}>
192
- <DialogContent className="max-w-[min(64rem,95vw)] border-0 bg-background p-2" onKeyDown={onKey} data-testid="genesis-chat-lightbox">
193
- <VisuallyHidden>
194
- <DialogTitle>{img?.name ?? "Photo"}</DialogTitle>
195
- <DialogDescription>
196
- Photo {index === null ? 0 : index + 1} of {images.length}. Use the arrow keys for the others.
197
- </DialogDescription>
198
- </VisuallyHidden>
199
- {img?.url ? <img src={img.url} alt={img.name ?? "Photo"} className="mx-auto max-h-[80vh] w-auto rounded-md object-contain" /> : null}
200
- {images.length > 1 ? (
201
- <div className="flex items-center justify-between gap-2">
202
- <Button type="button" variant="ghost" size="icon" onClick={() => go(-1)} aria-label="Previous photo">
203
- <ChevronLeft />
204
- </Button>
205
- <span className="text-sm tabular-nums text-muted-foreground">
206
- {(index ?? 0) + 1} / {images.length}
207
- </span>
208
- <Button type="button" variant="ghost" size="icon" onClick={() => go(1)} aria-label="Next photo">
209
- <ChevronRight />
210
- </Button>
211
- </div>
212
- ) : null}
213
- </DialogContent>
214
- </Dialog>
183
+ <GenesisLightbox
184
+ open={shown !== -1}
185
+ onOpenChange={(open) => !open && onIndexChange(null)}
186
+ items={items}
187
+ index={Math.max(0, shown)}
188
+ onIndexChange={(i) => onIndexChange(at[i] ?? null)}
189
+ labels={{ previous: "Previous photo", next: "Next photo", photo: (n, count) => `Photo ${n} of ${count}` }}
190
+ className="genesis-chat-lightbox"
191
+ />
215
192
  );
216
193
  }
217
194
 
195
+ /**
196
+ * @deprecated Chat's photo grid opens its photos itself. To show photos full size elsewhere, render
197
+ * `Lightbox` from `@marktiderman/genesis-ui` with `GalleryItem`s. This adapter is removed in a
198
+ * later minor.
199
+ */
200
+ export const Lightbox = ChatLightbox;
201
+
218
202
  /** A video: a hosted one (Mux) streams once ready and says "Processing…" until then; a file plays from storage. */
219
203
  export function VideoAttachment({ view }: { view: AttachmentView }) {
220
204
  const a = view.attachment;
@@ -6,6 +6,11 @@
6
6
  * internal notes for observers, voice notes recorded in place, videos from the
7
7
  * camera, emoji, and scheduled send (the arrow beside Send). Where you may not
8
8
  * post it says why instead; when who you are couldn't load, it offers a retry.
9
+ *
10
+ * Moving onto genesis-ui (feature `inbox-thread`): its scrolling, list and composer are the same
11
+ * behaviour as genesis-ui's `ComposerBar`, which were promoted from here. This screen keeps its data
12
+ * wiring (the chat client, realtime, read state) and moves its rendering onto `ComposerBar` with chat's
13
+ * builder; until then fix behaviour in both places.
9
14
  */
10
15
  import {
11
16
  useCallback,