@marktiderman/genesis-chat 0.11.4 → 0.13.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 (72) hide show
  1. package/README.md +162 -4
  2. package/dist/{chunk-ZQFREERR.js → chunk-3UNYTK62.js} +3 -3
  3. package/dist/{chunk-ZQFREERR.js.map → chunk-3UNYTK62.js.map} +1 -1
  4. package/dist/{chunk-5XYDVUPS.js → chunk-GEEJMKQF.js} +29 -4
  5. package/dist/chunk-GEEJMKQF.js.map +1 -0
  6. package/dist/{chunk-D4RPOYB7.js → chunk-H4BRVJJ7.js} +193 -30
  7. package/dist/chunk-H4BRVJJ7.js.map +1 -0
  8. package/dist/{chunk-O2QSBRSH.js → chunk-SEMN3S6Q.js} +3 -3
  9. package/dist/{chunk-O2QSBRSH.js.map → chunk-SEMN3S6Q.js.map} +1 -1
  10. package/dist/{client-DP7rhJ1U.d.ts → client-DXWyDJ2u.d.ts} +29 -0
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +3 -3
  13. package/dist/native.d.ts +355 -145
  14. package/dist/native.js +701 -217
  15. package/dist/native.js.map +1 -1
  16. package/dist/{outbox-C4LnqpKT.d.ts → outbox-Ctngv6Yz.d.ts} +1 -1
  17. package/dist/push.d.ts +2 -2
  18. package/dist/react.d.ts +83 -6
  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-CSzdqNR_.d.ts → thread-mZsRiIGz.d.ts} +1 -1
  23. package/dist/web.d.ts +24 -7
  24. package/dist/web.js +140 -67
  25. package/dist/web.js.map +1 -1
  26. package/migrations/0006_genesis_chat_read_receipts.sql +110 -0
  27. package/migrations/0007_genesis_chat_unread_and_delete_for_me.sql +455 -0
  28. package/migrations/tests/0006_genesis_chat_read_receipts.test.sql +131 -0
  29. package/migrations/tests/0007_genesis_chat_unread_and_delete_for_me.test.sql +178 -0
  30. package/package.json +17 -9
  31. package/src/__tests__/inbox-row-actions.test.tsx +251 -0
  32. package/src/__tests__/unread-delete-for-me.test.ts +84 -0
  33. package/src/__tests__/web.test.tsx +5 -2
  34. package/src/core/client.ts +30 -1
  35. package/src/core/types.ts +7 -0
  36. package/src/native/__tests__/bubble-native-feel.test.tsx +153 -0
  37. package/src/native/__tests__/composer-attach-menu.test.tsx +47 -0
  38. package/src/native/__tests__/inbox-screen-actions.test.tsx +131 -0
  39. package/src/native/__tests__/inbox-screen.test.tsx +29 -1
  40. package/src/native/__tests__/media-cache-key.test.tsx +21 -0
  41. package/src/native/__tests__/organise-screens.test.tsx +2 -0
  42. package/src/native/__tests__/receipts.test.ts +95 -0
  43. package/src/native/__tests__/review-lows.test.tsx +80 -0
  44. package/src/native/__tests__/sheets-fit.test.tsx +45 -0
  45. package/src/native/__tests__/stable-hooks.test.tsx +68 -0
  46. package/src/native/__tests__/thread-layout.test.ts +2 -2
  47. package/src/native/__tests__/thread-screen-audit.test.tsx +248 -0
  48. package/src/native/__tests__/thread-screen.test.tsx +111 -0
  49. package/src/native/__tests__/thread-title.test.tsx +59 -0
  50. package/src/native/composer.tsx +61 -26
  51. package/src/native/copy.ts +47 -10
  52. package/src/native/emoji-picker.tsx +1 -1
  53. package/src/native/inbox-screen.tsx +52 -27
  54. package/src/native/index.ts +7 -2
  55. package/src/native/media.tsx +7 -1
  56. package/src/native/message-actions-sheet.tsx +1 -1
  57. package/src/native/message-bubble.tsx +171 -19
  58. package/src/native/modules.ts +3 -1
  59. package/src/native/receipts.ts +102 -0
  60. package/src/native/schedule-sheet.tsx +8 -3
  61. package/src/native/stack-options.ts +35 -3
  62. package/src/native/thread-screen.tsx +243 -17
  63. package/src/native/thread-times.tsx +89 -0
  64. package/src/native/thread-title.tsx +111 -0
  65. package/src/native/typing-bubble.tsx +85 -0
  66. package/src/react/inbox-actions.ts +121 -0
  67. package/src/react/index.tsx +172 -23
  68. package/src/web/inbox.tsx +120 -11
  69. package/src/web/index.ts +1 -1
  70. package/src/web/memory-client.ts +40 -7
  71. package/dist/chunk-5XYDVUPS.js.map +0 -1
  72. package/dist/chunk-D4RPOYB7.js.map +0 -1
@@ -216,3 +216,114 @@ describe("threadListMode", () => {
216
216
  expect(nearBottom(at(900))).toBe(false);
217
217
  });
218
218
  });
219
+
220
+ /** A list that draws its rows and footer, so the bubbles' status and the typing bubble render. */
221
+ function drawingList() {
222
+ function List(props: Record<string, unknown>) {
223
+ const data = (props.data as unknown[] | undefined) ?? [];
224
+ const renderItem = props.renderItem as (info: { item: unknown; index: number }) => ReactNode;
225
+ return (
226
+ <>
227
+ {data.map((item, index) => (
228
+ <div key={(item as ThreadRow).key}>{renderItem({ item, index })}</div>
229
+ ))}
230
+ {props.ListFooterComponent as ReactNode}
231
+ </>
232
+ );
233
+ }
234
+ return { List };
235
+ }
236
+
237
+ const LEE = "44444444-4444-4444-8444-444444444444";
238
+
239
+ function receiptsClient(messages: ChatMessage[], others: { userId: string; lastReadSeq: number; lastReadAt?: string | null }[], maxMembers: number | null = 2) {
240
+ const handlers: { onSignal?: (s: unknown) => void; onActivity?: (a: unknown) => void } = {};
241
+ const client = {
242
+ ...fakeClient(messages, 99),
243
+ members: vi.fn(async () => [
244
+ { conversationId: CONV, userId: ME, role: "member", lastReadSeq: 99, lastReadAt: null, joinedAt: "2026-10-01T00:00:00Z" },
245
+ ...others.map((o) => ({ conversationId: CONV, role: "member", joinedAt: "2026-10-01T00:00:00Z", lastReadAt: null, ...o })),
246
+ ]),
247
+ kind: vi.fn(async () => ({ kind: "direct", label: "Direct", maxMembers })),
248
+ subscribeConversation: vi.fn((_id: string, _me: string, h: typeof handlers) => {
249
+ Object.assign(handlers, h);
250
+ return { unsubscribe: vi.fn(), signal: vi.fn() };
251
+ }),
252
+ } as unknown as ChatClient;
253
+ return { client, handlers };
254
+ }
255
+
256
+ describe("ChatThreadScreen's message status", () => {
257
+ const today = new Date();
258
+ today.setHours(9, 41, 0, 0);
259
+ const sentAt = new Date(today.getTime() - 60_000).toISOString();
260
+ const messages = [msg(1, SAM, sentAt), msg(2, ME, sentAt)];
261
+
262
+ it("shows Read with the time under the last message you sent once the other person's lastReadSeq reaches it", async () => {
263
+ const { client } = receiptsClient(messages, [{ userId: SAM, lastReadSeq: 2, lastReadAt: today.toISOString() }]);
264
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} />));
265
+ const receipt = await screen.findByTestId("chat-thread-message-m2-receipt", {}, { timeout: 2000 });
266
+ expect(receipt.textContent).toBe(`Read ${today.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })}`);
267
+ expect(screen.queryByTestId("chat-thread-message-m1-receipt")).toBeNull();
268
+ });
269
+
270
+ it("turns Delivered into Read when the live read hint comes, from the members read again", async () => {
271
+ const sam = { userId: SAM, lastReadSeq: 1 };
272
+ const { client, handlers } = receiptsClient(messages, [sam]);
273
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} />));
274
+ await waitFor(() => expect(screen.getByTestId("chat-thread-message-m2-receipt").textContent).toBe("Delivered"), { timeout: 2000 });
275
+ sam.lastReadSeq = 2;
276
+ act(() => handlers.onSignal?.({ type: "read", conversationId: CONV, userId: SAM, seq: 2, at: null }));
277
+ await waitFor(() => expect(screen.getByTestId("chat-thread-message-m2-receipt").textContent).toBe("Read"));
278
+ });
279
+
280
+ it("never takes a read hint's payload as the read place: a forged one changes nothing", async () => {
281
+ const { client, handlers } = receiptsClient(messages, [{ userId: SAM, lastReadSeq: 1 }]);
282
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} />));
283
+ await waitFor(() => expect(screen.getByTestId("chat-thread-message-m2-receipt").textContent).toBe("Delivered"), { timeout: 2000 });
284
+ const fetches = vi.mocked(client.members).mock.calls.length;
285
+ act(() => handlers.onSignal?.({ type: "read", conversationId: CONV, userId: SAM, seq: 1_000_000, at: "2026-01-01T09:41:00Z" }));
286
+ act(() => handlers.onSignal?.({ type: "read", conversationId: CONV, userId: SAM, seq: 1_000_001, at: null }));
287
+ await waitFor(() => expect(vi.mocked(client.members).mock.calls.length).toBe(fetches + 1));
288
+ expect(screen.getByTestId("chat-thread-message-m2-receipt").textContent).toBe("Delivered");
289
+ });
290
+
291
+ it('hides it with receipts="hide"', async () => {
292
+ const { client } = receiptsClient(messages, [{ userId: SAM, lastReadSeq: 2 }]);
293
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} receipts="hide" />));
294
+ await screen.findByTestId("chat-thread-message-m2", {}, { timeout: 2000 });
295
+ expect(screen.queryByTestId("chat-thread-message-m2-receipt")).toBeNull();
296
+ });
297
+
298
+ it("in a group, says Read by N, and tapping it lists who", async () => {
299
+ const { client } = receiptsClient(messages, [{ userId: SAM, lastReadSeq: 2 }, { userId: LEE, lastReadSeq: 1 }], null);
300
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} />));
301
+ await waitFor(() => expect(screen.getByTestId("chat-thread-message-m2-receipt").textContent).toBe("Read by 1"), { timeout: 2000 });
302
+ fireEvent.click(screen.getByTestId("chat-thread-message-m2-receipt"));
303
+ expect(await screen.findByTestId(`chat-thread-readers-${SAM}`)).toBeTruthy();
304
+ expect(screen.queryByTestId(`chat-thread-readers-${LEE}`)).toBeNull();
305
+ });
306
+ });
307
+
308
+ describe("ChatThreadScreen's typing", () => {
309
+ it("draws someone typing as a bubble of dots at the bottom of the thread, read out as the activity line", async () => {
310
+ const { client, handlers } = receiptsClient([msg(1, SAM, "2026-11-22T09:00:00Z")], [{ userId: SAM, lastReadSeq: 1 }]);
311
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} />));
312
+ await screen.findByTestId("chat-thread-message-m1", {}, { timeout: 2000 });
313
+ expect(screen.queryByTestId("chat-thread-typing")).toBeNull();
314
+ act(() => handlers.onActivity?.({ userId: SAM, activity: "typing", at: Date.now() }));
315
+ const bubble = await screen.findByTestId("chat-thread-typing");
316
+ expect(bubble.getAttribute("aria-label")).toMatch(/is typing…$/);
317
+ expect(screen.getByTestId("chat-thread-typing-dot-2")).toBeTruthy();
318
+ expect(screen.queryByTestId("chat-thread-activity")).toBeNull();
319
+ });
320
+
321
+ it("keeps the words for someone recording a voice note", async () => {
322
+ const { client, handlers } = receiptsClient([msg(1, SAM, "2026-11-22T09:00:00Z")], [{ userId: SAM, lastReadSeq: 1 }]);
323
+ render(wrap(client, drawingList().List, <ChatThreadScreen conversationId={CONV} />));
324
+ await screen.findByTestId("chat-thread-message-m1", {}, { timeout: 2000 });
325
+ act(() => handlers.onActivity?.({ userId: SAM, activity: "recording-voice", at: Date.now() }));
326
+ expect((await screen.findByTestId("chat-thread-activity")).textContent).toMatch(/recording a voice message/);
327
+ expect(screen.queryByTestId("chat-thread-typing")).toBeNull();
328
+ });
329
+ });
@@ -0,0 +1,59 @@
1
+ // @vitest-environment happy-dom
2
+ // @feat:chat
3
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
4
+ import type { ReactElement } from "react";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import { ChatNativeProvider } from "../context";
7
+ import { chatThreadStackOptions } from "../stack-options";
8
+
9
+ afterEach(cleanup);
10
+
11
+ type TitleFn = (p: { tintColor?: string }) => ReactElement;
12
+
13
+ describe("useChatThreadStackOptions' title", () => {
14
+ it("stays the bar's plain title when nothing more is asked for", () => {
15
+ const opts = chatThreadStackOptions({ headerTitle: "Sam" }, "#fff");
16
+ expect(opts.title).toBe("Sam");
17
+ expect(opts.headerTitle).toBeUndefined();
18
+ });
19
+
20
+ it("draws an avatar, a subtitle and a button that opens the details, read as one", () => {
21
+ const onPressTitle = vi.fn();
22
+ const opts = chatThreadStackOptions({ headerTitle: "Sam", avatar: { name: "Sam Lee", src: null, id: "u2" }, subtitle: "Away until Monday", onPressTitle, titleHint: "Shows details" }, "#fff");
23
+ expect(opts.title).toBe("Sam");
24
+ render(<ChatNativeProvider>{(opts.headerTitle as TitleFn)({})}</ChatNativeProvider>);
25
+ const title = screen.getByTestId("chat-thread-title");
26
+ expect(title.getAttribute("role")).toBe("button");
27
+ expect(title.getAttribute("aria-label")).toBe("Sam, Away until Monday");
28
+ expect(screen.getByTestId("chat-thread-title-avatar").getAttribute("aria-hidden")).toBe("true");
29
+ fireEvent.click(title);
30
+ expect(onPressTitle).toHaveBeenCalled();
31
+ });
32
+
33
+ it("is a header, not a button, without onPressTitle; null hides the subtitle", () => {
34
+ const opts = chatThreadStackOptions({ headerTitle: "Group", subtitle: null }, "#fff");
35
+ render(<ChatNativeProvider>{(opts.headerTitle as TitleFn)({})}</ChatNativeProvider>);
36
+ expect(screen.getByTestId("chat-thread-title").getAttribute("role")).toBe("header");
37
+ expect(screen.queryByTestId("chat-thread-title-subtitle")).toBeNull();
38
+ });
39
+
40
+ it("takes {} and an id alone as avatar data (the initials), never as a child, and keeps an element as the app's own", () => {
41
+ for (const avatar of [{}, { id: "u2" }]) {
42
+ const opts = chatThreadStackOptions({ headerTitle: "Sam", avatar, subtitle: null }, "#fff");
43
+ const { unmount } = render(<ChatNativeProvider>{(opts.headerTitle as TitleFn)({})}</ChatNativeProvider>);
44
+ expect(screen.getByTestId("chat-thread-title-avatar").textContent).toBe("S");
45
+ unmount();
46
+ }
47
+ const own = chatThreadStackOptions({ headerTitle: "Sam", avatar: <span data-testid="own" />, subtitle: null }, "#fff");
48
+ render(<ChatNativeProvider>{(own.headerTitle as TitleFn)({})}</ChatNativeProvider>);
49
+ expect(screen.getByTestId("own")).toBeTruthy();
50
+ cleanup();
51
+ // An array or a Set of elements is a node too, never avatar data.
52
+ for (const avatar of [[<span key="a" data-testid="in-array" />], new Set([<span key="s" data-testid="in-set" />])]) {
53
+ const opts = chatThreadStackOptions({ headerTitle: "Sam", avatar, subtitle: null }, "#fff");
54
+ const { unmount } = render(<ChatNativeProvider>{(opts.headerTitle as TitleFn)({})}</ChatNativeProvider>);
55
+ expect(screen.getByTestId(Array.isArray(avatar) ? "in-array" : "in-set")).toBeTruthy();
56
+ unmount();
57
+ }
58
+ });
59
+ });
@@ -12,9 +12,9 @@
12
12
  * attachments and reply above it, the mic in Send's place and the recording in the input's.
13
13
  */
14
14
  import { useEffect, useMemo, useRef, useState } from "react";
15
- import { PanResponder, Pressable, ScrollView, View } from "react-native";
16
- import { NativeComposerBar, NativeIcon, NativeImage, NativeListItem, NativeSheet, NativeText, useGenesisModules } from "@marktiderman/genesis-ui-native/components";
17
- import { useThemeRoles } from "@marktiderman/genesis-ui-native/hooks";
15
+ import { Animated, PanResponder, Pressable, ScrollView, View } from "react-native";
16
+ import { NativeComposerBar, NativeContextMenu, NativeIcon, NativeImage, NativeText, useGenesisModules } from "@marktiderman/genesis-ui-native/components";
17
+ import { useReducedMotion, useThemeRoles } from "@marktiderman/genesis-ui-native/hooks";
18
18
  import { CHAT_LIMITS, formatDuration, recordingLimitMs } from "../core/media";
19
19
  import type { LocalFile } from "../core/outbox";
20
20
  import type { ChatRole } from "../core/types";
@@ -140,18 +140,17 @@ function ComposerBody({ composer, canPost, onSend, signalTyping, onRecordVideo,
140
140
  }
141
141
  setCanPaste(paste);
142
142
  // One source: straight to the picker, no sheet in between.
143
- if (!paste && !modules.imagePicker?.launchCameraAsync && modules.imagePicker) return pick("library", false);
143
+ if (!paste && !modules.imagePicker?.launchCameraAsync && modules.imagePicker) return pick("library");
144
144
  setAttachOpen(true);
145
145
  };
146
146
 
147
147
  const remaining = CHAT_LIMITS.attachmentsPerMessage - state.attachments.length;
148
- // The picker opens once the sheet has gone: iOS won't present one modal while another is dismissing.
149
- const afterSheet = () => new Promise<void>((resolve) => setTimeout(resolve, 800));
150
- const pick = async (from: "library" | "camera", fromSheet = true) => {
148
+ // From the menu, NativeContextMenu runs this once its sheet has gone (iOS won't present one modal
149
+ // while another is dismissing): no fixed wait.
150
+ const pick = async (from: "library" | "camera") => {
151
151
  setAttachOpen(false);
152
152
  const picker = modules.imagePicker;
153
153
  if (!picker) return;
154
- if (fromSheet) await afterSheet();
155
154
  try {
156
155
  if (from === "camera") {
157
156
  const permission = await picker.requestCameraPermissionsAsync?.();
@@ -264,19 +263,18 @@ function ComposerBody({ composer, canPost, onSend, signalTyping, onRecordVideo,
264
263
  replaceInput={recording && voice ? <RecordingBar voice={voice} testID={testID} /> : null}
265
264
  />
266
265
  <ChatEmojiPickerSheet open={emojiOpen} onClose={() => setEmojiOpen(false)} onSelect={insertEmoji} userId={userId} testID={`${testID}-emoji-sheet`} />
267
- <NativeSheet open={attachOpen} onOpenChange={setAttachOpen} testID={`${testID}-attach-sheet`}>
268
- <View>
269
- {modules.imagePicker ? (
270
- <NativeListItem testID={`${testID}-attach-library`} title={copy.attachLibrary} leading={<NativeIcon name="image" />} onPress={() => void pick("library")} />
271
- ) : null}
272
- {modules.imagePicker?.launchCameraAsync ? (
273
- <NativeListItem testID={`${testID}-attach-camera`} title={copy.attachCamera} leading={<NativeIcon name="camera" />} onPress={() => void pick("camera")} />
274
- ) : null}
275
- {canPaste ? (
276
- <NativeListItem testID={`${testID}-attach-paste`} title={copy.attachPaste} leading={<NativeIcon name="copy" />} onPress={() => void paste()} />
277
- ) : null}
278
- </View>
279
- </NativeSheet>
266
+ <NativeContextMenu
267
+ open={attachOpen}
268
+ onOpenChange={setAttachOpen}
269
+ title={copy.attach}
270
+ cancelLabel={copy.cancel}
271
+ actions={[
272
+ ...(modules.imagePicker ? [{ id: "library", label: copy.attachLibrary, onPress: () => void pick("library") }] : []),
273
+ ...(modules.imagePicker?.launchCameraAsync ? [{ id: "camera", label: copy.attachCamera, onPress: () => void pick("camera") }] : []),
274
+ ...(canPaste ? [{ id: "paste", label: copy.attachPaste, onPress: () => void paste() }] : []),
275
+ ]}
276
+ testID={`${testID}-attach-sheet`}
277
+ />
280
278
  </>
281
279
  );
282
280
  }
@@ -316,16 +314,40 @@ function IconButton({
316
314
  * same button stops and sends. It stays one view throughout: swapping in another button while
317
315
  * the finger that locked is still down left the touch with a responder that no longer existed,
318
316
  * and the next tap anywhere on the screen did nothing.
317
+ *
318
+ * While held, the mic follows the finger (left toward cancel, up toward the lock) on the native
319
+ * driver, and springs home when it lets go or locks; with Reduce Motion it goes home at once.
319
320
  */
321
+ export function micOffset(dx: number, dy: number): { x: number; y: number } {
322
+ return { x: Math.max(-MIC_FOLLOW_X, Math.min(0, dx)), y: Math.max(-MIC_FOLLOW_Y, Math.min(0, dy)) };
323
+ }
324
+ const MIC_FOLLOW_X = 120;
325
+ const MIC_FOLLOW_Y = 72;
326
+
320
327
  function MicButton({ voice, disabled, testID }: { voice: Voice; disabled: boolean; testID: string }) {
321
328
  const { copy } = useChatNative();
322
329
  const colors = useThemeRoles();
330
+ const reducedMotion = useReducedMotion();
331
+ const reduced = useRef(reducedMotion);
332
+ reduced.current = reducedMotion;
333
+ const followX = useRef(new Animated.Value(0)).current;
334
+ const followY = useRef(new Animated.Value(0)).current;
335
+ const home = useRef(() => {
336
+ for (const v of [followX, followY]) {
337
+ if (reduced.current) v.setValue(0);
338
+ else Animated.spring(v, { toValue: 0, useNativeDriver: true, bounciness: 6 }).start();
339
+ }
340
+ }).current;
323
341
  const { state, dispatch } = voice;
324
342
  const latest = useRef(dispatch);
325
343
  latest.current = dispatch;
326
344
  const locked = state.phase === "recording" && state.locked;
327
345
  const lockedNow = useRef(locked);
328
346
  lockedNow.current = locked;
347
+ // Locking, or the recording ending, sends the mic home.
348
+ useEffect(() => {
349
+ if (locked || state.phase === "idle") home();
350
+ }, [locked, state.phase, home]);
329
351
  // VoiceOver and TalkBack can't hold and slide: a double tap starts a locked (hands-free) recording.
330
352
  const lockWhenReady = useRef(false);
331
353
  useEffect(() => {
@@ -348,14 +370,24 @@ function MicButton({ voice, disabled, testID }: { voice: Voice; disabled: boolea
348
370
  if (!tapToSend) latest.current({ type: "press" });
349
371
  },
350
372
  onPanResponderMove: (_e, g) => {
351
- if (!tapToSend) latest.current({ type: "move", dx: g.dx, dy: g.dy });
373
+ if (tapToSend) return;
374
+ latest.current({ type: "move", dx: g.dx, dy: g.dy });
375
+ if (!lockedNow.current) {
376
+ const at = micOffset(g.dx, g.dy);
377
+ followX.setValue(at.x);
378
+ followY.setValue(at.y);
379
+ }
380
+ },
381
+ onPanResponderRelease: () => {
382
+ home();
383
+ latest.current({ type: tapToSend ? "send" : "release" });
352
384
  },
353
- onPanResponderRelease: () => latest.current({ type: tapToSend ? "send" : "release" }),
354
385
  onPanResponderTerminate: () => {
386
+ home();
355
387
  if (!tapToSend) latest.current({ type: "cancel" });
356
388
  },
357
389
  });
358
- }, []);
390
+ }, [followX, followY, home]);
359
391
 
360
392
  const holding = !locked && (state.phase === "starting" || state.phase === "recording");
361
393
  return (
@@ -384,9 +416,12 @@ function MicButton({ voice, disabled, testID }: { voice: Voice; disabled: boolea
384
416
  style={{ width: 44, height: 44, alignItems: "center", justifyContent: "center", opacity: disabled ? 0.4 : 1, transform: [{ scale: holding ? 1.25 : 1 }] }}
385
417
  {...(disabled ? {} : responder.panHandlers)}
386
418
  >
387
- <View style={{ width: 34, height: 34, borderRadius: 17, alignItems: "center", justifyContent: "center", backgroundColor: locked ? colors.tint : holding ? colors.destructive : "transparent" }}>
419
+ <Animated.View
420
+ testID={`${testID}-mic-follow`}
421
+ style={{ width: 34, height: 34, borderRadius: 17, alignItems: "center", justifyContent: "center", backgroundColor: locked ? colors.tint : holding ? colors.destructive : "transparent", transform: [{ translateX: followX }, { translateY: followY }] }}
422
+ >
388
423
  <NativeIcon name={locked ? "arrow-up" : "mic"} size={locked || holding ? 18 : 24} color={locked || holding ? colors.surface : colors.tint} weight={locked ? "semibold" : undefined} />
389
- </View>
424
+ </Animated.View>
390
425
  </View>
391
426
  </View>
392
427
  );
@@ -3,10 +3,14 @@
3
3
  * Every word the native chat screens say, in one catalog an app can override
4
4
  * (translate, rename "Message" to "Note"). `{name}` and `{count}` are filled in.
5
5
  */
6
+ import { defaultInboxActionLabels, type ChatInboxActionLabels } from "../react/inbox-actions";
6
7
  import { chatOrganiseCopy, type ChatOrganiseCopy } from "./organise-copy";
7
8
 
8
- /** Topics, scheduled send, availability, broadcast, search and moderation are in `ChatOrganiseCopy`. */
9
- export interface ChatNativeCopy extends ChatOrganiseCopy {
9
+ /**
10
+ * Topics, scheduled send, availability, broadcast, search and moderation are in `ChatOrganiseCopy`;
11
+ * the inbox row actions' words in `ChatInboxActionLabels`, shared with the web inbox.
12
+ */
13
+ export interface ChatNativeCopy extends ChatOrganiseCopy, ChatInboxActionLabels {
10
14
  inboxTitle: string;
11
15
  inboxEmptyTitle: string;
12
16
  inboxEmptyBody: string;
@@ -18,12 +22,20 @@ export interface ChatNativeCopy extends ChatOrganiseCopy {
18
22
  someone: string;
19
23
  youPrefix: string;
20
24
  mentionedYou: string;
21
- markRead: string;
22
- pin: string;
23
- unpin: string;
24
- archive: string;
25
25
  threadEmptyTitle: string;
26
26
  threadEmptyBody: string;
27
+ /** The conversation or its first page couldn't be read, and there's nothing to show. */
28
+ threadErrorTitle: string;
29
+ threadErrorBody: string;
30
+ /** The phone is offline (NetInfo), in the thread's status line. */
31
+ waitingForNetwork: string;
32
+ /** Online, but the live channel hasn't joined (yet, or again). */
33
+ connecting: string;
34
+ /** The pill over the composer when new messages came in below where you are. */
35
+ newMessagesPillOne: string;
36
+ newMessagesPill: string;
37
+ /** VoiceOver's hint on the pill. */
38
+ newMessagesPillHint: string;
27
39
  loadEarlier: string;
28
40
  newMessages: string;
29
41
  placeholder: string;
@@ -123,6 +135,18 @@ export interface ChatNativeCopy extends ChatOrganiseCopy {
123
135
  viewerHint: string;
124
136
  sending: string;
125
137
  notSent: string;
138
+ /** Message status under the last message you sent (`ChatThreadScreen receipts`). */
139
+ receiptSending: string;
140
+ receiptSent: string;
141
+ receiptDelivered: string;
142
+ /** Read, when the server has no read time (a database before chat 0006). */
143
+ receiptRead: string;
144
+ receiptReadAt: string;
145
+ receiptReadBy: string;
146
+ receiptReadByEveryone: string;
147
+ /** The hint on "Read by N", and the title of the sheet it opens. */
148
+ receiptReadersHint: string;
149
+ receiptReadersTitle: string;
126
150
  retry: string;
127
151
  /** On a message whose file didn't survive a relaunch: pick it again. */
128
152
  attachAgain: string;
@@ -173,12 +197,16 @@ export const chatNativeCopy: ChatNativeCopy = {
173
197
  someone: "Someone",
174
198
  youPrefix: "You: ",
175
199
  mentionedYou: "Mentioned you",
176
- markRead: "Mark read",
177
- pin: "Pin",
178
- unpin: "Unpin",
179
- archive: "Archive",
200
+ ...defaultInboxActionLabels,
180
201
  threadEmptyTitle: "No messages yet",
181
202
  threadEmptyBody: "Say hello below.",
203
+ threadErrorTitle: "Couldn't load messages",
204
+ threadErrorBody: "Check your connection, then try again.",
205
+ waitingForNetwork: "Waiting for network…",
206
+ connecting: "Connecting…",
207
+ newMessagesPillOne: "1 new message",
208
+ newMessagesPill: "{count} new messages",
209
+ newMessagesPillHint: "Goes to the newest message",
182
210
  loadEarlier: "Load earlier messages",
183
211
  newMessages: "New messages",
184
212
  placeholder: "Message",
@@ -264,6 +292,15 @@ export const chatNativeCopy: ChatNativeCopy = {
264
292
  viewerHint: "Swipe up or down for the next or previous photo.",
265
293
  sending: "Sending",
266
294
  notSent: "Not sent",
295
+ receiptSending: "Sending…",
296
+ receiptSent: "Sent",
297
+ receiptDelivered: "Delivered",
298
+ receiptRead: "Read",
299
+ receiptReadAt: "Read {time}",
300
+ receiptReadBy: "Read by {count}",
301
+ receiptReadByEveryone: "Read by everyone",
302
+ receiptReadersHint: "Shows who has read it",
303
+ receiptReadersTitle: "Read by",
267
304
  retry: "Retry",
268
305
  attachAgain: "Attach again",
269
306
  discard: "Delete",
@@ -212,7 +212,7 @@ export function ChatEmojiPickerSheet({ open, onClose, onSelect, testID = "chat-e
212
212
  const { copy } = useChatNative();
213
213
  const colors = useThemeRoles();
214
214
  return (
215
- <NativeSheet open={open} onOpenChange={(o) => (o ? undefined : onClose())} testID={testID}>
215
+ <NativeSheet open={open} onOpenChange={(o) => (o ? undefined : onClose())} fitContent testID={testID}>
216
216
  <View style={{ gap: 4, paddingHorizontal: 16 }}>
217
217
  <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between", minHeight: 44 }}>
218
218
  <NativeText preset="h4" accessibilityRole="header">
@@ -2,17 +2,19 @@
2
2
  * @feat:chat
3
3
  * Your conversations on genesis-ui-native's InboxPage: each with its avatar,
4
4
  * unread count, last message and time; pull to refresh; an empty state that
5
- * offers to start a conversation; Mark read, Pin and Archive on swipe, long
6
- * press and as accessibility actions. Under the navigator's large title
7
- * (`getInboxPageStackOptions`).
5
+ * offers to start a conversation. Each row has Messages' actions: swipe right for Mark as
6
+ * Unread (or Read) and Pin, left for Hide Alerts and Delete (for you, after asking); Archive
7
+ * is in the long-press menu. Every action is also a screen reader action on the row. Under the
8
+ * navigator's large title (`getInboxPageStackOptions`).
8
9
  */
9
10
  import { useCallback, useMemo, useState } from "react";
11
+ import { Alert } from "react-native";
12
+ import type { RowSwipeAction } from "@marktiderman/genesis-core/row-actions";
10
13
  import { NativeAvatar } from "@marktiderman/genesis-ui-native/components";
11
14
  import { InboxPage, type InboxItem, type InboxPageProps } from "@marktiderman/genesis-ui-native/layouts";
12
15
  import type { ChatInboxItem } from "../core/types";
13
- import { chatKeys, useChat, useInbox, usePeople, type ChatAttachmentKind } from "../react/index";
16
+ import { inboxRowActions, useChat, useInbox, useInboxActions, usePeople, type ChatAttachmentKind, type ChatConfirm } from "../react/index";
14
17
  import { attachmentPreview } from "./attachment-cards";
15
- import { useQueryClient } from "@tanstack/react-query";
16
18
  import type { ChatNativeCopy } from "./copy";
17
19
  import { initials, useChatNative, type ChatPerson } from "./context";
18
20
  import { displayBody } from "./message-bubble";
@@ -29,6 +31,12 @@ export interface ChatInboxScreenProps {
29
31
  /** Every kind but these (`["support"]` keeps support tickets out of a messages inbox). */
30
32
  excludeKinds?: string[];
31
33
  archived?: boolean;
34
+ /**
35
+ * Each row's actions: receives the conversation and the default set (`inboxRowActions`:
36
+ * Messages' Unread, Pin, Hide Alerts, Delete for me and Archive) and returns the row's. Add,
37
+ * drop, reorder or relabel them; the default keeps them as they are.
38
+ */
39
+ rowActions?: (item: ChatInboxItem, defaults: RowSwipeAction[]) => RowSwipeAction[];
32
40
  /** Passed to InboxPage (a header, a section title, slots). */
33
41
  pageProps?: Partial<Omit<InboxPageProps, "items">>;
34
42
  testID?: string;
@@ -58,13 +66,26 @@ export function inboxRow(
58
66
  unread: item.unread > 0,
59
67
  unreadCount: item.unread,
60
68
  meta: item.mentioned ? ctx.copy.mentionedYou : undefined,
69
+ muted: item.muted,
70
+ pinned: item.pinned,
61
71
  avatar: <NativeAvatar size={40} src={other?.avatarUrl ?? null} fallback={initials(title)} alt={title} recyclingKey={item.conversationId} />,
62
72
  };
63
73
  }
64
74
 
65
- export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, archived, pageProps, testID = "chat-inbox" }: ChatInboxScreenProps) {
66
- const { client, userId, attachmentKinds } = useChat();
67
- const queryClient = useQueryClient();
75
+ /** Asks with the system alert: Cancel, then the destructive action. */
76
+ export function alertConfirm(cancelLabel: string): ChatConfirm {
77
+ return (title, body, confirmLabel) =>
78
+ new Promise((resolve) =>
79
+ Alert.alert(title, body, [
80
+ { text: cancelLabel, style: "cancel", onPress: () => resolve(false) },
81
+ { text: confirmLabel, style: "destructive", onPress: () => resolve(true) },
82
+ ], { cancelable: true, onDismiss: () => resolve(false) }),
83
+ );
84
+ }
85
+
86
+ export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, archived, rowActions, pageProps, testID = "chat-inbox" }: ChatInboxScreenProps) {
87
+ const { userId, attachmentKinds } = useChat();
88
+ const act = useInboxActions();
68
89
  const { copy, person: known } = useChatNative();
69
90
  const inbox = useInbox({ kind, kinds, excludeKinds, archived });
70
91
  // The other person in each direct conversation, fetched in one batch (ChatProvider loadPeople).
@@ -82,26 +103,26 @@ export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, ar
82
103
  }
83
104
  }, [inbox]);
84
105
 
85
- const settle = useCallback(() => {
86
- void queryClient.invalidateQueries({ queryKey: ["genesis-chat", "inbox"] });
87
- void queryClient.invalidateQueries({ queryKey: chatKeys.unread() });
88
- }, [queryClient]);
106
+ // A row action that fails says so, rather than leaving the row as it was without a word.
107
+ const options = useMemo(
108
+ () => ({
109
+ confirm: alertConfirm(copy.cancel),
110
+ onError: (e: unknown) => Alert.alert(copy.actionFailed, e instanceof Error ? e.message : undefined),
111
+ }),
112
+ [copy],
113
+ );
89
114
 
90
- const items: InboxItem[] = inbox.items.map((item) => ({
91
- ...inboxRow(item, { me: userId, copy, person, kinds: attachmentKinds }),
92
- onPress: () => onOpen(item.conversationId),
93
- swipeActions: [
94
- ...(item.unread > 0 ? [{ id: "read", label: copy.markRead, onPress: () => void client.markRead(item.conversationId).then(settle, settle) }] : []),
95
- {
96
- id: "pin",
97
- label: item.pinned ? copy.unpin : copy.pin,
98
- onPress: () => void client.setMySettings(item.conversationId, { pinned: !item.pinned }).then(settle, settle),
99
- },
100
- ...(item.archived
101
- ? []
102
- : [{ id: "archive", label: copy.archive, onPress: () => void client.setMySettings(item.conversationId, { archived: true }).then(settle, settle) }]),
103
- ],
104
- }));
115
+ const items: InboxItem[] = inbox.items.map((item) => {
116
+ // Messages' row actions: Unread (or Read) and Pin to the right, Hide Alerts and Delete to the
117
+ // left, round buttons; Archive in the long-press menu only. Every one is also a screen reader
118
+ // action on the row.
119
+ const defaults = inboxRowActions(item, act, copy, options);
120
+ return {
121
+ ...inboxRow(item, { me: userId, copy, person, kinds: attachmentKinds }),
122
+ onPress: () => onOpen(item.conversationId),
123
+ swipeActions: rowActions ? rowActions(item, defaults) : defaults,
124
+ };
125
+ });
105
126
 
106
127
  return (
107
128
  <InboxPage
@@ -114,6 +135,10 @@ export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, ar
114
135
  onRefresh={refresh}
115
136
  emptyTitle={copy.inboxEmptyTitle}
116
137
  emptyBody={copy.inboxEmptyBody}
138
+ // Messages' round buttons behind the swipe, the row a pill while open.
139
+ swipeAppearance="round"
140
+ mutedLabel={copy.alertsOff}
141
+ pinnedLabel={copy.pinnedMark}
117
142
  emptyActionLabel={onStart ? copy.startConversation : undefined}
118
143
  onEmptyAction={onStart}
119
144
  {...pageProps}
@@ -26,8 +26,13 @@
26
26
  *
27
27
  * @stability Beta
28
28
  */
29
- export { ChatInboxScreen, inboxRow, type ChatInboxScreenProps } from "./inbox-screen";
30
- export { ChatThreadScreen, threadListMode, nearBottom, AT_BOTTOM_POINTS, type ChatThreadScreenProps, type ChatThreadScreenSlots } from "./thread-screen";
29
+ export { ChatInboxScreen, alertConfirm, inboxRow, type ChatInboxScreenProps } from "./inbox-screen";
30
+ export { ChatThreadScreen, threadListMode, nearBottom, AT_BOTTOM_POINTS, connectionState, countUnseenBelow, useOnline, type ChatThreadScreenProps, type ChatThreadScreenSlots, type ChatThreadAccessoryContext, type ChatConnectionState } from "./thread-screen";
31
+ export { ChatThreadTitle, type ChatThreadTitleProps, type ChatThreadTitleAvatar } from "./thread-title";
32
+ export { bubbleCorners, bubblePosition, type BubblePosition } from "./message-bubble";
33
+ export { TIME_REVEAL_WIDTH, startsTimeReveal, timeRevealFor } from "./thread-times";
34
+ export { lastSentReceipt, receiptText, readWhen, type ChatReceiptsMode, type MessageReceipt, type MessageReceiptFor, type ReceiptOptions, type ReceiptCopy } from "./receipts";
35
+ export { ChatTypingBubble, type ChatTypingBubbleProps } from "./typing-bubble";
31
36
  export { chatThreadStackOptions, useChatThreadStackOptions, type ChatThreadStackOptionsProps } from "./stack-options";
32
37
  export { ChatStartSheet, ChatStartButton, type ChatStartPerson, type ChatStartSheetProps } from "./start-sheet";
33
38
  export { ChatComposer, type ChatComposerProps } from "./composer";
@@ -22,6 +22,11 @@ export interface BubbleAttachment {
22
22
  kind: string;
23
23
  /** What to show now: a signed URL, or the local preview. */
24
24
  uri: string | null;
25
+ /**
26
+ * What expo-image caches it under: the storage path, which stays the same when the signed URL
27
+ * is re-signed (a new expiry would otherwise miss the disk cache and download it again).
28
+ */
29
+ cacheKey?: string | null;
25
30
  name: string | null;
26
31
  width: number | null;
27
32
  height: number | null;
@@ -45,6 +50,7 @@ export function fromServer(a: ChatAttachment, urls: Record<string, string>): Bub
45
50
  key: a.id,
46
51
  kind: a.kind,
47
52
  uri: (a.path ? urls[a.path] : null) ?? a.url ?? null,
53
+ cacheKey: a.path && a.provider === "storage" ? a.path : null,
48
54
  name: a.name,
49
55
  width: a.width,
50
56
  height: a.height,
@@ -145,7 +151,7 @@ export function MessageAttachments({ attachments, mine, onOpenImage, testID }: A
145
151
  style={{ borderRadius: 14, overflow: "hidden" }}
146
152
  >
147
153
  {a.uri ? (
148
- <NativeImage src={a.uri} width={w} height={h} placeholder={a.thumbhash ? { thumbhash: a.thumbhash } : undefined} recyclingKey={a.key} />
154
+ <NativeImage src={a.uri} width={w} height={h} placeholder={a.thumbhash ? { thumbhash: a.thumbhash } : undefined} cacheKey={a.cacheKey ?? undefined} recyclingKey={a.key} />
149
155
  ) : (
150
156
  <View style={{ width: w, height: h, backgroundColor: colors.fill }} />
151
157
  )}
@@ -58,7 +58,7 @@ export function MessageActionsSheet({ message, context, onClose, onReact, onActi
58
58
  };
59
59
 
60
60
  return (
61
- <NativeSheet open={message !== null} onOpenChange={(open) => (open ? undefined : onClose())} testID={testID}>
61
+ <NativeSheet open={message !== null} onOpenChange={(open) => (open ? undefined : onClose())} fitContent testID={testID}>
62
62
  {message && picking ? (
63
63
  <View style={{ paddingHorizontal: 16 }}>
64
64
  <ChatEmojiPicker