@marktiderman/genesis-ui-native 3.5.1 → 3.7.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 (96) hide show
  1. package/README.md +115 -7
  2. package/dist/{chunk-ONH2PCGH.js → chunk-3KFUS7O6.js} +9 -15
  3. package/dist/chunk-3KFUS7O6.js.map +1 -0
  4. package/dist/{chunk-LBVD7XXL.js → chunk-7NDKIIOT.js} +627 -20
  5. package/dist/chunk-7NDKIIOT.js.map +1 -0
  6. package/dist/chunk-CAI7LGN6.js +39 -0
  7. package/dist/chunk-CAI7LGN6.js.map +1 -0
  8. package/dist/{chunk-ABVSSJNT.js → chunk-GBNIBHSU.js} +198 -168
  9. package/dist/chunk-GBNIBHSU.js.map +1 -0
  10. package/dist/chunk-IXC3LO2K.js +410 -0
  11. package/dist/chunk-IXC3LO2K.js.map +1 -0
  12. package/dist/{chunk-GHYUNNNU.js → chunk-KH2RVAI5.js} +174 -93
  13. package/dist/chunk-KH2RVAI5.js.map +1 -0
  14. package/dist/{chunk-6KWEAGRD.js → chunk-O4BMDV7I.js} +110 -17
  15. package/dist/chunk-O4BMDV7I.js.map +1 -0
  16. package/dist/chunk-RTYO24SC.js +105 -0
  17. package/dist/chunk-RTYO24SC.js.map +1 -0
  18. package/dist/{chunk-D5RKSPMH.js → chunk-YWDDDYDI.js} +4 -3
  19. package/dist/chunk-YWDDDYDI.js.map +1 -0
  20. package/dist/components/index.d.ts +382 -10
  21. package/dist/components/index.js +6 -5
  22. package/dist/data/index.d.ts +68 -4
  23. package/dist/data/index.js +231 -30
  24. package/dist/data/index.js.map +1 -1
  25. package/dist/hooks/index.d.ts +90 -2
  26. package/dist/hooks/index.js +3 -3
  27. package/dist/icons/lucide.d.ts +1 -1
  28. package/dist/icons/lucide.js +7 -1
  29. package/dist/icons/lucide.js.map +1 -1
  30. package/dist/{inbox-page-BEarNEIP.d.ts → inbox-page-B7_Oi2fS.d.ts} +2 -44
  31. package/dist/index.d.ts +8 -5
  32. package/dist/index.js +9 -8
  33. package/dist/layouts/index.d.ts +40 -51
  34. package/dist/layouts/index.js +6 -4
  35. package/dist/{native-modules-PwnGltOU.d.ts → native-modules-DEJJQhDx.d.ts} +55 -1
  36. package/package.json +101 -4
  37. package/src/__tests__/doctor-rules.test.ts +87 -0
  38. package/src/__tests__/native-modules-lists.test.tsx +1 -0
  39. package/src/components/__tests__/button-haptic.test.tsx +52 -0
  40. package/src/components/__tests__/composer-bar.test.tsx +79 -0
  41. package/src/components/__tests__/gallery-card.test.tsx +59 -0
  42. package/src/components/__tests__/gallery-grid.test.tsx +160 -0
  43. package/src/components/__tests__/lightbox-resnap.test.tsx +50 -0
  44. package/src/components/__tests__/lightbox-zoom.test.ts +33 -0
  45. package/src/components/__tests__/lightbox.test.tsx +141 -0
  46. package/src/components/__tests__/live-indicator.test.tsx +72 -0
  47. package/src/components/__tests__/rating.test.tsx +82 -0
  48. package/src/components/__tests__/thread-list.test.tsx +219 -0
  49. package/src/components/button.tsx +18 -1
  50. package/src/components/composer-bar.tsx +276 -0
  51. package/src/components/drawer.tsx +15 -9
  52. package/src/components/gallery-card.tsx +109 -0
  53. package/src/components/gallery-grid.tsx +285 -0
  54. package/src/components/gallery-layout.ts +2 -0
  55. package/src/components/gallery-types.ts +2 -0
  56. package/src/components/index.ts +44 -0
  57. package/src/components/lightbox-zoom.tsx +282 -0
  58. package/src/components/lightbox.tsx +342 -0
  59. package/src/components/live-indicator.tsx +139 -0
  60. package/src/components/rating.tsx +128 -0
  61. package/src/components/skeleton.tsx +9 -4
  62. package/src/components/thread-list.tsx +457 -0
  63. package/src/components/toast.tsx +7 -4
  64. package/src/data/NativeConflictSheet.tsx +181 -0
  65. package/src/data/NativeResourceForm.tsx +15 -1
  66. package/src/data/index.ts +2 -0
  67. package/src/data/resource-view/NativeRecordView.tsx +85 -8
  68. package/src/data/resource-view/NativeResourceView.tsx +79 -32
  69. package/src/data/resource-view/__tests__/native-record-view.test.tsx +95 -1
  70. package/src/data/resource-view/__tests__/native-resource-gallery.test.tsx +125 -0
  71. package/src/hooks/__tests__/use-haptics.test.tsx +146 -0
  72. package/src/hooks/__tests__/use-motion.test.tsx +106 -0
  73. package/src/hooks/__tests__/use-thread-jump.test.tsx +88 -0
  74. package/src/hooks/index.ts +5 -0
  75. package/src/hooks/use-haptics.ts +64 -0
  76. package/src/hooks/use-motion.ts +128 -0
  77. package/src/hooks/use-press-feedback.ts +87 -0
  78. package/src/hooks/use-thread-jump.ts +110 -0
  79. package/src/icon-names.ts +6 -0
  80. package/src/icons/lucide.ts +12 -0
  81. package/src/layouts/__tests__/inbox-page.test.tsx +6 -0
  82. package/src/layouts/__tests__/thread-page.test.tsx +114 -14
  83. package/src/layouts/inbox-page.tsx +6 -55
  84. package/src/layouts/index.ts +2 -0
  85. package/src/layouts/thread-page.tsx +326 -262
  86. package/src/native-modules.tsx +20 -2
  87. package/dist/chunk-6KWEAGRD.js.map +0 -1
  88. package/dist/chunk-7PCWEY6R.js +0 -27
  89. package/dist/chunk-7PCWEY6R.js.map +0 -1
  90. package/dist/chunk-ABVSSJNT.js.map +0 -1
  91. package/dist/chunk-D5RKSPMH.js.map +0 -1
  92. package/dist/chunk-GHYUNNNU.js.map +0 -1
  93. package/dist/chunk-LBVD7XXL.js.map +0 -1
  94. package/dist/chunk-ONH2PCGH.js.map +0 -1
  95. package/dist/chunk-Z3AQYVUA.js +0 -36
  96. package/dist/chunk-Z3AQYVUA.js.map +0 -1
@@ -0,0 +1,219 @@
1
+ // @feat:inbox-thread
2
+ import { forwardRef, useImperativeHandle, createRef } from "react";
3
+ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
4
+ import { AccessibilityInfo } from "react-native";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import { GenesisModulesProvider } from "../../native-modules";
7
+ import { NativeThreadList, threadListMode, threadNearBottom, type NativeThreadListHandle } from "../thread-list";
8
+
9
+ type Row = { id: string; text: string };
10
+ const rows: Row[] = [
11
+ { id: "a", text: "first" },
12
+ { id: "b", text: "second" },
13
+ { id: "c", text: "third" },
14
+ ];
15
+
16
+ /** A list module that records its props and the calls made through its ref. */
17
+ function recordingList() {
18
+ const calls = { props: [] as Record<string, unknown>[], scrollToIndex: vi.fn(), scrollToEnd: vi.fn(), scrollToOffset: vi.fn() };
19
+ const List = forwardRef<unknown, Record<string, any>>(function List(props, ref) {
20
+ calls.props.push(props);
21
+ useImperativeHandle(ref, () => ({ scrollToIndex: calls.scrollToIndex, scrollToEnd: calls.scrollToEnd, scrollToOffset: calls.scrollToOffset }));
22
+ return (
23
+ <div data-testid={props.testID} role={props.accessibilityRole}>
24
+ {props.ListHeaderComponent}
25
+ {props.data.map((item: Row, index: number) => (
26
+ <div key={props.keyExtractor(item)}>{props.renderItem({ item, index })}</div>
27
+ ))}
28
+ </div>
29
+ );
30
+ });
31
+ return { List, calls };
32
+ }
33
+
34
+ const renderRow = (r: Row) => <span data-testid={`row-${r.id}`}>{r.text}</span>;
35
+
36
+ afterEach(() => vi.restoreAllMocks());
37
+
38
+ describe("threadListMode", () => {
39
+ it("uses FlashList's chat mode, and FlatList's held position with following by hand", () => {
40
+ expect(threadListMode(true, false)).toEqual({
41
+ followsByHand: false,
42
+ maintainVisibleContentPosition: { startRenderingFromBottom: true, autoscrollToBottomThreshold: 0.2, animateAutoScrollToBottom: true },
43
+ });
44
+ expect(threadListMode(true, true).maintainVisibleContentPosition.animateAutoScrollToBottom).toBe(false);
45
+ // Anchored past the list header (child 0), so loading earlier rows from the very top keeps the place.
46
+ expect(threadListMode(false, false)).toEqual({ followsByHand: true, maintainVisibleContentPosition: { minIndexForVisible: 1 } });
47
+ });
48
+
49
+ it("counts near the bottom as the bottom", () => {
50
+ expect(threadNearBottom({ contentOffset: { y: 900 }, contentSize: { height: 1500 }, layoutMeasurement: { height: 500 } })).toBe(true);
51
+ expect(threadNearBottom({ contentOffset: { y: 100 }, contentSize: { height: 1500 }, layoutMeasurement: { height: 500 } })).toBe(false);
52
+ });
53
+ });
54
+
55
+ describe("NativeThreadList", () => {
56
+ it("renders oldest first as a list, through the app's FlashList in chat mode, not inverted", () => {
57
+ const { List, calls } = recordingList();
58
+ render(
59
+ <GenesisModulesProvider modules={{ list: List as never }}>
60
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} getItemType={() => "theirs"} />
61
+ </GenesisModulesProvider>,
62
+ );
63
+ expect(screen.getByTestId("l").getAttribute("role")).toBe("list");
64
+ expect([...screen.getByTestId("l").querySelectorAll('[data-testid^="row-"]')].map((e) => e.textContent)).toEqual(["first", "second", "third"]);
65
+ const props = calls.props.at(-1)!;
66
+ expect(props.inverted).toBeUndefined();
67
+ expect(props.maintainVisibleContentPosition).toMatchObject({ startRenderingFromBottom: true });
68
+ expect(props.keyboardDismissMode).toBe("interactive");
69
+ });
70
+
71
+ it("loads earlier rows near the top, and offers the button too", () => {
72
+ const { List, calls } = recordingList();
73
+ const onLoadEarlier = vi.fn();
74
+ render(
75
+ <GenesisModulesProvider modules={{ list: List as never }}>
76
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} hasEarlier onLoadEarlier={onLoadEarlier} />
77
+ </GenesisModulesProvider>,
78
+ );
79
+ (calls.props.at(-1)!.onStartReached as () => void)();
80
+ expect(onLoadEarlier).toHaveBeenCalledTimes(1);
81
+ fireEvent.click(screen.getByTestId("l-earlier"));
82
+ expect(onLoadEarlier).toHaveBeenCalledTimes(2);
83
+ });
84
+
85
+ it("doesn't load earlier rows while they're already loading", () => {
86
+ const { List, calls } = recordingList();
87
+ const onLoadEarlier = vi.fn();
88
+ render(
89
+ <GenesisModulesProvider modules={{ list: List as never }}>
90
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} hasEarlier loadingEarlier onLoadEarlier={onLoadEarlier} />
91
+ </GenesisModulesProvider>,
92
+ );
93
+ (calls.props.at(-1)!.onStartReached as () => void)();
94
+ expect(onLoadEarlier).not.toHaveBeenCalled();
95
+ expect(screen.getByTestId("l-earlier-loading")).toBeTruthy();
96
+ });
97
+
98
+ it("reports leaving and coming back to the bottom", () => {
99
+ const { List, calls } = recordingList();
100
+ const onAtBottomChange = vi.fn();
101
+ render(
102
+ <GenesisModulesProvider modules={{ list: List as never }}>
103
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} onAtBottomChange={onAtBottomChange} />
104
+ </GenesisModulesProvider>,
105
+ );
106
+ const scroll = calls.props.at(-1)!.onScroll as (e: unknown) => void;
107
+ scroll({ nativeEvent: { contentOffset: { y: 0 }, contentSize: { height: 2000 }, layoutMeasurement: { height: 500 } } });
108
+ expect(onAtBottomChange).toHaveBeenLastCalledWith(false);
109
+ scroll({ nativeEvent: { contentOffset: { y: 1500 }, contentSize: { height: 2000 }, layoutMeasurement: { height: 500 } } });
110
+ expect(onAtBottomChange).toHaveBeenLastCalledWith(true);
111
+ expect(onAtBottomChange).toHaveBeenCalledTimes(2);
112
+ });
113
+
114
+ it("goes to a row it holds, centred, and says where it landed", async () => {
115
+ const { List, calls } = recordingList();
116
+ const announce = vi.fn();
117
+ (AccessibilityInfo as { announceForAccessibility?: unknown }).announceForAccessibility = announce;
118
+ render(
119
+ <GenesisModulesProvider modules={{ list: List as never }}>
120
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} jumpTo="b" jumpAnnouncement={(r) => r.text} />
121
+ </GenesisModulesProvider>,
122
+ );
123
+ await waitFor(() => expect(calls.scrollToIndex).toHaveBeenCalledWith(expect.objectContaining({ index: 1, viewPosition: 0.5 })));
124
+ expect(announce).toHaveBeenCalledWith("second");
125
+ });
126
+
127
+ it("goes to a row by its jumpId when that isn't its key, and highlights it", async () => {
128
+ const { List, calls } = recordingList();
129
+ type Sent = { key: string; serverId: string | null; text: string };
130
+ const sent: Sent[] = [
131
+ { key: "c:1", serverId: "m1", text: "first" },
132
+ { key: "c:2", serverId: "m2", text: "second" },
133
+ { key: "d:3", serverId: null, text: "Today" },
134
+ ];
135
+ render(
136
+ <GenesisModulesProvider modules={{ list: List as never }}>
137
+ <NativeThreadList<Sent>
138
+ testID="l"
139
+ data={sent}
140
+ keyExtractor={(r) => r.key}
141
+ jumpId={(r) => r.serverId}
142
+ renderItem={(r, { highlighted }) => <span data-testid={`row-${r.key}`} data-highlighted={String(highlighted)}>{r.text}</span>}
143
+ jumpTo="m2"
144
+ />
145
+ </GenesisModulesProvider>,
146
+ );
147
+ await waitFor(() => expect(calls.scrollToIndex).toHaveBeenCalledWith(expect.objectContaining({ index: 1 })));
148
+ await waitFor(() => expect(screen.getByTestId("row-c:2").getAttribute("data-highlighted")).toBe("true"));
149
+ expect(screen.getByTestId("row-c:1").getAttribute("data-highlighted")).toBe("false");
150
+ });
151
+
152
+ it("doesn't take its own scroll to a row for coming back to the bottom (which would follow the bottom again and leave the row)", async () => {
153
+ const { List, calls } = recordingList();
154
+ const onAtBottomChange = vi.fn();
155
+ render(
156
+ <GenesisModulesProvider modules={{ list: List as never }}>
157
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} jumpTo="a" onAtBottomChange={onAtBottomChange} />
158
+ </GenesisModulesProvider>,
159
+ );
160
+ await waitFor(() => expect(calls.scrollToIndex).toHaveBeenCalled());
161
+ expect(onAtBottomChange).toHaveBeenLastCalledWith(false);
162
+ // The jump's scroll starts where the list was, at the bottom: its first events say so.
163
+ const scroll = calls.props.at(-1)!.onScroll as (e: unknown) => void;
164
+ act(() => scroll({ nativeEvent: { contentOffset: { y: 1500 }, contentSize: { height: 2000 }, layoutMeasurement: { height: 500 } } }));
165
+ expect(onAtBottomChange).not.toHaveBeenCalledWith(true);
166
+ });
167
+
168
+ it("counts the reader's own drag straight away, even while the list is settling from a jump", async () => {
169
+ const { List, calls } = recordingList();
170
+ const onAtBottomChange = vi.fn();
171
+ render(
172
+ <GenesisModulesProvider modules={{ list: List as never }}>
173
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} jumpTo="c" onAtBottomChange={onAtBottomChange} />
174
+ </GenesisModulesProvider>,
175
+ );
176
+ await waitFor(() => expect(calls.scrollToIndex).toHaveBeenCalled());
177
+ const props = calls.props.at(-1)!;
178
+ const scroll = props.onScroll as (e: unknown) => void;
179
+ // Inside the settling window: the list's own movement is ignored...
180
+ act(() => scroll({ nativeEvent: { contentOffset: { y: 1500 }, contentSize: { height: 2000 }, layoutMeasurement: { height: 500 } } }));
181
+ expect(onAtBottomChange).not.toHaveBeenCalledWith(true);
182
+ // ...but a reader who takes hold and reaches the bottom counts at once.
183
+ act(() => (props.onScrollBeginDrag as () => void)());
184
+ act(() => scroll({ nativeEvent: { contentOffset: { y: 1500 }, contentSize: { height: 2000 }, layoutMeasurement: { height: 500 } } }));
185
+ expect(onAtBottomChange).toHaveBeenLastCalledWith(true);
186
+ act(() => scroll({ nativeEvent: { contentOffset: { y: 0 }, contentSize: { height: 2000 }, layoutMeasurement: { height: 500 } } }));
187
+ expect(onAtBottomChange).toHaveBeenLastCalledWith(false);
188
+ });
189
+
190
+ it("loads until a row it doesn't hold, and says when it can't be found", async () => {
191
+ const { List } = recordingList();
192
+ const onLoadUntil = vi.fn(async () => false);
193
+ const onJumpFailed = vi.fn();
194
+ render(
195
+ <GenesisModulesProvider modules={{ list: List as never }}>
196
+ <NativeThreadList testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} jumpTo="gone" onLoadUntil={onLoadUntil} onJumpFailed={onJumpFailed} />
197
+ </GenesisModulesProvider>,
198
+ );
199
+ await waitFor(() => expect(onJumpFailed).toHaveBeenCalledWith("gone"));
200
+ expect(onLoadUntil).toHaveBeenCalledWith("gone");
201
+ });
202
+
203
+ it("goes to the newest row through its handle", async () => {
204
+ const { List, calls } = recordingList();
205
+ const ref = createRef<NativeThreadListHandle>();
206
+ render(
207
+ <GenesisModulesProvider modules={{ list: List as never }}>
208
+ <NativeThreadList ref={ref} testID="l" data={rows} keyExtractor={(r) => r.id} renderItem={renderRow} />
209
+ </GenesisModulesProvider>,
210
+ );
211
+ act(() => ref.current!.scrollToEnd({ animated: false }));
212
+ await waitFor(() => expect(calls.scrollToEnd).toHaveBeenCalled());
213
+ });
214
+
215
+ it("shows the empty state when there are no rows", () => {
216
+ render(<NativeThreadList testID="l" data={[] as Row[]} keyExtractor={(r) => r.id} renderItem={renderRow} empty={<span data-testid="none" />} />);
217
+ expect(screen.getByTestId("none")).toBeTruthy();
218
+ });
219
+ });
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { type VariantProps, cva } from "class-variance-authority";
7
7
  import { ActivityIndicator, Pressable, Text, type AccessibilityState } from "react-native";
8
+ import { useHaptics, type HapticKind } from "../hooks/use-haptics";
8
9
  import { cn } from "../utils";
9
10
 
10
11
  const buttonVariants = cva(
@@ -66,6 +67,11 @@ export interface NativeButtonProps
66
67
  accessibilityHint?: string;
67
68
  /** Merged with the button's own `disabled` and `busy`: `{ selected: true }` for a vote cast, a filter on. */
68
69
  accessibilityState?: AccessibilityState;
70
+ /**
71
+ * A haptic through `GenesisModules.haptics` (`light` for a vote, `success` for a save): it plays
72
+ * when the press counts, except `select`, which ticks on press-in as `usePressFeedback` does. Default none.
73
+ */
74
+ haptic?: HapticKind | undefined;
69
75
  }
70
76
 
71
77
  function NativeButton({
@@ -78,9 +84,19 @@ function NativeButton({
78
84
  disabled,
79
85
  loading,
80
86
  accessibilityState,
87
+ haptic,
81
88
  ...props
82
89
  }: NativeButtonProps) {
83
90
  const isDisabled = disabled || loading;
91
+ const play = useHaptics();
92
+ const press =
93
+ haptic && haptic !== "select" && onPress
94
+ ? () => {
95
+ play(haptic);
96
+ onPress();
97
+ }
98
+ : onPress;
99
+ const tick = haptic === "select" && onPress ? () => play("select") : undefined;
84
100
 
85
101
  return (
86
102
  <Pressable
@@ -89,7 +105,8 @@ function NativeButton({
89
105
  isDisabled && "opacity-50",
90
106
  className
91
107
  )}
92
- onPress={onPress}
108
+ onPress={press}
109
+ onPressIn={tick}
93
110
  disabled={isDisabled}
94
111
  accessibilityRole="button"
95
112
  accessibilityState={{ ...accessibilityState, disabled: isDisabled, busy: loading }}
@@ -0,0 +1,276 @@
1
+ /**
2
+ * NativeComposerBar — the bar you write a message in: an input that grows
3
+ * with what you type (up to `maxLines`, then scrolls), a send button, and
4
+ * slots beside and above it. ThreadPage's composer; chat, comments and AI
5
+ * prompts build on it too.
6
+ *
7
+ * - **Modes:** `modes` with a `tone` each ("Reply" / "Internal note"). The
8
+ * picker sits above the input, and an `internal` tone edges the bar and
9
+ * the input in the theme's `warning` role, so a staff-only note never
10
+ * reads like a reply (the send button keeps the tint: text on `warning`
11
+ * would fail contrast). The row it sends carries the same tone (ThreadPage).
12
+ * - **Slots:** `leading` (attach), `trailing` (beside send: an emoji button),
13
+ * `above` (a reply preview, attachments waiting to send), `idleAction` (in
14
+ * Send's place while there's nothing to send: a hold-to-record mic) and
15
+ * `replaceInput` (instead of `leading` and the input: a recording's
16
+ * waveform). Attachments with no text: pass `empty={false}`.
17
+ * - **More ways to send:** `sendActions` ("Schedule"). Touch and hold Send:
18
+ * one action runs, several open a menu. Each is also an accessibility
19
+ * action on Send.
20
+ * - **Keyboard:** the bar doesn't move itself. Put it under a keyboard-aware
21
+ * container (ThreadPage does, with `GenesisModules.keyboardAvoidingView`);
22
+ * the list above it dismisses the keyboard interactively on a drag.
23
+ * - **Accessibility:** send and the mode picker are 44pt targets, the input
24
+ * is labelled by its placeholder (and says when it writes an internal
25
+ * note), Sending is announced, and the input stays editable while a
26
+ * message sends (the keyboard stays up).
27
+ *
28
+ * @stability Beta
29
+ */
30
+ import { useEffect, type ReactNode } from "react";
31
+ import { AccessibilityInfo, ActivityIndicator, Alert, Animated, Dimensions, Platform, Pressable, TextInput, View } from "react-native";
32
+ import type { ComposerMode } from "@marktiderman/genesis-core/conversation";
33
+ import { useThemeRoles } from "../hooks/use-theme-roles";
34
+ import { useGenesisModules } from "../native-modules";
35
+ import { usePressFeedback } from "../hooks/use-press-feedback";
36
+ import { NativeIcon } from "./icon";
37
+ import { NativeText } from "./text";
38
+
39
+ export type { ComposerMode, ComposerTone } from "@marktiderman/genesis-core/conversation";
40
+
41
+ export interface NativeComposerBarProps {
42
+ value: string;
43
+ onChangeText: (text: string) => void;
44
+ onSend: () => void;
45
+ /** A send is in flight: the button spins and won't send twice. */
46
+ sending?: boolean;
47
+ /** Turns sending off (besides a blank value). */
48
+ disabled?: boolean;
49
+ placeholder?: string;
50
+ /** Send's label, to VoiceOver. Default "Send". */
51
+ sendLabel?: string;
52
+ sendingLabel?: string;
53
+ maxLength?: number;
54
+ /** The input grows to this many lines, then scrolls. Default 6. */
55
+ maxLines?: number;
56
+ /** Ways to send ("Reply", "Internal note"). Two or more show the picker. */
57
+ modes?: readonly ComposerMode[];
58
+ /** The chosen mode's id. Default the first. */
59
+ mode?: string;
60
+ onModeChange?: (id: string) => void;
61
+ leading?: ReactNode;
62
+ trailing?: ReactNode;
63
+ above?: ReactNode;
64
+ /**
65
+ * Whether there's nothing to send. By default, a blank `value`; pass `false` when attachments
66
+ * are waiting and no text is needed.
67
+ */
68
+ empty?: boolean;
69
+ /** Takes Send's place (the same 44pt spot) while there's nothing to send and nothing sending: a hold-to-record mic. */
70
+ idleAction?: ReactNode;
71
+ /** Shown instead of `leading` and the input (a recording in progress). Label it yourself: it's one region to VoiceOver. */
72
+ replaceInput?: ReactNode;
73
+ /** Touch and hold Send for these (one runs straight away; several open a menu). Each is also an accessibility action on Send. */
74
+ sendActions?: readonly ComposerSendAction[];
75
+ /** Title of the menu when there are several `sendActions`. */
76
+ sendActionsTitle?: string;
77
+ /** The hint on Send when it has `sendActions`. Default "Touch and hold for more options". */
78
+ sendActionsHint?: string;
79
+ /** Passed to the input (to insert at the cursor, say). */
80
+ onSelectionChange?: (e: { nativeEvent: { selection: { start: number; end: number } } }) => void;
81
+ /** The input takes text (default). When false, nothing sends and the input reads as disabled. */
82
+ editable?: boolean;
83
+ testID?: string;
84
+ }
85
+
86
+ /** Another way to send (touch and hold Send). */
87
+ export interface ComposerSendAction {
88
+ id: string;
89
+ label: string;
90
+ onPress: () => void;
91
+ destructive?: boolean;
92
+ }
93
+
94
+ function openSendActions(actions: readonly ComposerSendAction[], title: string | undefined) {
95
+ if (actions.length === 1) return actions[0]!.onPress();
96
+ Alert.alert(title ?? "", undefined, [
97
+ ...actions.map((a) => ({ text: a.label, style: a.destructive ? ("destructive" as const) : ("default" as const), onPress: a.onPress })),
98
+ { text: "Cancel", style: "cancel" as const },
99
+ ]);
100
+ }
101
+
102
+ const LINE = 22;
103
+ const PAD_Y = 8;
104
+
105
+ export function NativeComposerBar({
106
+ value,
107
+ onChangeText,
108
+ onSend,
109
+ sending = false,
110
+ disabled = false,
111
+ placeholder = "Message",
112
+ sendLabel = "Send",
113
+ sendingLabel = "Sending",
114
+ maxLength,
115
+ maxLines = 6,
116
+ modes,
117
+ mode,
118
+ onModeChange,
119
+ leading,
120
+ trailing,
121
+ above,
122
+ empty,
123
+ idleAction,
124
+ replaceInput,
125
+ sendActions,
126
+ sendActionsTitle,
127
+ sendActionsHint = "Touch and hold for more options",
128
+ onSelectionChange,
129
+ editable = true,
130
+ testID = "composer",
131
+ }: NativeComposerBarProps) {
132
+ const colors = useThemeRoles();
133
+ const { symbol, icons } = useGenesisModules();
134
+ // No icon module: the arrow would draw nothing, so the button says its label.
135
+ const hasIcon = Boolean(symbol || icons?.["arrow-up"]);
136
+ const current = modes?.find((m) => m.id === mode) ?? modes?.[0];
137
+ const internal = current?.tone === "internal";
138
+ const blank = empty ?? !value.trim();
139
+ const canSend = !blank && !disabled && !sending && editable;
140
+ const actions = sendActions?.length ? sendActions : null;
141
+ const idle = idleAction != null && blank && !sending;
142
+ const sendPress = usePressFeedback({ haptic: "light", scale: 0.9, disabled: !canSend });
143
+ // A multiline input grows with its text by itself; this caps it, after which it scrolls.
144
+ // Lines grow with the person's text size (Dynamic Type, Android font scale).
145
+ const fontScale = Dimensions.get("window").fontScale || 1;
146
+ const maxHeight = Math.ceil(LINE * fontScale) * maxLines + PAD_Y * 2;
147
+ // Say "Sending" on iOS too (a live region is Android-only).
148
+ useEffect(() => {
149
+ if (sending && Platform.OS === "ios") (AccessibilityInfo as { announceForAccessibility?: (t: string) => void }).announceForAccessibility?.(sendingLabel);
150
+ }, [sending, sendingLabel]);
151
+
152
+ return (
153
+ <View
154
+ testID={testID}
155
+ style={{
156
+ paddingHorizontal: 12,
157
+ paddingTop: 8,
158
+ paddingBottom: 8,
159
+ gap: 6,
160
+ backgroundColor: colors.groupedBackground,
161
+ borderTopWidth: internal ? 2 : 0,
162
+ borderTopColor: colors.warning,
163
+ }}
164
+ >
165
+ {modes && modes.length > 1 ? (
166
+ <View testID={`${testID}-modes`} accessibilityRole="tablist" style={{ flexDirection: "row", gap: 4 }}>
167
+ {modes.map((m) => {
168
+ const on = m.id === current?.id;
169
+ return (
170
+ <Pressable
171
+ key={m.id}
172
+ testID={`${testID}-mode-${m.id}`}
173
+ accessibilityRole="tab"
174
+ accessibilityState={{ selected: on }}
175
+ accessibilityLabel={m.label}
176
+ onPress={() => onModeChange?.(m.id)}
177
+ style={{
178
+ minHeight: 44,
179
+ justifyContent: "center",
180
+ paddingHorizontal: 12,
181
+ borderRadius: 22,
182
+ backgroundColor: on ? colors.fill : "transparent",
183
+ borderWidth: m.tone === "internal" ? 1 : 0,
184
+ borderColor: colors.warning,
185
+ }}
186
+ >
187
+ <NativeText preset="label" style={{ color: on ? colors.label : colors.secondaryLabel }}>
188
+ {m.label}
189
+ </NativeText>
190
+ </Pressable>
191
+ );
192
+ })}
193
+ </View>
194
+ ) : null}
195
+ {above}
196
+ <View style={{ flexDirection: "row", alignItems: "flex-end", gap: 8 }}>
197
+ {replaceInput != null ? (
198
+ <View style={{ flex: 1, minHeight: 44, justifyContent: "center" }}>{replaceInput}</View>
199
+ ) : (
200
+ <>
201
+ {leading}
202
+ <TextInput
203
+ testID={`${testID}-input`}
204
+ value={value}
205
+ onChangeText={onChangeText}
206
+ placeholder={internal ? current!.label : placeholder}
207
+ placeholderTextColor={colors.tertiaryLabel as string}
208
+ accessibilityLabel={internal ? current!.label : placeholder}
209
+ accessibilityState={editable ? undefined : { disabled: true }}
210
+ editable={editable}
211
+ onSelectionChange={onSelectionChange}
212
+ multiline
213
+ maxLength={maxLength}
214
+ style={{
215
+ flex: 1,
216
+ minHeight: 44,
217
+ maxHeight,
218
+ textAlignVertical: "center",
219
+ paddingHorizontal: 14,
220
+ paddingTop: PAD_Y,
221
+ paddingBottom: PAD_Y,
222
+ borderRadius: 22,
223
+ fontSize: 17,
224
+ lineHeight: LINE,
225
+ color: colors.label as string,
226
+ backgroundColor: colors.surface,
227
+ borderWidth: internal ? 1 : 0,
228
+ borderColor: colors.warning,
229
+ opacity: editable ? 1 : 0.6,
230
+ }}
231
+ />
232
+ </>
233
+ )}
234
+ {trailing}
235
+ {idle ? (
236
+ <View testID={`${testID}-idle`} style={{ minWidth: 44, height: 44, alignItems: "center", justifyContent: "center" }}>
237
+ {idleAction}
238
+ </View>
239
+ ) : sending ? (
240
+ <View testID={`${testID}-sending`} accessible accessibilityLabel={sendingLabel} accessibilityLiveRegion="polite" style={{ width: 44, height: 44, alignItems: "center", justifyContent: "center" }}>
241
+ <ActivityIndicator />
242
+ </View>
243
+ ) : (
244
+ <Animated.View style={sendPress.style}>
245
+ <Pressable
246
+ testID={`${testID}-send`}
247
+ accessibilityRole="button"
248
+ accessibilityLabel={sendLabel}
249
+ accessibilityState={{ disabled: !canSend }}
250
+ accessibilityHint={actions ? sendActionsHint : undefined}
251
+ accessibilityActions={actions && canSend ? actions.map((a) => ({ name: a.id, label: a.label })) : undefined}
252
+ onAccessibilityAction={actions ? (e) => actions.find((a) => a.id === e.nativeEvent.actionName)?.onPress() : undefined}
253
+ onLongPress={actions ? () => openSendActions(actions, sendActionsTitle) : undefined}
254
+ disabled={!canSend}
255
+ onPressIn={sendPress.onPressIn}
256
+ onPressOut={sendPress.onPressOut}
257
+ onPress={() => {
258
+ sendPress.confirm();
259
+ onSend();
260
+ }}
261
+ style={{ minWidth: 44, height: 44, paddingHorizontal: hasIcon ? 0 : 14, borderRadius: 22, alignItems: "center", justifyContent: "center", backgroundColor: canSend ? colors.tint : colors.fill }}
262
+ >
263
+ {hasIcon ? (
264
+ <NativeIcon name="arrow-up" size={20} color={canSend ? colors.background : colors.tertiaryLabel} />
265
+ ) : (
266
+ <NativeText preset="label" className={canSend ? "text-primary-foreground" : undefined} style={canSend ? undefined : { color: colors.tertiaryLabel }}>
267
+ {sendLabel}
268
+ </NativeText>
269
+ )}
270
+ </Pressable>
271
+ </Animated.View>
272
+ )}
273
+ </View>
274
+ </View>
275
+ );
276
+ }
@@ -26,7 +26,7 @@ import {
26
26
  } from "react-native";
27
27
  import { SafeAreaInsetsContext } from "react-native-safe-area-context";
28
28
  import { cn } from "../utils";
29
- import { useReducedMotion } from "../hooks/use-reduced-motion";
29
+ import { useMotion } from "../hooks/use-motion";
30
30
  import { useGenesisModules, type GenesisReanimatedModule } from "../native-modules";
31
31
 
32
32
  export interface NativeDrawerProps {
@@ -41,8 +41,6 @@ export interface NativeDrawerProps {
41
41
  testID?: string;
42
42
  }
43
43
 
44
- const OPEN_MS = 220;
45
- const SETTLE_MS = 180;
46
44
 
47
45
  export function NativeDrawer(props: NativeDrawerProps) {
48
46
  const { reanimated } = useGenesisModules();
@@ -86,14 +84,18 @@ function useSwipe(
86
84
  function ReanimatedDrawer({ reanimated: R, ...props }: NativeDrawerProps & { reanimated: GenesisReanimatedModule }) {
87
85
  const { open, side = "left", width } = props;
88
86
  const drawerWidth = width ?? Math.min(Dimensions.get("window").width * 0.8, 360);
89
- const reducedMotion = useReducedMotion();
87
+ // The shared motion tokens: a panel opens at `base`, a released drag settles at `fast`; Reduce Motion snaps.
88
+ const motion = useMotion();
89
+ const reducedMotion = motion.reduced;
90
+ const OPEN_MS = motion.duration.base;
91
+ const SETTLE_MS = motion.duration.fast;
90
92
  const translate = R.useSharedValue(closedOffset(side, drawerWidth));
91
93
 
92
94
  useEffect(() => {
93
95
  const to = open ? 0 : closedOffset(side, drawerWidth);
94
96
  translate.value = reducedMotion ? to : R.withTiming(to, { duration: OPEN_MS });
95
97
  // eslint-disable-next-line react-hooks/exhaustive-deps
96
- }, [drawerWidth, open, reducedMotion, side]);
98
+ }, [drawerWidth, open, reducedMotion, side, OPEN_MS]);
97
99
 
98
100
  // `translate` and `R` are stable for the component's life.
99
101
  const follow = useCallback((dx: number) => {
@@ -103,7 +105,7 @@ function ReanimatedDrawer({ reanimated: R, ...props }: NativeDrawerProps & { rea
103
105
  const settle = useCallback(() => {
104
106
  translate.value = reducedMotion ? 0 : R.withTiming(0, { duration: SETTLE_MS });
105
107
  // eslint-disable-next-line react-hooks/exhaustive-deps
106
- }, [reducedMotion]);
108
+ }, [reducedMotion, SETTLE_MS]);
107
109
  const panResponder = useSwipe(side, drawerWidth, props.onOpenChange, follow, settle);
108
110
  const animatedStyle = R.useAnimatedStyle(() => {
109
111
  "worklet";
@@ -116,7 +118,11 @@ function ReanimatedDrawer({ reanimated: R, ...props }: NativeDrawerProps & { rea
116
118
  function AnimatedDrawer(props: NativeDrawerProps) {
117
119
  const { open, side = "left", width } = props;
118
120
  const drawerWidth = width ?? Math.min(Dimensions.get("window").width * 0.8, 360);
119
- const reducedMotion = useReducedMotion();
121
+ // The shared motion tokens: a panel opens at `base`, a released drag settles at `fast`; Reduce Motion snaps.
122
+ const motion = useMotion();
123
+ const reducedMotion = motion.reduced;
124
+ const OPEN_MS = motion.duration.base;
125
+ const SETTLE_MS = motion.duration.fast;
120
126
  const translate = useRef(new Animated.Value(closedOffset(side, drawerWidth))).current;
121
127
 
122
128
  useEffect(() => {
@@ -125,7 +131,7 @@ function AnimatedDrawer(props: NativeDrawerProps) {
125
131
  duration: reducedMotion ? 0 : OPEN_MS,
126
132
  useNativeDriver: true,
127
133
  }).start();
128
- }, [drawerWidth, open, reducedMotion, side, translate]);
134
+ }, [drawerWidth, open, reducedMotion, side, translate, OPEN_MS]);
129
135
 
130
136
  const follow = useCallback((dx: number) => translate.setValue(dx), [translate]);
131
137
  const settle = useCallback(
@@ -135,7 +141,7 @@ function AnimatedDrawer(props: NativeDrawerProps) {
135
141
  duration: reducedMotion ? 0 : SETTLE_MS,
136
142
  useNativeDriver: true,
137
143
  }).start(),
138
- [reducedMotion, translate]
144
+ [reducedMotion, translate, SETTLE_MS]
139
145
  );
140
146
  const panResponder = useSwipe(side, drawerWidth, props.onOpenChange, follow, settle);
141
147