@marktiderman/genesis-chat 0.8.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-chat",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -93,7 +93,7 @@
93
93
  "@marktiderman/genesis-ai": ">=0.1.0 <1.0.0",
94
94
  "@marktiderman/genesis-core": ">=1.17.0 <3.0.0",
95
95
  "@marktiderman/genesis-ui": ">=2.31.0 <3.0.0",
96
- "@marktiderman/genesis-ui-native": ">=3.6.0 <4.0.0",
96
+ "@marktiderman/genesis-ui-native": ">=3.7.0 <4.0.0",
97
97
  "@supabase/supabase-js": "^2.118.0",
98
98
  "@tanstack/react-query": "^5.0.0",
99
99
  "hls.js": "^1.5.0",
@@ -175,10 +175,10 @@
175
175
  "devDependencies": {
176
176
  "@ai-sdk/anthropic": "4.0.88",
177
177
  "@marktiderman/genesis-ai": "^0.2.0",
178
- "@marktiderman/genesis-core": "^2.11.0",
178
+ "@marktiderman/genesis-core": "^2.12.0",
179
179
  "@marktiderman/genesis-notifications": "^0.4.2",
180
- "@marktiderman/genesis-ui": "^2.31.0",
181
- "@marktiderman/genesis-ui-native": "^3.6.0",
180
+ "@marktiderman/genesis-ui": "^2.31.1",
181
+ "@marktiderman/genesis-ui-native": "^3.7.0",
182
182
  "@supabase/supabase-js": "^2.118.0",
183
183
  "@tanstack/react-query": "^5.105.0",
184
184
  "@testing-library/react": "^16.3.2",
@@ -1,8 +1,9 @@
1
1
  // @vitest-environment happy-dom
2
2
  // @feat:chat
3
3
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
4
- import { act, cleanup, render, waitFor } from "@testing-library/react";
5
- import type { ReactNode } from "react";
4
+ import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
5
+ import { forwardRef, useImperativeHandle, type ReactNode } from "react";
6
+ import { AccessibilityInfo } from "react-native";
6
7
  import { afterEach, describe, expect, it, vi } from "vitest";
7
8
  import { GenesisModulesProvider, NativeToastProvider } from "@marktiderman/genesis-ui-native/components";
8
9
  import type { ChatClient } from "../../core/client";
@@ -100,6 +101,43 @@ describe("ChatThreadScreen's list", () => {
100
101
  });
101
102
  });
102
103
 
104
+ /** A list that also takes the thread's scroll calls through its ref. */
105
+ function scrollingList() {
106
+ const seen: Record<string, unknown>[] = [];
107
+ const scrollToIndex = vi.fn();
108
+ const List = forwardRef<unknown, Record<string, unknown>>(function List(props, ref) {
109
+ seen.push(props);
110
+ useImperativeHandle(ref, () => ({ scrollToIndex, scrollToEnd: vi.fn(), scrollToOffset: vi.fn() }));
111
+ return null;
112
+ });
113
+ return { List, scrollToIndex, last: () => seen.at(-1)! };
114
+ }
115
+
116
+ describe("ChatThreadScreen's jump to a message", () => {
117
+ const messages = [msg(1, SAM, "2026-10-24T10:00:00Z"), msg(2, ME, "2026-10-24T10:01:00Z"), msg(3, SAM, "2026-10-24T10:02:00Z")];
118
+
119
+ it("goes to a message by its server id (rows are keyed by client id), centred, and says whose it is", async () => {
120
+ const announce = vi.fn();
121
+ (AccessibilityInfo as { announceForAccessibility?: unknown }).announceForAccessibility = announce;
122
+ const list = scrollingList();
123
+ render(wrap(fakeClient(messages, 3), list.List, <ChatThreadScreen conversationId={CONV} jumpTo={{ messageId: "m2", seq: 2 }} />));
124
+ await waitFor(() => expect(list.scrollToIndex).toHaveBeenCalled());
125
+ const { index, viewPosition } = list.scrollToIndex.mock.calls.at(-1)![0] as { index: number; viewPosition: number };
126
+ const row = (list.last().data as ThreadRow[])[index]!;
127
+ expect(row.key).toBe("c:c2");
128
+ expect(row.type === "message" && row.item.type === "message" ? row.item.message.id : null).toBe("m2");
129
+ expect(viewPosition).toBe(0.5);
130
+ expect(announce).toHaveBeenCalledWith("Message from You: body 2");
131
+ });
132
+
133
+ it("says so when the message isn't there and there's no seq to load back to", async () => {
134
+ const list = scrollingList();
135
+ render(wrap(fakeClient(messages, 3), list.List, <ChatThreadScreen conversationId={CONV} jumpTo={{ messageId: "m9" }} />));
136
+ expect(await screen.findByText("That message isn't here any more", {}, { timeout: 2000 })).toBeTruthy();
137
+ expect(list.scrollToIndex).not.toHaveBeenCalled();
138
+ });
139
+ });
140
+
103
141
  describe("threadListMode", () => {
104
142
  it("follows new rows by hand only on FlatList, which keeps its place for earlier rows", () => {
105
143
  expect(threadListMode(true, false)).toMatchObject({ followsByHand: false });
@@ -278,7 +278,7 @@ function MessageBubbleImpl(props: MessageBubbleProps) {
278
278
  testID={testID}
279
279
  accessibilityElementsHidden={invisible || undefined}
280
280
  importantForAccessibility={invisible ? "no-hide-descendants" : undefined}
281
- style={{ paddingHorizontal: 8, paddingTop: row.groupStart ? 8 : 2, backgroundColor: props.highlighted ? colors.fill : undefined, display: invisible ? "none" : undefined }}
281
+ style={{ paddingTop: row.groupStart ? 8 : 2, borderRadius: 12, backgroundColor: props.highlighted ? colors.fill : undefined, display: invisible ? "none" : undefined }}
282
282
  >
283
283
  {row.showName && sender?.name ? (
284
284
  <NativeText preset="caption" style={{ marginLeft: group ? 48 : 12, marginBottom: 2, color: colors.secondaryLabel }}>
@@ -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";
@@ -102,34 +100,9 @@ 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
103
  /**
131
104
  * Points from the bottom that still count as "at the bottom" (FlatList, which follows by hand).
132
- * @deprecated Promoted to genesis-ui-native as `THREAD_AT_BOTTOM_POINTS`. ChatThreadScreen moves onto NativeThreadList with its builder (feature `inbox-thread`); this copy is removed then.
105
+ * @deprecated Use genesis-ui-native's `THREAD_AT_BOTTOM_POINTS`. ChatThreadScreen is on NativeThreadList; this copy is removed in a later minor.
133
106
  */
134
107
  export const AT_BOTTOM_POINTS = 120;
135
108
 
@@ -139,7 +112,7 @@ export const AT_BOTTOM_POINTS = 120;
139
112
  * a screen of it, keeps the first visible row in place when earlier ones load
140
113
  * at the top). FlatList: keeps its place when earlier rows load at the top;
141
114
  * the screen follows new rows itself (`followsByHand`).
142
- * @deprecated Promoted to genesis-ui-native as `threadListMode` (which anchors FlatList past the header, `minIndexForVisible: 1`). ChatThreadScreen moves onto NativeThreadList with its builder (feature `inbox-thread`); this copy is removed then.
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.
143
116
  */
144
117
  export function threadListMode(flash: boolean, reducedMotion: boolean): { followsByHand: boolean; maintainVisibleContentPosition: Record<string, unknown> } {
145
118
  if (flash) {
@@ -153,7 +126,7 @@ export function threadListMode(flash: boolean, reducedMotion: boolean): { follow
153
126
 
154
127
  /**
155
128
  * Whether a scroll position is at (or near) the bottom of its content.
156
- * @deprecated Promoted to genesis-ui-native as `threadNearBottom`. ChatThreadScreen moves onto NativeThreadList with its builder (feature `inbox-thread`); this copy is removed then.
129
+ * @deprecated Use genesis-ui-native's `threadNearBottom`. ChatThreadScreen is on NativeThreadList; this copy is removed in a later minor.
157
130
  */
158
131
  export function nearBottom(m: { contentOffset: { y: number }; contentSize: { height: number }; layoutMeasurement: { height: number } }, slack = AT_BOTTOM_POINTS): boolean {
159
132
  return m.contentOffset.y + m.layoutMeasurement.height >= m.contentSize.height - slack;
@@ -190,30 +163,9 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
190
163
  const colors = useThemeRoles();
191
164
  const reducedMotion = useReducedMotion();
192
165
  const genesis = useGenesisModules();
193
- const List = (genesis.list ?? FlatList) as unknown as ComponentType<ChatListProps>;
194
- const mode = threadListMode(Boolean(genesis.list), reducedMotion);
195
- const listRef = useRef<{
196
- scrollToEnd?: (o?: { animated?: boolean }) => void;
197
- scrollToIndex?: (o: { index: number; animated?: boolean; viewPosition?: number }) => void;
198
- scrollToOffset?: (o: { offset: number; animated?: boolean }) => void;
199
- } | null>(null);
200
- // FlatList follows by hand: at the bottom (or not yet scrolled), new rows and a shorter list keep it there.
201
- const atBottom = useRef(true);
202
- // FlatList opens at the top and is moved to the bottom a frame later: until it has been, the top
203
- // isn't "reached" (it would load an earlier page on every open).
204
- const placed = useRef(!mode.followsByHand);
205
- const toBottom = useCallback(
206
- (animated: boolean) => {
207
- const go = (a: boolean) => listRef.current?.scrollToEnd?.({ animated: a && !reducedMotion });
208
- requestAnimationFrame(() => {
209
- go(animated);
210
- placed.current = true;
211
- });
212
- // Once more after the new row has its size (FlashList measures it after the first pass).
213
- if (animated) setTimeout(() => go(true), 180);
214
- },
215
- [reducedMotion],
216
- );
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 }), []);
217
169
  const composer = useChatComposer(conversationId, threadRootId, userId);
218
170
  const { setReply } = composer;
219
171
  const [actionsFor, setActionsFor] = useState<ChatMessage | null>(null);
@@ -344,53 +296,31 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
344
296
  );
345
297
  const observer = conv.role === "observer";
346
298
  const { loadUntil } = conv;
347
- // The message being gone to, for FlatList's retry once it has measured that far (by id: rows may have moved).
348
- const jumpingTo = useRef<{ id: string; tries: number } | null>(null);
349
- const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
350
- useEffect(() => () => {
351
- if (retryTimer.current) clearTimeout(retryTimer.current);
352
- }, []);
353
- const rowsNow = useRef(rows);
354
- rowsNow.current = rows;
355
- const { highlightedId, jumping } = useJumpToMessage({
356
- target: jumpTo,
357
- rows,
358
- loading: conv.isLoading,
359
- has: useCallback((id: string) => byId.has(id), [byId]),
360
- loadUntil,
361
- scrollTo: (index, id) => {
362
- jumpingTo.current = { id, tries: 0 };
363
- const scroll = (at: number) => listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
364
- requestAnimationFrame(() => scroll(index));
365
- // Once more after the first layout: with the message already loaded (the thread was opened
366
- // before), the jump runs on the first frame, and FlashList's start-at-the-bottom placement,
367
- // which comes after it, would win and leave the thread at the bottom.
368
- if (retryTimer.current) clearTimeout(retryTimer.current);
369
- retryTimer.current = setTimeout(() => {
370
- const at = rowIndexOf(rowsNow.current, id);
371
- if (at >= 0) scroll(at);
372
- }, 250);
373
- },
374
- onStart: () => {
375
- atBottom.current = false;
376
- placed.current = true;
377
- },
378
- onLanded: (id) => {
379
- const m = byId.get(id);
380
- 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
+ });
381
309
  },
382
- onGone: () => {
383
- toast.show({ title: copy.messageGone });
384
- // Back to where the thread opens: the newest messages.
385
- atBottom.current = true;
386
- 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)) }) : "";
387
316
  },
388
- onError: fail,
389
- });
317
+ [copy.jumpedTo, nameOf, attachmentKinds],
318
+ );
319
+ const onJumpFailed = useCallback(() => toast.show({ title: copy.messageGone }), [toast, copy.messageGone]);
390
320
  const reattachable = useCallback((files: readonly PendingFile[]) => files.every((f) => !f.lost || f.kind === "image" || f.kind === "video"), []);
391
321
 
392
322
  const renderItem = useCallback(
393
- ({ item: row }: { item: ThreadRow }) => {
323
+ (row: ThreadRow, { highlighted }: ThreadRowInfo) => {
394
324
  if (row.type === "day") return <DaySeparator label={row.label} testID={`${testID}-day-${row.key}`} />;
395
325
  if (row.type === "unread") return <UnreadDivider label={copy.newMessages} testID={`${testID}-unread`} />;
396
326
  const m = row.item.type === "message" ? row.item.message : null;
@@ -412,7 +342,7 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
412
342
  onToggleReaction={allowed ? react : undefined}
413
343
  onOpenImage={onOpenImage}
414
344
  observer={observer}
415
- highlighted={Boolean(m && m.id === highlightedId)}
345
+ highlighted={highlighted}
416
346
  linkPreview={m ? previewToShow(previews[m.id]) : null}
417
347
  linkPreviewImages={linkPreviewImages}
418
348
  attachmentKinds={attachmentKinds}
@@ -423,7 +353,7 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
423
353
  />
424
354
  );
425
355
  },
426
- [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],
427
357
  );
428
358
 
429
359
  // ---- Video messages ----
@@ -452,10 +382,9 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
452
382
  (video: RecordedVideo) => {
453
383
  videoUploads.start({ conversationId, userId, video, extra: { replyToId: replyNow, threadRootId }, send: outbox.send, videoUpload, prepared: takePrepared(), openFile: modules.openFile });
454
384
  if (replyNow) setReply(null);
455
- atBottom.current = true;
456
- toBottom(true);
385
+ toNewest();
457
386
  },
458
- [conversationId, userId, replyNow, threadRootId, outbox, videoUpload, takePrepared, modules.openFile, setReply, toBottom],
387
+ [conversationId, userId, replyNow, threadRootId, outbox, videoUpload, takePrepared, modules.openFile, setReply, toNewest],
459
388
  );
460
389
 
461
390
  const activity = activityLine(conv.activity, (id) => nameOf(id));
@@ -485,7 +414,6 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
485
414
  ? { behavior: "translate-with-padding", keyboardVerticalOffset: offset }
486
415
  : { behavior: Platform.OS === "ios" ? "padding" : undefined, keyboardVerticalOffset: offset };
487
416
 
488
- const empty = !conv.isLoading && rows.length === 0;
489
417
  return (
490
418
  <ChatPeopleScope userIds={peopleIds}>
491
419
  <SafeAreaView ref={rootRef as never} onLayout={measureTop} testID={testID} edges={["left", "right", "bottom"]} style={{ flex: 1, backgroundColor: colors.groupedBackground }}>
@@ -495,64 +423,26 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
495
423
  ) : null}
496
424
  <ChatAwayLine text={awayLine} testID={`${testID}-away`} />
497
425
  <View style={{ flex: 1 }}>
498
- {conv.isLoading ? (
499
- <LoadingThread testID={`${testID}-loading`} />
500
- ) : empty ? (
501
- <View style={{ flex: 1, justifyContent: "center" }}>
502
- <NativeEmptyState variant="first-run" title={copy.threadEmptyTitle} body={currentTopic?.closedAt ? copy.topicClosedNotice : copy.threadEmptyBody} testID={`${testID}-empty`} />
503
- </View>
504
- ) : (
505
- <List
506
- ref={listRef}
507
- testID={`${testID}-list`}
508
- data={rows}
509
- renderItem={renderItem}
510
- keyExtractor={(row) => row.key}
511
- getItemType={(row) => (row.type === "message" ? (row.mine ? "mine" : "theirs") : row.type)}
512
- onStartReached={() => {
513
- // Not while going to a message: its pages are loading, and new rows would move it.
514
- if (placed.current && !jumping && conv.hasEarlier && !conv.loadingEarlier) void conv.loadEarlier();
515
- }}
516
- onStartReachedThreshold={0.5}
517
- keyboardShouldPersistTaps="handled"
518
- keyboardDismissMode="interactive"
519
- contentContainerStyle={{ paddingVertical: 8 }}
520
- maintainVisibleContentPosition={mode.maintainVisibleContentPosition}
521
- extraData={highlightedId}
522
- onScrollToIndexFailed={({ index, averageItemLength }) => {
523
- // FlatList hasn't measured that far up yet: get near it, then try again (three times at most).
524
- listRef.current?.scrollToOffset?.({ offset: Math.max(0, index * averageItemLength - 200), animated: false });
525
- const target = jumpingTo.current;
526
- if (!target || target.tries >= 3) return;
527
- target.tries += 1;
528
- if (retryTimer.current) clearTimeout(retryTimer.current);
529
- retryTimer.current = setTimeout(() => {
530
- const at = rowIndexOf(rowsNow.current, target.id);
531
- if (at >= 0) listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
532
- }, 250);
533
- }}
534
- {...(mode.followsByHand
535
- ? {
536
- scrollEventThrottle: 32,
537
- onScroll: (e: NativeSyntheticEvent<NativeScrollEvent>) => {
538
- atBottom.current = nearBottom(e.nativeEvent);
539
- },
540
- onContentSizeChange: () => {
541
- if (atBottom.current) toBottom(false);
542
- },
543
- onLayout: () => {
544
- if (atBottom.current) toBottom(false);
545
- },
546
- }
547
- : {})}
548
- ListHeaderComponent={
549
- conv.hasEarlier ? (
550
- <EarlierAnchor loading={conv.loadingEarlier} label={copy.loadEarlier} onPress={() => void conv.loadEarlier()} testID={`${testID}-earlier`} />
551
- ) : null
552
- }
553
- ListFooterComponent={activity ? <ActivityLine text={activity} testID={`${testID}-activity`} /> : null}
554
- />
555
- )}
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
+ />
556
446
  </View>
557
447
  {scheduling && !threadRootId ? <ChatScheduledBar conversationId={conversationId} testID={`${testID}-scheduled`} /> : null}
558
448
  <VideoUploadTray conversationId={conversationId} userId={userId} testID={`${testID}-video-uploads`} />
@@ -569,9 +459,7 @@ export function ChatThreadScreen(props: ChatThreadScreenProps) {
569
459
  role={conv.role}
570
460
  onSend={({ input, files }) => {
571
461
  void conv.send(input, files).catch(fail);
572
- // What you send is what you look at next, wherever the list was.
573
- atBottom.current = true;
574
- toBottom(true);
462
+ toNewest();
575
463
  }}
576
464
  signalTyping={conv.signalTyping}
577
465
  signalRecording={conv.signalRecording}
@@ -640,34 +528,7 @@ function ActivityLine({ text, testID }: { text: string; testID: string }) {
640
528
  );
641
529
  }
642
530
 
643
- function EarlierAnchor({ loading, label, onPress, testID }: { loading: boolean; label: string; onPress: () => void; testID: string }) {
644
- const colors = useThemeRoles();
645
- return (
646
- <View style={{ alignItems: "center", paddingVertical: 12 }}>
647
- {loading ? (
648
- <View testID={`${testID}-loading`} style={{ gap: 8, alignItems: "center" }}>
649
- <NativeSkeleton width={180} height={14} />
650
- <NativeSkeleton width={120} height={14} />
651
- </View>
652
- ) : (
653
- <Pressable testID={testID} accessibilityRole="button" accessibilityLabel={label} onPress={onPress} style={{ minHeight: 44, justifyContent: "center", paddingHorizontal: 16 }}>
654
- <NativeText preset="label" style={{ color: colors.tint }}>
655
- {label}
656
- </NativeText>
657
- </Pressable>
658
- )}
659
- </View>
660
- );
661
- }
662
-
663
- function LoadingThread({ testID }: { testID: string }) {
664
- return (
665
- <View testID={testID} style={{ flex: 1, justifyContent: "flex-end", padding: 16, gap: 10 }}>
666
- <NativeSkeleton width={200} height={36} className="rounded-2xl" />
667
- <View style={{ alignItems: "flex-end" }}>
668
- <NativeSkeleton width={160} height={36} className="rounded-2xl" />
669
- </View>
670
- <NativeSkeleton width={240} height={36} className="rounded-2xl" />
671
- </View>
672
- );
673
- }
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
  }
@@ -39,7 +42,7 @@ export interface UseJumpOptions {
39
42
  type Pending = JumpTarget & { phase: "new" | "loading" | "loaded" };
40
43
 
41
44
  /**
42
- * @deprecated Promoted to genesis-ui-native as `useThreadJump`. ChatThreadScreen moves onto NativeThreadList with its builder (feature `inbox-thread`); this copy is removed then.
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.
43
46
  */
44
47
  export function useJumpToMessage({ target, rows, loading, has, loadUntil, scrollTo, onStart, onLanded, onGone, onError }: UseJumpOptions) {
45
48
  const [pending, setPending] = useState<Pending | null>(target ? { ...target, phase: "new" } : null);