@marktiderman/genesis-ui-native 3.6.0 → 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 (47) hide show
  1. package/README.md +44 -0
  2. package/dist/{chunk-AGTBABAH.js → chunk-3KFUS7O6.js} +4 -4
  3. package/dist/{chunk-AGTBABAH.js.map → chunk-3KFUS7O6.js.map} +1 -1
  4. package/dist/{chunk-2Z72MYHB.js → chunk-7NDKIIOT.js} +5 -5
  5. package/dist/{chunk-2Z72MYHB.js.map → chunk-7NDKIIOT.js.map} +1 -1
  6. package/dist/chunk-CAI7LGN6.js +39 -0
  7. package/dist/chunk-CAI7LGN6.js.map +1 -0
  8. package/dist/{chunk-FUMSL7VZ.js → chunk-GBNIBHSU.js} +6 -6
  9. package/dist/{chunk-FUMSL7VZ.js.map → chunk-GBNIBHSU.js.map} +1 -1
  10. package/dist/{chunk-SEJ6RBP7.js → chunk-IXC3LO2K.js} +100 -51
  11. package/dist/chunk-IXC3LO2K.js.map +1 -0
  12. package/dist/{chunk-NDXNSSM6.js → chunk-KH2RVAI5.js} +3 -4
  13. package/dist/chunk-KH2RVAI5.js.map +1 -0
  14. package/dist/{chunk-6PGLX6ET.js → chunk-O4BMDV7I.js} +14 -16
  15. package/dist/chunk-O4BMDV7I.js.map +1 -0
  16. package/dist/{chunk-4OQOJ2OC.js → chunk-RTYO24SC.js} +30 -5
  17. package/dist/chunk-RTYO24SC.js.map +1 -0
  18. package/dist/{chunk-ZRQAFFTN.js → chunk-YWDDDYDI.js} +2 -2
  19. package/dist/{chunk-ZRQAFFTN.js.map → chunk-YWDDDYDI.js.map} +1 -1
  20. package/dist/components/index.d.ts +55 -10
  21. package/dist/components/index.js +6 -5
  22. package/dist/data/index.js +4 -4
  23. package/dist/hooks/index.d.ts +32 -3
  24. package/dist/hooks/index.js +3 -2
  25. package/dist/icons/lucide.d.ts +1 -1
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +9 -8
  28. package/dist/layouts/index.js +6 -5
  29. package/dist/{native-modules-Cl3zw3kh.d.ts → native-modules-DEJJQhDx.d.ts} +29 -1
  30. package/package.json +25 -2
  31. package/src/__tests__/doctor-rules.test.ts +27 -0
  32. package/src/components/__tests__/button-haptic.test.tsx +52 -0
  33. package/src/components/__tests__/composer-bar.test.tsx +24 -0
  34. package/src/components/__tests__/thread-list.test.tsx +63 -0
  35. package/src/components/button.tsx +18 -1
  36. package/src/components/composer-bar.tsx +101 -23
  37. package/src/components/index.ts +1 -1
  38. package/src/components/thread-list.tsx +43 -13
  39. package/src/hooks/__tests__/use-haptics.test.tsx +146 -0
  40. package/src/hooks/index.ts +2 -0
  41. package/src/hooks/use-haptics.ts +64 -0
  42. package/src/hooks/use-press-feedback.ts +87 -0
  43. package/src/native-modules.tsx +4 -0
  44. package/dist/chunk-4OQOJ2OC.js.map +0 -1
  45. package/dist/chunk-6PGLX6ET.js.map +0 -1
  46. package/dist/chunk-NDXNSSM6.js.map +0 -1
  47. package/dist/chunk-SEJ6RBP7.js.map +0 -1
@@ -124,6 +124,69 @@ describe("NativeThreadList", () => {
124
124
  expect(announce).toHaveBeenCalledWith("second");
125
125
  });
126
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
+
127
190
  it("loads until a row it doesn't hold, and says when it can't be found", async () => {
128
191
  const { List } = recordingList();
129
192
  const onLoadUntil = vi.fn(async () => false);
@@ -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 }}
@@ -9,8 +9,14 @@
9
9
  * the input in the theme's `warning` role, so a staff-only note never
10
10
  * reads like a reply (the send button keeps the tint: text on `warning`
11
11
  * would fail contrast). The row it sends carries the same tone (ThreadPage).
12
- * - **Slots:** `leading` (attach), `trailing` (beside send: a mic), `above`
13
- * (a reply preview, attachments waiting to send).
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.
14
20
  * - **Keyboard:** the bar doesn't move itself. Put it under a keyboard-aware
15
21
  * container (ThreadPage does, with `GenesisModules.keyboardAvoidingView`);
16
22
  * the list above it dismisses the keyboard interactively on a drag.
@@ -22,10 +28,11 @@
22
28
  * @stability Beta
23
29
  */
24
30
  import { useEffect, type ReactNode } from "react";
25
- import { AccessibilityInfo, ActivityIndicator, Dimensions, Platform, Pressable, TextInput, View } from "react-native";
31
+ import { AccessibilityInfo, ActivityIndicator, Alert, Animated, Dimensions, Platform, Pressable, TextInput, View } from "react-native";
26
32
  import type { ComposerMode } from "@marktiderman/genesis-core/conversation";
27
33
  import { useThemeRoles } from "../hooks/use-theme-roles";
28
34
  import { useGenesisModules } from "../native-modules";
35
+ import { usePressFeedback } from "../hooks/use-press-feedback";
29
36
  import { NativeIcon } from "./icon";
30
37
  import { NativeText } from "./text";
31
38
 
@@ -54,9 +61,44 @@ export interface NativeComposerBarProps {
54
61
  leading?: ReactNode;
55
62
  trailing?: ReactNode;
56
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;
57
83
  testID?: string;
58
84
  }
59
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
+
60
102
  const LINE = 22;
61
103
  const PAD_Y = 8;
62
104
 
@@ -77,6 +119,14 @@ export function NativeComposerBar({
77
119
  leading,
78
120
  trailing,
79
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,
80
130
  testID = "composer",
81
131
  }: NativeComposerBarProps) {
82
132
  const colors = useThemeRoles();
@@ -85,8 +135,11 @@ export function NativeComposerBar({
85
135
  const hasIcon = Boolean(symbol || icons?.["arrow-up"]);
86
136
  const current = modes?.find((m) => m.id === mode) ?? modes?.[0];
87
137
  const internal = current?.tone === "internal";
88
- const blank = !value.trim();
89
- const canSend = !blank && !disabled && !sending;
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 });
90
143
  // A multiline input grows with its text by itself; this caps it, after which it scrolls.
91
144
  // Lines grow with the person's text size (Dynamic Type, Android font scale).
92
145
  const fontScale = Dimensions.get("window").fontScale || 1;
@@ -141,6 +194,10 @@ export function NativeComposerBar({
141
194
  ) : null}
142
195
  {above}
143
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
+ <>
144
201
  {leading}
145
202
  <TextInput
146
203
  testID={`${testID}-input`}
@@ -149,6 +206,9 @@ export function NativeComposerBar({
149
206
  placeholder={internal ? current!.label : placeholder}
150
207
  placeholderTextColor={colors.tertiaryLabel as string}
151
208
  accessibilityLabel={internal ? current!.label : placeholder}
209
+ accessibilityState={editable ? undefined : { disabled: true }}
210
+ editable={editable}
211
+ onSelectionChange={onSelectionChange}
152
212
  multiline
153
213
  maxLength={maxLength}
154
214
  style={{
@@ -166,31 +226,49 @@ export function NativeComposerBar({
166
226
  backgroundColor: colors.surface,
167
227
  borderWidth: internal ? 1 : 0,
168
228
  borderColor: colors.warning,
229
+ opacity: editable ? 1 : 0.6,
169
230
  }}
170
231
  />
232
+ </>
233
+ )}
171
234
  {trailing}
172
- {sending ? (
235
+ {idle ? (
236
+ <View testID={`${testID}-idle`} style={{ minWidth: 44, height: 44, alignItems: "center", justifyContent: "center" }}>
237
+ {idleAction}
238
+ </View>
239
+ ) : sending ? (
173
240
  <View testID={`${testID}-sending`} accessible accessibilityLabel={sendingLabel} accessibilityLiveRegion="polite" style={{ width: 44, height: 44, alignItems: "center", justifyContent: "center" }}>
174
241
  <ActivityIndicator />
175
242
  </View>
176
243
  ) : (
177
- <Pressable
178
- testID={`${testID}-send`}
179
- accessibilityRole="button"
180
- accessibilityLabel={sendLabel}
181
- accessibilityState={{ disabled: !canSend }}
182
- disabled={!canSend}
183
- onPress={onSend}
184
- style={{ minWidth: 44, height: 44, paddingHorizontal: hasIcon ? 0 : 14, borderRadius: 22, alignItems: "center", justifyContent: "center", backgroundColor: canSend ? colors.tint : colors.fill }}
185
- >
186
- {hasIcon ? (
187
- <NativeIcon name="arrow-up" size={20} color={canSend ? colors.background : colors.tertiaryLabel} />
188
- ) : (
189
- <NativeText preset="label" className={canSend ? "text-primary-foreground" : undefined} style={canSend ? undefined : { color: colors.tertiaryLabel }}>
190
- {sendLabel}
191
- </NativeText>
192
- )}
193
- </Pressable>
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>
194
272
  )}
195
273
  </View>
196
274
  </View>
@@ -306,7 +306,7 @@ export {
306
306
  } from "./thread-list";
307
307
  export type { NativeThreadListProps, NativeThreadListHandle, ThreadRowInfo } from "./thread-list";
308
308
  export { NativeComposerBar } from "./composer-bar";
309
- export type { NativeComposerBarProps, ComposerMode, ComposerTone } from "./composer-bar";
309
+ export type { NativeComposerBarProps, ComposerMode, ComposerTone, ComposerSendAction } from "./composer-bar";
310
310
 
311
311
  // --- Gallery and media primitives ---
312
312
 
@@ -112,6 +112,13 @@ export interface NativeThreadListProps<T> {
112
112
  renderEarlier?: (props: { loading: boolean; onPress: () => void; label: string; testID: string }) => ReactNode;
113
113
  /** Go to this row, loading earlier pages with `onLoadUntil` until it's here. A new id, or the same one after `null`, goes again. */
114
114
  jumpTo?: string | null;
115
+ /**
116
+ * The id `jumpTo` names a row by, when it isn't the row's key: a message keyed by the id the
117
+ * phone gave it (so it keeps its row when the server's copy lands) and gone to by the server's
118
+ * id. `null` for a row that can't be gone to (a day heading). `keyExtractor` by default.
119
+ * Pass a stable function (module scope, or `useCallback`): a new one each render re-renders every row.
120
+ */
121
+ jumpId?: (row: T) => string | null | undefined;
115
122
  /** Load earlier pages until the row is held; resolve false when it can't be found. */
116
123
  onLoadUntil?: (id: string) => Promise<boolean>;
117
124
  /** What VoiceOver says on arriving at `jumpTo`. */
@@ -147,6 +154,7 @@ interface ThreadListComponentProps {
147
154
  contentContainerStyle?: Record<string, unknown>;
148
155
  maintainVisibleContentPosition?: Record<string, unknown>;
149
156
  onScroll?: (e: { nativeEvent: ScrollMetrics }) => void;
157
+ onScrollBeginDrag?: () => void;
150
158
  scrollEventThrottle?: number;
151
159
  onContentSizeChange?: () => void;
152
160
  onLayout?: () => void;
@@ -175,6 +183,7 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
175
183
  earlierLabel = "Load earlier messages",
176
184
  renderEarlier,
177
185
  jumpTo,
186
+ jumpId,
178
187
  onLoadUntil,
179
188
  jumpAnnouncement,
180
189
  onJumpFailed,
@@ -214,9 +223,11 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
214
223
  const pending = timers.current;
215
224
  return () => pending.forEach(clearTimeout);
216
225
  }, []);
217
- const latest = useRef({ data, keyExtractor, jumpAnnouncement, onJumpFailed, onAtBottomChange });
218
- latest.current = { data, keyExtractor, jumpAnnouncement, onJumpFailed, onAtBottomChange };
219
- const indexOf = useCallback((id: string) => latest.current.data.findIndex((row) => latest.current.keyExtractor(row) === id), []);
226
+ const idOf = jumpId ?? keyExtractor;
227
+ const latest = useRef({ data, idOf, jumpAnnouncement, onJumpFailed, onAtBottomChange });
228
+ latest.current = { data, idOf, jumpAnnouncement, onJumpFailed, onAtBottomChange };
229
+ // The row a jump names, by `jumpId` (the key by default).
230
+ const indexOf = useCallback((id: string) => latest.current.data.findIndex((row) => latest.current.idOf(row) === id), []);
220
231
 
221
232
  const setAtBottom = useCallback((v: boolean) => {
222
233
  if (atBottom.current === v) return;
@@ -255,7 +266,10 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
255
266
  (id: string) => {
256
267
  const scroll = () => {
257
268
  const at = indexOf(id);
258
- if (at >= 0) listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
269
+ if (at < 0) return;
270
+ // Each try moves the list again: its events don't count until this one settles.
271
+ settlingUntil.current = Date.now() + SETTLING_MS;
272
+ listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
259
273
  };
260
274
  jumpTries.current = { id, tries: 0 };
261
275
  settlingUntil.current = Date.now() + SETTLING_MS;
@@ -281,10 +295,17 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
281
295
  },
282
296
  onLanded: (id) => {
283
297
  // A jump to a row already at the bottom moves nothing, so no scroll event says so: look once it settles.
298
+ // Not before the list's own scrolling has settled (a second try extends it): mid-way, it can still read as the bottom.
284
299
  if (recheck.current) clearTimeout(recheck.current);
285
- recheck.current = setTimeout(() => {
300
+ const look = () => {
301
+ const wait = settlingUntil.current - Date.now();
302
+ if (wait > 0) {
303
+ recheck.current = setTimeout(look, wait + 50);
304
+ return;
305
+ }
286
306
  if (metrics.current && threadNearBottom(metrics.current)) setAtBottom(true);
287
- }, SETTLING_MS + 50);
307
+ };
308
+ recheck.current = setTimeout(look, SETTLING_MS + 50);
288
309
  const at = indexOf(id);
289
310
  const said = at >= 0 ? latest.current.jumpAnnouncement?.(latest.current.data[at]!) : undefined;
290
311
  if (said) announce(said);
@@ -310,8 +331,8 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
310
331
  );
311
332
 
312
333
  const renderListItem = useCallback(
313
- ({ item, index }: { item: unknown; index: number }) => renderItem(item as T, { index, highlighted: highlightedId !== null && keyExtractor(item as T) === highlightedId }),
314
- [highlightedId, keyExtractor, renderItem],
334
+ ({ item, index }: { item: unknown; index: number }) => renderItem(item as T, { index, highlighted: highlightedId !== null && idOf(item as T) === highlightedId }),
335
+ [highlightedId, idOf, renderItem],
315
336
  );
316
337
  const listKey = useCallback((row: unknown) => keyExtractor(row as T), [keyExtractor]);
317
338
  const listItemType = useMemo(() => (getItemType ? (row: unknown) => getItemType(row as T) : undefined), [getItemType]);
@@ -320,13 +341,19 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
320
341
  metrics.current = { contentOffset: { y: e.nativeEvent.contentOffset.y }, contentSize: { height: e.nativeEvent.contentSize.height }, layoutMeasurement: { height: e.nativeEvent.layoutMeasurement.height } };
321
342
  const height = e.nativeEvent.layoutMeasurement.height;
322
343
  setViewport((v) => (Math.abs(v - height) < 1 ? v : height));
323
- const near = threadNearBottom(e.nativeEvent);
324
- // The list's own scroll (to the newest, to a row) passes through "not at the bottom": ignore that.
325
- if (!near && Date.now() < settlingUntil.current) return;
326
- setAtBottom(near);
344
+ // The list's own scroll (to the newest, to a row) isn't the reader moving. Going to a row starts
345
+ // at the bottom, so its first events say "at the bottom": taken, that turned following back on,
346
+ // and FlatList's next layout scrolled to the end, away from the row. After a jump, onLanded
347
+ // looks again once it has settled.
348
+ if (Date.now() < settlingUntil.current) return;
349
+ setAtBottom(threadNearBottom(e.nativeEvent));
327
350
  },
328
351
  [setAtBottom],
329
352
  );
353
+ // The reader's touch ends the list's own scroll: from here their scrolling counts, even mid-jump.
354
+ const onScrollBeginDrag = useCallback(() => {
355
+ settlingUntil.current = 0;
356
+ }, []);
330
357
  const onScrollToIndexFailed = useCallback(
331
358
  ({ index, averageItemLength }: { index: number; averageItemLength: number }) => {
332
359
  // FlatList hasn't measured that far up yet: get near it, then try again by id (three times at most).
@@ -336,7 +363,9 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
336
363
  target.tries += 1;
337
364
  later(() => {
338
365
  const at = indexOf(target.id);
339
- if (at >= 0) listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
366
+ if (at < 0) return;
367
+ settlingUntil.current = Date.now() + SETTLING_MS;
368
+ listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
340
369
  }, 250);
341
370
  },
342
371
  [indexOf, later, reducedMotion],
@@ -381,6 +410,7 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
381
410
  maintainVisibleContentPosition={mode.maintainVisibleContentPosition}
382
411
  scrollEventThrottle={32}
383
412
  onScroll={onScroll}
413
+ onScrollBeginDrag={onScrollBeginDrag}
384
414
  onScrollToIndexFailed={onScrollToIndexFailed}
385
415
  {...(mode.followsByHand ? { onContentSizeChange: follow, onLayout: follow } : {})}
386
416
  ListHeaderComponent={listHeader}
@@ -0,0 +1,146 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import type { ReactNode } from "react";
3
+ import { act, renderHook, waitFor } from "@testing-library/react";
4
+ import { AccessibilityInfo, Animated } from "react-native";
5
+ import { GenesisModulesProvider } from "../../native-modules";
6
+ import { playHaptic, useHaptics, type GenesisHapticsModule } from "../use-haptics";
7
+ import { usePressFeedback } from "../use-press-feedback";
8
+ import { __resetReducedMotion } from "../use-reduced-motion";
9
+
10
+ function fakeHaptics(overrides: Partial<GenesisHapticsModule> = {}) {
11
+ return {
12
+ impactAsync: vi.fn(() => Promise.resolve()),
13
+ selectionAsync: vi.fn(() => Promise.resolve()),
14
+ notificationAsync: vi.fn(() => Promise.resolve()),
15
+ ImpactFeedbackStyle: { Light: "light", Medium: "medium", Heavy: "heavy" },
16
+ NotificationFeedbackType: { Success: "success", Warning: "warning", Error: "error" },
17
+ ...overrides,
18
+ };
19
+ }
20
+
21
+ const withHaptics = (haptics: GenesisHapticsModule) =>
22
+ function Wrapper({ children }: { children: ReactNode }) {
23
+ return <GenesisModulesProvider modules={{ haptics }}>{children}</GenesisModulesProvider>;
24
+ };
25
+
26
+ afterEach(() => {
27
+ vi.restoreAllMocks();
28
+ __resetReducedMotion();
29
+ });
30
+
31
+ describe("playHaptic", () => {
32
+ it.each([
33
+ ["light", "impactAsync", "light"],
34
+ ["medium", "impactAsync", "medium"],
35
+ ["heavy", "impactAsync", "heavy"],
36
+ ["success", "notificationAsync", "success"],
37
+ ["warning", "notificationAsync", "warning"],
38
+ ["error", "notificationAsync", "error"],
39
+ ] as const)("plays %s through %s", (kind, method, style) => {
40
+ const h = fakeHaptics();
41
+ playHaptic(h, kind);
42
+ expect(h[method]).toHaveBeenCalledWith(style);
43
+ });
44
+
45
+ it("plays select as a selection tick", () => {
46
+ const h = fakeHaptics();
47
+ playHaptic(h, "select");
48
+ expect(h.selectionAsync).toHaveBeenCalled();
49
+ });
50
+
51
+ it("falls back to medium when the module has no heavy style", () => {
52
+ const h = fakeHaptics({ ImpactFeedbackStyle: { Light: "light", Medium: "medium" } });
53
+ playHaptic(h, "heavy");
54
+ expect(h.impactAsync).toHaveBeenCalledWith("medium");
55
+ });
56
+
57
+ it("does nothing without a module", () => {
58
+ expect(() => playHaptic(undefined, "light")).not.toThrow();
59
+ });
60
+
61
+ it("never throws or rejects", async () => {
62
+ const throws = fakeHaptics({ impactAsync: vi.fn(() => { throw new Error("no engine"); }) });
63
+ expect(() => playHaptic(throws, "light")).not.toThrow();
64
+ const rejects = fakeHaptics({ selectionAsync: vi.fn(() => Promise.reject(new Error("no engine"))) });
65
+ playHaptic(rejects, "select");
66
+ await act(async () => {});
67
+ });
68
+ });
69
+
70
+ describe("useHaptics", () => {
71
+ it("plays through the app's GenesisModules.haptics", () => {
72
+ const h = fakeHaptics();
73
+ const { result } = renderHook(() => useHaptics(), { wrapper: withHaptics(h) });
74
+ result.current("success");
75
+ expect(h.notificationAsync).toHaveBeenCalledWith("success");
76
+ });
77
+
78
+ it("is a no-op without the module", () => {
79
+ const { result } = renderHook(() => useHaptics());
80
+ expect(() => result.current("light")).not.toThrow();
81
+ });
82
+ });
83
+
84
+ describe("usePressFeedback", () => {
85
+ it("shrinks while held and plays its haptic only when the press counts", async () => {
86
+ vi.spyOn(AccessibilityInfo, "isReduceMotionEnabled").mockResolvedValue(false);
87
+ const timing = vi.spyOn(Animated, "timing");
88
+ const spring = vi.spyOn(Animated, "spring");
89
+ const h = fakeHaptics();
90
+ const { result } = renderHook(() => usePressFeedback({ haptic: "light" }), { wrapper: withHaptics(h) });
91
+ await act(async () => {});
92
+ expect(result.current.style.transform).toHaveLength(1);
93
+ result.current.onPressIn();
94
+ expect(timing).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ toValue: 0.97, useNativeDriver: true }));
95
+ result.current.onPressOut();
96
+ expect(spring).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ toValue: 1, damping: 30, stiffness: 400 }));
97
+ expect(h.impactAsync).not.toHaveBeenCalled();
98
+ result.current.confirm();
99
+ expect(h.impactAsync).toHaveBeenCalledWith("light");
100
+ });
101
+
102
+ it("ticks on press-in for select", () => {
103
+ const h = fakeHaptics();
104
+ const { result } = renderHook(() => usePressFeedback({ haptic: "select" }), { wrapper: withHaptics(h) });
105
+ result.current.onPressIn();
106
+ expect(h.selectionAsync).toHaveBeenCalledTimes(1);
107
+ result.current.confirm();
108
+ expect(h.selectionAsync).toHaveBeenCalledTimes(1);
109
+ });
110
+
111
+ it("dims instead of moving under Reduce Motion, and never springs", async () => {
112
+ vi.spyOn(AccessibilityInfo, "isReduceMotionEnabled").mockResolvedValue(true);
113
+ const timing = vi.spyOn(Animated, "timing");
114
+ const spring = vi.spyOn(Animated, "spring");
115
+ const { result } = renderHook(() => usePressFeedback());
116
+ await waitFor(() => expect(result.current.style.opacity).toBeDefined());
117
+ expect(result.current.style.transform).toBeUndefined();
118
+ result.current.onPressIn();
119
+ expect(timing).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ toValue: 0.6 }));
120
+ result.current.onPressOut();
121
+ expect(timing).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ toValue: 1 }));
122
+ expect(spring).not.toHaveBeenCalled();
123
+ });
124
+
125
+ it("gives no feedback when disabled", () => {
126
+ const timing = vi.spyOn(Animated, "timing");
127
+ const h = fakeHaptics();
128
+ const { result } = renderHook(() => usePressFeedback({ haptic: "light", disabled: true }), { wrapper: withHaptics(h) });
129
+ expect(result.current.style).toEqual({});
130
+ result.current.onPressIn();
131
+ result.current.confirm();
132
+ expect(timing).not.toHaveBeenCalled();
133
+ expect(h.impactAsync).not.toHaveBeenCalled();
134
+ });
135
+ });
136
+
137
+ describe("usePressFeedback, disabled mid-press", () => {
138
+ it("comes back to rest when disabled while held", () => {
139
+ const { result, rerender } = renderHook(({ disabled }) => usePressFeedback({ disabled }), { initialProps: { disabled: false } });
140
+ const value = result.current.style.transform?.[0]?.scale as unknown as { setValue: (v: number) => void };
141
+ const reset = vi.spyOn(value, "setValue");
142
+ result.current.onPressIn();
143
+ rerender({ disabled: true });
144
+ expect(reset).toHaveBeenCalledWith(1);
145
+ });
146
+ });
@@ -9,6 +9,8 @@
9
9
  export { useReducedMotion } from "./use-reduced-motion";
10
10
  // The jump is the shared conversation contract's (genesis-core), re-exported here.
11
11
  export { useThreadJump, JUMP_SETTLE_MS, type UseThreadJumpOptions } from "@marktiderman/genesis-core/conversation";
12
+ export { useHaptics, playHaptic, type HapticKind, type GenesisHapticsModule } from "./use-haptics";
13
+ export { usePressFeedback, type PressFeedbackOptions, type PressFeedback } from "./use-press-feedback";
12
14
  export { useMotion, animateMotion, motionSpring, motionTiming, type UseMotionOptions, type MotionHow, type MotionSpringConfig, type MotionTimingConfig } from "./use-motion";
13
15
  export { useThemeMode, type ThemeMode } from "./use-theme-mode";
14
16
  export { useThemeRoles, type ThemeRoleColors, type UseThemeRolesOptions } from "./use-theme-roles";