@marktiderman/genesis-ui-native 3.6.0 → 3.8.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 (90) hide show
  1. package/README.md +48 -1
  2. package/dist/{chunk-NDXNSSM6.js → chunk-DHONOH6K.js} +24 -211
  3. package/dist/chunk-DHONOH6K.js.map +1 -0
  4. package/dist/{chunk-6PGLX6ET.js → chunk-FGIIBON3.js} +334 -24
  5. package/dist/chunk-FGIIBON3.js.map +1 -0
  6. package/dist/{chunk-ZRQAFFTN.js → chunk-FOJJB6AB.js} +2 -2
  7. package/dist/{chunk-ZRQAFFTN.js.map → chunk-FOJJB6AB.js.map} +1 -1
  8. package/dist/{chunk-SEJ6RBP7.js → chunk-JZ7RAGDQ.js} +117 -60
  9. package/dist/chunk-JZ7RAGDQ.js.map +1 -0
  10. package/dist/chunk-PWS2HLDE.js +137 -0
  11. package/dist/chunk-PWS2HLDE.js.map +1 -0
  12. package/dist/{chunk-AGTBABAH.js → chunk-PWYMRUAK.js} +43 -30
  13. package/dist/chunk-PWYMRUAK.js.map +1 -0
  14. package/dist/{chunk-FUMSL7VZ.js → chunk-T7FEVT62.js} +53 -12
  15. package/dist/chunk-T7FEVT62.js.map +1 -0
  16. package/dist/{chunk-2Z72MYHB.js → chunk-UZCJDMGE.js} +353 -19
  17. package/dist/chunk-UZCJDMGE.js.map +1 -0
  18. package/dist/components/index.d.ts +275 -24
  19. package/dist/components/index.js +5 -5
  20. package/dist/data/index.d.ts +2 -1
  21. package/dist/data/index.js +7 -12
  22. package/dist/data/index.js.map +1 -1
  23. package/dist/hooks/index.d.ts +36 -3
  24. package/dist/hooks/index.js +2 -2
  25. package/dist/icons/lucide.d.ts +1 -1
  26. package/dist/icons/lucide.js +13 -3
  27. package/dist/icons/lucide.js.map +1 -1
  28. package/dist/{inbox-page-B7_Oi2fS.d.ts → inbox-page-BGqR_cBs.d.ts} +4 -1
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.js +8 -8
  31. package/dist/layouts/index.d.ts +12 -3
  32. package/dist/layouts/index.js +5 -5
  33. package/dist/{native-modules-Cl3zw3kh.d.ts → native-modules-CeAaO2Dh.d.ts} +55 -3
  34. package/package.json +73 -2
  35. package/src/__tests__/doctor-rules.test.ts +27 -0
  36. package/src/__tests__/native-modules-lists.test.tsx +1 -0
  37. package/src/components/__tests__/bulk-bar.test.tsx +36 -0
  38. package/src/components/__tests__/button-haptic.test.tsx +74 -0
  39. package/src/components/__tests__/composer-bar.test.tsx +140 -1
  40. package/src/components/__tests__/gallery-grid.test.tsx +2 -2
  41. package/src/components/__tests__/library-round-5.test.tsx +121 -0
  42. package/src/components/__tests__/share-sheet.test.tsx +47 -0
  43. package/src/components/__tests__/swipe-row-context-menu.test.tsx +215 -0
  44. package/src/components/__tests__/tab-bar.test.tsx +43 -0
  45. package/src/components/__tests__/thread-list.test.tsx +200 -0
  46. package/src/components/__tests__/tier-badge.test.tsx +57 -0
  47. package/src/components/__tests__/whats-new-sheet.test.tsx +29 -0
  48. package/src/components/bulk-bar.tsx +91 -0
  49. package/src/components/button.tsx +81 -25
  50. package/src/components/choice-card.tsx +104 -0
  51. package/src/components/composer-bar.tsx +104 -25
  52. package/src/components/context-menu.tsx +101 -0
  53. package/src/components/gallery-grid.tsx +10 -4
  54. package/src/components/index.ts +19 -2
  55. package/src/components/inline-alert.tsx +36 -1
  56. package/src/components/input.tsx +3 -0
  57. package/src/components/progress.tsx +24 -2
  58. package/src/components/rating.tsx +35 -16
  59. package/src/components/share-sheet.tsx +127 -0
  60. package/src/components/sheet.tsx +9 -1
  61. package/src/components/swipe-row.tsx +74 -0
  62. package/src/components/tab-bar.tsx +133 -0
  63. package/src/components/tabs.tsx +2 -0
  64. package/src/components/text.tsx +3 -0
  65. package/src/components/textarea.tsx +3 -0
  66. package/src/components/thread-list.tsx +78 -23
  67. package/src/components/tier-badge.tsx +74 -0
  68. package/src/components/whats-new-sheet.tsx +89 -0
  69. package/src/data/resource-view/NativeRecordView.tsx +3 -8
  70. package/src/data/resource-view/use-native-resource-view.ts +2 -2
  71. package/src/hooks/__tests__/use-haptics.test.tsx +146 -0
  72. package/src/hooks/index.ts +3 -1
  73. package/src/hooks/use-haptics.ts +64 -0
  74. package/src/hooks/use-press-feedback.ts +87 -0
  75. package/src/hooks/use-theme-roles.ts +3 -0
  76. package/src/icon-names.ts +12 -2
  77. package/src/icons/lucide.ts +27 -7
  78. package/src/layouts/__tests__/inbox-page.test.tsx +26 -7
  79. package/src/layouts/__tests__/thread-page.test.tsx +89 -2
  80. package/src/layouts/inbox-page.tsx +28 -12
  81. package/src/layouts/thread-page.tsx +69 -8
  82. package/src/native-modules.tsx +20 -0
  83. package/dist/chunk-2Z72MYHB.js.map +0 -1
  84. package/dist/chunk-4OQOJ2OC.js +0 -80
  85. package/dist/chunk-4OQOJ2OC.js.map +0 -1
  86. package/dist/chunk-6PGLX6ET.js.map +0 -1
  87. package/dist/chunk-AGTBABAH.js.map +0 -1
  88. package/dist/chunk-FUMSL7VZ.js.map +0 -1
  89. package/dist/chunk-NDXNSSM6.js.map +0 -1
  90. package/dist/chunk-SEJ6RBP7.js.map +0 -1
@@ -22,7 +22,12 @@
22
22
  * rendered. Going to a row waits for `loading`, loads until it's held,
23
23
  * scrolls to it (again after FlashList's own placement on open), highlights
24
24
  * it for two seconds and announces it. Reduce Motion scrolls without
25
- * animating.
25
+ * animating. The reader's touch wins: a drag during a jump ends the list's own
26
+ * scrolling and drops the jump, even one still loading, so nothing snaps back.
27
+ *
28
+ * A row is gone when, once `onLoadUntil` has settled, no row answers to its
29
+ * id. The list knows only its rows: a row that's drawn (a deleted message's
30
+ * tombstone) is there, and whatever isn't drawn isn't, whatever a cache holds.
26
31
  *
27
32
  * Promoted from genesis-chat's thread and its `useJumpToMessage` (G4); chat
28
33
  * moves onto it later.
@@ -112,11 +117,18 @@ export interface NativeThreadListProps<T> {
112
117
  renderEarlier?: (props: { loading: boolean; onPress: () => void; label: string; testID: string }) => ReactNode;
113
118
  /** 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
119
  jumpTo?: string | null;
120
+ /**
121
+ * The id `jumpTo` names a row by, when it isn't the row's key: a message keyed by the id the
122
+ * phone gave it (so it keeps its row when the server's copy lands) and gone to by the server's
123
+ * id. `null` for a row that can't be gone to (a day heading). `keyExtractor` by default.
124
+ * Pass a stable function (module scope, or `useCallback`): a new one each render re-renders every row.
125
+ */
126
+ jumpId?: (row: T) => string | null | undefined;
115
127
  /** Load earlier pages until the row is held; resolve false when it can't be found. */
116
128
  onLoadUntil?: (id: string) => Promise<boolean>;
117
129
  /** What VoiceOver says on arriving at `jumpTo`. */
118
130
  jumpAnnouncement?: (row: T) => string;
119
- /** The row couldn't be found (deleted, out of reach). The list goes back to the newest row first. */
131
+ /** No row answers to this id once `onLoadUntil` has settled, or it failed. The list goes back to the newest row first. */
120
132
  onJumpFailed?: (id: string) => void;
121
133
  /** Whether the reader is at the bottom, as it changes (to show a "new messages" pill, say). */
122
134
  onAtBottomChange?: (atBottom: boolean) => void;
@@ -147,6 +159,7 @@ interface ThreadListComponentProps {
147
159
  contentContainerStyle?: Record<string, unknown>;
148
160
  maintainVisibleContentPosition?: Record<string, unknown>;
149
161
  onScroll?: (e: { nativeEvent: ScrollMetrics }) => void;
162
+ onScrollBeginDrag?: () => void;
150
163
  scrollEventThrottle?: number;
151
164
  onContentSizeChange?: () => void;
152
165
  onLayout?: () => void;
@@ -175,6 +188,7 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
175
188
  earlierLabel = "Load earlier messages",
176
189
  renderEarlier,
177
190
  jumpTo,
191
+ jumpId,
178
192
  onLoadUntil,
179
193
  jumpAnnouncement,
180
194
  onJumpFailed,
@@ -202,6 +216,8 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
202
216
  const placed = useRef(!mode.followsByHand);
203
217
  // While the list scrolls itself, its own scroll events don't move "at the bottom".
204
218
  const settlingUntil = useRef(0);
219
+ // Bumped by each move the list starts and by the reader's touch: a queued try from an older move doesn't run.
220
+ const moveId = useRef(0);
205
221
  const timers = useRef(new Set<ReturnType<typeof setTimeout>>());
206
222
  const later = useCallback((fn: () => void, ms: number) => {
207
223
  const t = setTimeout(() => {
@@ -214,9 +230,11 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
214
230
  const pending = timers.current;
215
231
  return () => pending.forEach(clearTimeout);
216
232
  }, []);
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), []);
233
+ const idOf = jumpId ?? keyExtractor;
234
+ const latest = useRef({ data, idOf, jumpAnnouncement, onJumpFailed, onAtBottomChange });
235
+ latest.current = { data, idOf, jumpAnnouncement, onJumpFailed, onAtBottomChange };
236
+ // The row a jump names, by `jumpId` (the key by default).
237
+ const indexOf = useCallback((id: string) => latest.current.data.findIndex((row) => latest.current.idOf(row) === id), []);
220
238
 
221
239
  const setAtBottom = useCallback((v: boolean) => {
222
240
  if (atBottom.current === v) return;
@@ -227,13 +245,14 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
227
245
  const toBottom = useCallback(
228
246
  (animated: boolean) => {
229
247
  settlingUntil.current = Date.now() + SETTLING_MS;
248
+ const move = ++moveId.current;
230
249
  const go = (a: boolean) => listRef.current?.scrollToEnd?.({ animated: a && !reducedMotion });
231
250
  requestAnimationFrame(() => {
232
251
  go(animated);
233
252
  placed.current = true;
234
253
  });
235
254
  // Once more after a new row has its size (FlashList measures it after the first pass).
236
- if (animated) later(() => go(true), 180);
255
+ if (animated) later(() => move === moveId.current && go(true), 180);
237
256
  },
238
257
  [later, reducedMotion],
239
258
  );
@@ -253,9 +272,14 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
253
272
  const jumpTries = useRef<{ id: string; tries: number } | null>(null);
254
273
  const scrollToRow = useCallback(
255
274
  (id: string) => {
275
+ const move = ++moveId.current;
256
276
  const scroll = () => {
277
+ if (move !== moveId.current) return;
257
278
  const at = indexOf(id);
258
- if (at >= 0) listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
279
+ if (at < 0) return;
280
+ // Each try moves the list again: its events don't count until this one settles.
281
+ settlingUntil.current = Date.now() + SETTLING_MS;
282
+ listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
259
283
  };
260
284
  jumpTries.current = { id, tries: 0 };
261
285
  settlingUntil.current = Date.now() + SETTLING_MS;
@@ -266,10 +290,25 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
266
290
  },
267
291
  [indexOf, later, reducedMotion],
268
292
  );
293
+ // A jump to a row already in view moves nothing, so no scroll event says where the list is: look
294
+ // once its own scrolling has settled (a second try extends that; mid-way it can still read as the
295
+ // bottom). No scroll event yet means the list hasn't moved from where it opens, the bottom.
296
+ const lookForBottom = useCallback(() => {
297
+ if (recheck.current) clearTimeout(recheck.current);
298
+ const look = () => {
299
+ const wait = settlingUntil.current - Date.now();
300
+ if (wait > 0) {
301
+ recheck.current = setTimeout(look, wait + 50);
302
+ return;
303
+ }
304
+ if (!metrics.current || threadNearBottom(metrics.current)) setAtBottom(true);
305
+ };
306
+ recheck.current = setTimeout(look, SETTLING_MS + 50);
307
+ }, [setAtBottom]);
269
308
  const has = useCallback((id: string) => indexOf(id) >= 0, [indexOf]);
270
309
  // `has` must change when the rows do, so the jump looks again.
271
310
  const hasNow = useMemo(() => (id: string) => has(id), [has, data]); // eslint-disable-line react-hooks/exhaustive-deps
272
- const { highlightedId, jumping } = useThreadJump({
311
+ const { highlightedId, jumping, cancel: cancelJump } = useThreadJump({
273
312
  target: jumpTo,
274
313
  has: hasNow,
275
314
  loading,
@@ -280,11 +319,7 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
280
319
  placed.current = true;
281
320
  },
282
321
  onLanded: (id) => {
283
- // A jump to a row already at the bottom moves nothing, so no scroll event says so: look once it settles.
284
- if (recheck.current) clearTimeout(recheck.current);
285
- recheck.current = setTimeout(() => {
286
- if (metrics.current && threadNearBottom(metrics.current)) setAtBottom(true);
287
- }, SETTLING_MS + 50);
322
+ lookForBottom();
288
323
  const at = indexOf(id);
289
324
  const said = at >= 0 ? latest.current.jumpAnnouncement?.(latest.current.data[at]!) : undefined;
290
325
  if (said) announce(said);
@@ -310,8 +345,8 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
310
345
  );
311
346
 
312
347
  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],
348
+ ({ item, index }: { item: unknown; index: number }) => renderItem(item as T, { index, highlighted: highlightedId !== null && idOf(item as T) === highlightedId }),
349
+ [highlightedId, idOf, renderItem],
315
350
  );
316
351
  const listKey = useCallback((row: unknown) => keyExtractor(row as T), [keyExtractor]);
317
352
  const listItemType = useMemo(() => (getItemType ? (row: unknown) => getItemType(row as T) : undefined), [getItemType]);
@@ -320,26 +355,45 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
320
355
  metrics.current = { contentOffset: { y: e.nativeEvent.contentOffset.y }, contentSize: { height: e.nativeEvent.contentSize.height }, layoutMeasurement: { height: e.nativeEvent.layoutMeasurement.height } };
321
356
  const height = e.nativeEvent.layoutMeasurement.height;
322
357
  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);
358
+ // The list's own scroll (to the newest, to a row) isn't the reader moving. Going to a row starts
359
+ // at the bottom, so its first events say "at the bottom": taken, that turned following back on,
360
+ // and FlatList's next layout scrolled to the end, away from the row. After a jump, onLanded
361
+ // looks again once it has settled.
362
+ if (Date.now() < settlingUntil.current) return;
363
+ setAtBottom(threadNearBottom(e.nativeEvent));
327
364
  },
328
365
  [setAtBottom],
329
366
  );
367
+ // The reader's touch ends the list's own scroll: from here their scrolling counts, even mid-jump,
368
+ // the tries still queued don't snap them back, and a jump still loading doesn't land. Only a drag:
369
+ // a fling follows one, and onMomentumScrollBegin isn't promised to be the reader's alone (Android
370
+ // may report a programmatic smooth scroll), which would cancel the list's own retry. VoiceOver's
371
+ // three-finger scroll and a wheel send no drag, so those count once the settling window (400ms) ends.
372
+ const readerTookOver = useCallback(() => {
373
+ settlingUntil.current = 0;
374
+ moveId.current += 1;
375
+ jumpTries.current = null;
376
+ cancelJump();
377
+ }, [cancelJump]);
330
378
  const onScrollToIndexFailed = useCallback(
331
379
  ({ index, averageItemLength }: { index: number; averageItemLength: number }) => {
380
+ const target = jumpTries.current;
381
+ // The reader took over.
382
+ if (!target) return;
332
383
  // FlatList hasn't measured that far up yet: get near it, then try again by id (three times at most).
333
384
  listRef.current?.scrollToOffset?.({ offset: Math.max(0, index * averageItemLength - 200), animated: false });
334
- const target = jumpTries.current;
335
- if (!target || target.tries >= 3) return;
385
+ if (target.tries >= 3) return;
336
386
  target.tries += 1;
337
387
  later(() => {
388
+ if (jumpTries.current !== target) return;
338
389
  const at = indexOf(target.id);
339
- if (at >= 0) listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
390
+ if (at < 0) return;
391
+ settlingUntil.current = Date.now() + SETTLING_MS;
392
+ listRef.current?.scrollToIndex?.({ index: at, animated: !reducedMotion, viewPosition: 0.5 });
393
+ lookForBottom();
340
394
  }, 250);
341
395
  },
342
- [indexOf, later, reducedMotion],
396
+ [indexOf, later, lookForBottom, reducedMotion],
343
397
  );
344
398
  const follow = useCallback(() => {
345
399
  if (atBottom.current && !jumping) toBottom(false);
@@ -381,6 +435,7 @@ function NativeThreadListInner<T>(props: NativeThreadListProps<T>, ref: React.Fo
381
435
  maintainVisibleContentPosition={mode.maintainVisibleContentPosition}
382
436
  scrollEventThrottle={32}
383
437
  onScroll={onScroll}
438
+ onScrollBeginDrag={readerTookOver}
384
439
  onScrollToIndexFailed={onScrollToIndexFailed}
385
440
  {...(mode.followsByHand ? { onContentSizeChange: follow, onLayout: follow } : {})}
386
441
  ListHeaderComponent={listHeader}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * NativeTierBadge — a rank or tier label ("Gold", "Level 3"), with an optional
3
+ * leading icon and a tone from the brand's `accents`.
4
+ *
5
+ * `tone` names a brand accent, read from the nearest `GenesisThemeProvider`
6
+ * (`theme.tokens.accents`): the accent is the border and a 15% tint behind
7
+ * the text, and the text stays the foreground colour, so it reads at AA
8
+ * whatever the accent. Without a tone, a provider or such an accent, it is
9
+ * the secondary chip.
10
+ *
11
+ * @stability Beta
12
+ */
13
+ import { Text, View } from "react-native";
14
+ import { useOptionalTheme } from "@marktiderman/genesis-design-system";
15
+ import { cn } from "../utils";
16
+ import type { NativeIconName } from "../icon-names";
17
+ import { NativeIcon } from "./icon";
18
+
19
+ export interface NativeTierBadgeProps {
20
+ /** The rank or tier, as shown ("Gold"). */
21
+ label: string;
22
+ /** A key of the brand's `accents` (`"gold"`). Unset: neutral. */
23
+ tone?: string;
24
+ /** Leading icon, by Genesis icon name. */
25
+ icon?: NativeIconName;
26
+ /** `sm` for a list row, `md` (default) for a header. */
27
+ size?: "sm" | "md";
28
+ className?: string;
29
+ textClassName?: string;
30
+ /** What a screen reader says. Default: the label. */
31
+ accessibilityLabel?: string;
32
+ testID?: string;
33
+ }
34
+
35
+ /** `#rrggbb` + alpha (0–1) → `#rrggbbaa`; anything else is returned as is. */
36
+ function withAlpha(colour: string, alpha: number): string {
37
+ const full = /^#([0-9a-f]{3})$/i.test(colour) ? `#${[...colour.slice(1)].map((c) => c + c).join("")}` : colour;
38
+ // A colour that can't take an alpha here (rgb(), hsl(), a name) gets no tint, so the text stays readable.
39
+ if (!/^#[0-9a-f]{6}$/i.test(full)) return "transparent";
40
+ return `${full}${Math.round(alpha * 255).toString(16).padStart(2, "0")}`;
41
+ }
42
+
43
+ function NativeTierBadge({ label, tone, icon, size = "md", className, textClassName, accessibilityLabel, testID }: NativeTierBadgeProps) {
44
+ const accents = useOptionalTheme()?.tokens.accents;
45
+ const accent = tone ? accents?.[tone] : undefined;
46
+ return (
47
+ <View
48
+ className={cn(
49
+ "flex-row items-center self-start rounded-full border",
50
+ size === "sm" ? "gap-1 px-2 py-0.5" : "gap-1.5 px-2.5 py-1",
51
+ !accent && "border-transparent bg-secondary",
52
+ className
53
+ )}
54
+ style={accent ? { borderColor: accent, backgroundColor: withAlpha(accent, 0.15) } : undefined}
55
+ accessibilityRole="text"
56
+ accessibilityLabel={accessibilityLabel ?? label}
57
+ testID={testID}
58
+ >
59
+ {icon ? <NativeIcon name={icon} size={size === "sm" ? 12 : 14} {...(accent ? { color: accent } : {})} /> : null}
60
+ <Text
61
+ className={cn(
62
+ "font-semibold",
63
+ size === "sm" ? "text-xs" : "text-sm",
64
+ accent ? "text-foreground" : "text-secondary-foreground",
65
+ textClassName
66
+ )}
67
+ >
68
+ {label}
69
+ </Text>
70
+ </View>
71
+ );
72
+ }
73
+
74
+ export { NativeTierBadge };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * WhatsNewSheet — release notes in a sheet, shown once and closed with "Got it".
3
+ *
4
+ * The one sheet behind genesis-native's updates block (`WhatsNewSheet`) and genesis-product's
5
+ * `ProductWhatsNew`: each maps its own notes onto `NativeWhatsNewNote` and renders this.
6
+ *
7
+ * @stability Beta
8
+ */
9
+ import { View } from "react-native";
10
+ import { NativeButton } from "./button";
11
+ import { NativeSheet, NativeSheetScrollView } from "./sheet";
12
+ import { NativeText } from "./text";
13
+
14
+ /** One note. */
15
+ export interface NativeWhatsNewNote {
16
+ /** Unique within the sheet (a version, a note id). */
17
+ key: string;
18
+ title: string;
19
+ body?: string;
20
+ /** With `onOpenNote`, the note gets "Learn more". */
21
+ url?: string;
22
+ }
23
+
24
+ export interface NativeWhatsNewSheetProps<N extends NativeWhatsNewNote = NativeWhatsNewNote> {
25
+ notes: readonly N[];
26
+ /** Close and remember. */
27
+ dismiss: () => void;
28
+ /** "Learn more" on a note with a `url`: the sheet closes (and is remembered), then this opens it. */
29
+ onOpenNote?: (note: N) => void;
30
+ /** Default "What's new". */
31
+ title?: string;
32
+ /** Default "Got it". */
33
+ doneLabel?: string;
34
+ /** Default "Learn more". */
35
+ learnMoreLabel?: string;
36
+ /** The sheet's; each note is `{testID}-{key}`, Done `{testID}-done`, Learn more `{testID}-open-{key}`. */
37
+ testID?: string;
38
+ /** A note's testID. Default `{testID}-{key}`. */
39
+ noteTestID?: (key: string) => string;
40
+ }
41
+
42
+ export function NativeWhatsNewSheet<N extends NativeWhatsNewNote = NativeWhatsNewNote>({
43
+ notes,
44
+ dismiss,
45
+ onOpenNote,
46
+ title = "What's new",
47
+ doneLabel = "Got it",
48
+ learnMoreLabel = "Learn more",
49
+ testID = "native-whats-new",
50
+ noteTestID = (key) => `${testID}-${key}`,
51
+ }: NativeWhatsNewSheetProps<N>) {
52
+ return (
53
+ <NativeSheet open onOpenChange={(open) => (open ? undefined : dismiss())} testID={testID}>
54
+ {/* The notes scroll once they pass the sheet's height. */}
55
+ <NativeSheetScrollView contentContainerStyle={{ gap: 16, padding: 24 }}>
56
+ <NativeText preset="h3" accessibilityRole="header">
57
+ {title}
58
+ </NativeText>
59
+ {notes.map((note) => (
60
+ <View key={note.key} style={{ gap: 4 }} testID={noteTestID(note.key)}>
61
+ <NativeText preset="label">{note.title}</NativeText>
62
+ {note.body ? (
63
+ <NativeText preset="body-sm" className="text-muted-foreground">
64
+ {note.body}
65
+ </NativeText>
66
+ ) : null}
67
+ {note.url && onOpenNote ? (
68
+ <NativeButton
69
+ variant="ghost"
70
+ size="sm"
71
+ onPress={() => {
72
+ // Closed first: the note's screen opens with "what's new" seen.
73
+ dismiss();
74
+ onOpenNote(note);
75
+ }}
76
+ testID={`${testID}-open-${note.key}`}
77
+ >
78
+ {learnMoreLabel}
79
+ </NativeButton>
80
+ ) : null}
81
+ </View>
82
+ ))}
83
+ <NativeButton onPress={dismiss} testID={`${testID}-done`}>
84
+ {doneLabel}
85
+ </NativeButton>
86
+ </NativeSheetScrollView>
87
+ </NativeSheet>
88
+ );
89
+ }
@@ -12,7 +12,7 @@
12
12
  import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
13
13
  import { ActionSheetIOS, Alert, Platform, Pressable, ScrollView, View } from "react-native";
14
14
  import { useQuery, useQueryClient } from "@tanstack/react-query";
15
- import { DataWriteError, isDataWriteError, resourceKeys, useCapabilities, useDataProvider, useResource, useViewer, writeConflict, type BaseRecord, type DataRow, type ResourceContract, type WriteConflict } from "@marktiderman/genesis-core";
15
+ import { DataWriteError, isDataWriteError, NO_ROWS_MATCHED, resourceKeys, useCapabilities, useDataProvider, useResource, useViewer, writeConflict, type BaseRecord, type DataRow, type ResourceContract, type WriteConflict } from "@marktiderman/genesis-core";
16
16
  import { readinessChip, type ReadinessLabels } from "@marktiderman/genesis-core/resource";
17
17
  import { sameFormValue, type Allowed, type RecordView as RecordViewDef, type RecordViewHeaderAction } from "@marktiderman/genesis-core/resource-view";
18
18
  import { NativeBadge } from "../../components/badge";
@@ -559,12 +559,6 @@ function SettingsGroup({
559
559
  // directly: a save made while another of this record is in flight is checked against the
560
560
  // version that one commits, and the version this one commits goes into every cached copy.
561
561
  const saved = await update(recordView.recordId(row), data as Partial<DataRow & BaseRecord>, version != null ? { expectedVersion: String(version) } : undefined);
562
- // A write that matched no rows is a refusal, never a silent success.
563
- if (saved === null || saved === undefined) {
564
- lastFailure.current = fill(words.notChanged, { noun: view.noun });
565
- setRefusal(lastFailure.current);
566
- return "failed";
567
- }
568
562
  // The next edit builds on this save's version, even before the record refetches.
569
563
  if (versionField && saved[versionField] != null) editBase.current = { ...(editBase.current ?? row), [versionField]: saved[versionField] };
570
564
  setConflict(null);
@@ -576,7 +570,8 @@ function SettingsGroup({
576
570
  setConflict({ conflict: found, values, row: error.current, message: error.message });
577
571
  return "conflict";
578
572
  }
579
- lastFailure.current = refusalMessage(error, words.failed);
573
+ // A write that matched no rows is a refusal, in this screen's words.
574
+ lastFailure.current = isDataWriteError(error) && error.code === NO_ROWS_MATCHED ? fill(words.notChanged, { noun: view.noun }) : refusalMessage(error, words.failed);
580
575
  setRefusal(lastFailure.current);
581
576
  return "failed";
582
577
  } finally {
@@ -151,7 +151,7 @@ export function screenLists(...filters: (Filter | undefined)[]): Record<string,
151
151
  /** Pages kept loaded by default (cursor paging). */
152
152
  export const DEFAULT_MAX_PAGES = 10;
153
153
 
154
- type ServerSort = { field: string; order: "asc" | "desc" };
154
+ type ServerSort = { field: string; order: "asc" | "desc"; nulls?: "first" | "last" };
155
155
 
156
156
  /**
157
157
  * The server sorts: the `groupBy` field first, so every page arrives in section order and a later
@@ -161,7 +161,7 @@ type ServerSort = { field: string; order: "asc" | "desc" };
161
161
  export function serverSorts<T extends Row>(view: AnyResourceView<T>): ServerSort[] {
162
162
  const groupBy = view.definition.groupBy as string | undefined;
163
163
  const orderBy = view.definition.orderBy;
164
- const order: ServerSort | undefined = orderBy ? { field: orderBy.field as string, order: orderBy.direction ?? "asc" } : undefined;
164
+ const order: ServerSort | undefined = orderBy ? { field: orderBy.field as string, order: orderBy.direction ?? "asc", ...(orderBy.nulls ? { nulls: orderBy.nulls } : {}) } : undefined;
165
165
  if (!groupBy) return order ? [order] : [];
166
166
  if (order?.field === groupBy) return [order];
167
167
  return [{ field: groupBy, order: "asc" }, ...(order ? [order] : [])];
@@ -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,9 +9,11 @@
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
- export { useThemeRoles, type ThemeRoleColors, type UseThemeRolesOptions } from "./use-theme-roles";
16
+ export { useThemeRoles, type ThemeRoleColors, type UseThemeRolesOptions, sentBubbleColor } from "./use-theme-roles";
15
17
  export {
16
18
  BrandExtensionsProvider,
17
19
  useGenesisExtension,
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Haptics, one way in: the app passes expo-haptics once, as `GenesisModules.haptics`, and every
3
+ * Genesis primitive (and the app's own pieces) plays the same kinds of feedback through
4
+ * `useHaptics()`. Without the module nothing plays, and nothing throws.
5
+ *
6
+ * import * as Haptics from "expo-haptics";
7
+ * <GenesisModulesProvider modules={{ haptics: Haptics }}>
8
+ *
9
+ * const haptic = useHaptics();
10
+ * haptic("select");
11
+ *
12
+ * Kinds follow the platforms' own vocabulary: a light, medium or heavy impact (a press, a swipe
13
+ * passing its threshold, a long press opening a menu), a selection tick (a picker or a tab
14
+ * changing), and a success, warning or error notification. The OS's own haptics setting applies;
15
+ * Reduce Motion doesn't turn haptics off (they're not motion).
16
+ *
17
+ * @stability Beta
18
+ */
19
+ import { useCallback } from "react";
20
+ import { useGenesisModules } from "../native-modules";
21
+
22
+ /** What a haptic says. */
23
+ export type HapticKind = "light" | "medium" | "heavy" | "select" | "success" | "warning" | "error";
24
+
25
+ /**
26
+ * `import * as Haptics from "expo-haptics"`: the parts Genesis calls, written structurally (the
27
+ * same shape as genesis-chat's `HapticsLike`, so one module serves both).
28
+ */
29
+ export interface GenesisHapticsModule {
30
+ impactAsync(style?: never): Promise<void>;
31
+ selectionAsync(): Promise<void>;
32
+ notificationAsync(type?: never): Promise<void>;
33
+ ImpactFeedbackStyle: { Light: unknown; Medium: unknown; Heavy?: unknown };
34
+ NotificationFeedbackType: { Success: unknown; Warning: unknown; Error: unknown };
35
+ }
36
+
37
+ /** Plays a haptic on the module given; never throws and never rejects. No module, no haptic. */
38
+ export function playHaptic(haptics: GenesisHapticsModule | undefined, kind: HapticKind): void {
39
+ if (!haptics) return;
40
+ try {
41
+ const as = (s: unknown) => s as never;
42
+ const styles = haptics.ImpactFeedbackStyle;
43
+ const notes = haptics.NotificationFeedbackType;
44
+ const p =
45
+ kind === "light"
46
+ ? haptics.impactAsync(as(styles.Light))
47
+ : kind === "medium"
48
+ ? haptics.impactAsync(as(styles.Medium))
49
+ : kind === "heavy"
50
+ ? haptics.impactAsync(as(styles.Heavy ?? styles.Medium))
51
+ : kind === "select"
52
+ ? haptics.selectionAsync()
53
+ : haptics.notificationAsync(as(kind === "success" ? notes.Success : kind === "warning" ? notes.Warning : notes.Error));
54
+ void p?.catch?.(() => undefined);
55
+ } catch {
56
+ // A haptic is never worth an error.
57
+ }
58
+ }
59
+
60
+ /** A function that plays a haptic through the app's `GenesisModules.haptics`. Stable across renders. */
61
+ export function useHaptics(): (kind: HapticKind) => void {
62
+ const { haptics } = useGenesisModules();
63
+ return useCallback((kind: HapticKind) => playHaptic(haptics, kind), [haptics]);
64
+ }