@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
@@ -10,6 +10,7 @@ import { NativeButton } from "../components/button";
10
10
  import { NativeSeparator } from "../components/separator";
11
11
  import { NativeText } from "../components/text";
12
12
  import { NativeResourceFormFieldRenderer } from "./NativeResourceFormField";
13
+ import { NativeConflictSheet } from "./NativeConflictSheet";
13
14
 
14
15
  // ---------------------------------------------------------------------------
15
16
  // Types
@@ -59,7 +60,18 @@ function NativeResourceForm({
59
60
  validationMode: "onSubmit",
60
61
  };
61
62
 
62
- const { form, resolvedFields, onSubmit, isSaving } = useResourceForm(options);
63
+ const { form, resolvedFields, onSubmit, isSaving, conflict, keepMine, takeTheirs, dismissConflict } = useResourceForm(options);
64
+ // A save that met someone else's change: theirs above yours, then keep mine or take theirs.
65
+ const conflictSheet = (
66
+ <NativeConflictSheet
67
+ conflict={conflict}
68
+ label={(field) => resolvedFields.find((f) => f.key === field)?.label ?? titleCase(field)}
69
+ onKeepMine={keepMine}
70
+ onTakeTheirs={takeTheirs}
71
+ onDismiss={dismissConflict}
72
+ testID="native-resource-form-conflict"
73
+ />
74
+ );
63
75
 
64
76
  const resolvedTitle =
65
77
  title ?? (action === "create" ? `Create ${titleCase(resource)}` : `Edit ${titleCase(resource)}`);
@@ -137,6 +149,7 @@ function NativeResourceForm({
137
149
  <View style={{ gap: 16 }}>
138
150
  <NativeText preset="h3">{resolvedTitle}</NativeText>
139
151
  {formContent}
152
+ {conflictSheet}
140
153
  </View>
141
154
  );
142
155
  }
@@ -150,6 +163,7 @@ function NativeResourceForm({
150
163
  <NativeText preset="h3">{resolvedTitle}</NativeText>
151
164
  {formContent}
152
165
  </ScrollView>
166
+ {conflictSheet}
153
167
  </SafeAreaView>
154
168
  );
155
169
  }
package/src/data/index.ts CHANGED
@@ -8,3 +8,5 @@ export { NativeResourceFormFieldRenderer, type NativeResourceFormFieldRendererPr
8
8
  export { NativeResourceForm, type NativeResourceFormProps } from "./NativeResourceForm";
9
9
  export { NativeResourcePage, type NativeResourcePageProps, type NativeCardFieldDef } from "./NativeResourcePage";
10
10
  export * from "./resource-view";
11
+ // A save that met someone else's change: theirs above yours, then keep mine or take theirs.
12
+ export { NativeConflictSheet, type NativeConflictSheetProps, type NativeConflictSheetMessages } from "./NativeConflictSheet";
@@ -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, resourceKeys, useCapabilities, useDataProvider, useViewer, type DataRow, type ResourceContract } from "@marktiderman/genesis-core";
15
+ import { DataWriteError, isDataWriteError, 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";
@@ -23,6 +23,7 @@ import { NativeInput } from "../../components/input";
23
23
  import { NativeListItem } from "../../components/list-item";
24
24
  import { NativeSegmentedControl } from "../../components/segmented-control";
25
25
  import { NativeSheet } from "../../components/sheet";
26
+ import { NativeConflictSheet, type NativeConflictSheetMessages } from "../NativeConflictSheet";
26
27
  import { NativeSelect, NativeSelectContent, NativeSelectItem, NativeSelectTrigger } from "../../components/select";
27
28
  import { NativeSwitch } from "../../components/switch";
28
29
  import { NativeText } from "../../components/text";
@@ -59,6 +60,8 @@ export interface NativeRecordViewMessages extends ReadinessLabels {
59
60
  /** The back row of a section opened from the list of sections. */
60
61
  allSections: string;
61
62
  notANumber: string;
63
+ /** The conflict sheet's words (NativeConflictSheet's English when unset). */
64
+ conflict?: Partial<NativeConflictSheetMessages>;
62
65
  }
63
66
 
64
67
  export const defaultNativeRecordViewMessages: NativeRecordViewMessages = {
@@ -152,6 +155,9 @@ function useHeaderActions<T extends Row>({ view: recordView, row, onAction, can,
152
155
  /** Prefixes accessibility action names, so an action named "activate" never replaces the button's own. */
153
156
  const A11Y_PREFIX = "action:";
154
157
 
158
+ /** The settings save shows its own failures (inline, or in the conflict sheet), so useResource doesn't log them too. */
159
+ const alreadyShown = () => {};
160
+
155
161
  /**
156
162
  * The header menu: a button that lists the record view's actions. On iOS an action sheet
157
163
  * (ActionSheetIOS, destructive ones in red); elsewhere a sheet of rows, since Android's alert
@@ -475,7 +481,7 @@ export function NativeRecordView<T extends Row = Row>(props: NativeRecordViewPro
475
481
  function SettingsGroup({
476
482
  recordView,
477
483
  sectionId,
478
- row,
484
+ row: rowProp,
479
485
  words,
480
486
  onSaved,
481
487
  testID,
@@ -489,7 +495,13 @@ function SettingsGroup({
489
495
  testID: string;
490
496
  }) {
491
497
  const provider = useDataProvider();
498
+ // After "take theirs": their row, shown until the record refetches with it.
499
+ const [theirsRow, setTheirsRow] = useState<DataRow | null>(null);
500
+ useEffect(() => setTheirsRow(null), [rowProp]);
501
+ const row = theirsRow ?? rowProp;
492
502
  const view = recordView.view;
503
+ // A versioned resource checks the save against the version of the row shown (core README, "Versioned writes").
504
+ const versionField = useCapabilities(view.resource, { enabled: !!provider.capabilities }).data?.version?.field;
493
505
  // The view's edit-form mapping (the form sheet's), narrowed to this section's keys in their order.
494
506
  const fields = useMemo(() => {
495
507
  const byKey = new Map(formFieldsFor(view, "edit").map((f) => [f.key, f]));
@@ -501,6 +513,12 @@ function SettingsGroup({
501
513
  // Only the fields this person changed are theirs: the others show the row as it is now (a live
502
514
  // refresh updates them) and are never sent, so a stale draft can't overwrite someone else's change.
503
515
  const [edits, setEdits] = useState<Values>({});
516
+ // The row the person started editing: their save is checked against its version, not against a
517
+ // row that refreshed meanwhile (someone else's save would otherwise be overwritten).
518
+ const editBase = useRef<DataRow | undefined>(undefined);
519
+ useEffect(() => {
520
+ if (Object.keys(edits).length === 0) editBase.current = undefined;
521
+ }, [edits]);
504
522
  const draft = useMemo<Values>(() => ({ ...Object.fromEntries(fields.map((f) => [f.key, row[f.key]])), ...edits }), [fields, row, edits]);
505
523
  // An edit the row now holds (after a save, or someone else's same change) is no longer an edit.
506
524
  useEffect(() => {
@@ -518,25 +536,74 @@ function SettingsGroup({
518
536
  const dirty = Object.keys(changed).length > 0 && !shown.some((f) => invalid[f.key]);
519
537
 
520
538
  const set = (key: string, value: unknown, error?: string) => {
539
+ if (Object.keys(edits).length === 0 && editBase.current === undefined) editBase.current = row;
521
540
  setRefusal(null);
522
541
  setInvalid(({ [key]: _old, ...rest }) => (error ? { ...rest, [key]: error } : rest));
523
542
  setEdits((d) => ({ ...d, [key]: value }));
524
543
  };
525
- const save = async () => {
544
+ const queryClient = useQueryClient();
545
+ // The resource's own update; the record's reads are the screen's, so this one reads nothing.
546
+ const { update } = useResource<DataRow & BaseRecord>(view.resource, { enabled: false, onError: alreadyShown });
547
+ // A save that met someone else's change, and the values it tried to save.
548
+ const [conflict, setConflict] = useState<{ conflict: WriteConflict; values: Values; row: DataRow; message: string } | null>(null);
549
+ const lastFailure = useRef<string | null>(null);
550
+ /** Saves; says whether it saved, met a (new) conflict, or failed (the refusal is shown). */
551
+ const save = async (values: Values = changed, expectedVersion?: string): Promise<"saved" | "conflict" | "failed"> => {
526
552
  setSaving(true);
527
553
  setRefusal(null);
554
+ // Only the section's listed keys, never anything else the row or draft holds.
555
+ const data = recordView.settingsPatch(sectionId, values);
528
556
  try {
529
- // Only the section's listed keys, never anything else the row or draft holds.
530
- const result = await provider.update(view.resource, { id: recordView.recordId(row), data: recordView.settingsPatch(sectionId, changed) });
557
+ const version = expectedVersion ?? (versionField ? (editBase.current ?? row)[versionField] : undefined);
558
+ // Through the resource's write path (`update` with `expectedVersion`), not the provider
559
+ // directly: a save made while another of this record is in flight is checked against the
560
+ // version that one commits, and the version this one commits goes into every cached copy.
561
+ const saved = await update(recordView.recordId(row), data as Partial<DataRow & BaseRecord>, version != null ? { expectedVersion: String(version) } : undefined);
531
562
  // A write that matched no rows is a refusal, never a silent success.
532
- if (!result || result.data === null || result.data === undefined) setRefusal(fill(words.notChanged, { noun: view.noun }));
533
- else onSaved(result.data as DataRow);
563
+ if (saved === null || saved === undefined) {
564
+ lastFailure.current = fill(words.notChanged, { noun: view.noun });
565
+ setRefusal(lastFailure.current);
566
+ return "failed";
567
+ }
568
+ // The next edit builds on this save's version, even before the record refetches.
569
+ if (versionField && saved[versionField] != null) editBase.current = { ...(editBase.current ?? row), [versionField]: saved[versionField] };
570
+ setConflict(null);
571
+ onSaved(saved);
572
+ return "saved";
534
573
  } catch (error) {
535
- setRefusal(refusalMessage(error, words.failed));
574
+ const found = writeConflict(error, data);
575
+ if (found && isDataWriteError(error) && error.current) {
576
+ setConflict({ conflict: found, values, row: error.current, message: error.message });
577
+ return "conflict";
578
+ }
579
+ lastFailure.current = refusalMessage(error, words.failed);
580
+ setRefusal(lastFailure.current);
581
+ return "failed";
536
582
  } finally {
537
583
  setSaving(false);
538
584
  }
539
585
  };
586
+ const keepMine = async () => {
587
+ if (!conflict) return;
588
+ const { values, conflict: c } = conflict;
589
+ // The sheet stays up while this runs; a plain failure rejects, so the sheet says why.
590
+ // The real reason, on the sheet (the refusal line behind it says the same).
591
+ if ((await save(values, c.currentVersion ?? undefined)) === "failed") throw new Error(lastFailure.current ?? words.failed);
592
+ };
593
+ const takeTheirs = () => {
594
+ if (!conflict) return;
595
+ const { row: theirs } = conflict;
596
+ setConflict(null);
597
+ setEdits({});
598
+ // Their row at once, then the refetch confirms it.
599
+ setTheirsRow({ ...rowProp, ...theirs });
600
+ void queryClient.invalidateQueries({ queryKey: [...resourceKeys(view.resource).all] });
601
+ };
602
+ const dismissConflict = () => {
603
+ // Closed without choosing: the edits stay, unsaved, and the screen still says why.
604
+ if (conflict) setRefusal(conflict.message);
605
+ setConflict(null);
606
+ };
540
607
 
541
608
  return (
542
609
  <View style={{ gap: 12 }}>
@@ -563,6 +630,16 @@ function SettingsGroup({
563
630
  {words.save}
564
631
  </NativeButton>
565
632
  ) : null}
633
+ <NativeConflictSheet
634
+ conflict={conflict?.conflict ?? null}
635
+ noun={view.noun}
636
+ label={(key) => fields.find((f) => f.key === key)?.label ?? key}
637
+ onKeepMine={keepMine}
638
+ onTakeTheirs={takeTheirs}
639
+ onDismiss={dismissConflict}
640
+ {...(words.conflict ? { messages: words.conflict } : {})}
641
+ testID={`${testID}-conflict`}
642
+ />
566
643
  </View>
567
644
  );
568
645
  }
@@ -21,12 +21,14 @@ import { SafeAreaView } from "react-native-safe-area-context";
21
21
  import type { BaseRecord, DataRow } from "@marktiderman/genesis-core";
22
22
  import { personTimeZone } from "@marktiderman/genesis-core/dates";
23
23
  import { scopeClock, useOne, useOptionalViewerScope } from "@marktiderman/genesis-core/hooks";
24
- import type { RowPicture } from "@marktiderman/genesis-core/resource-view";
24
+ import type { GalleryItem } from "@marktiderman/genesis-core/gallery";
25
+ import type { RowPicture, ViewGallery } from "@marktiderman/genesis-core/resource-view";
25
26
  import { NativeAvatar } from "../../components/avatar";
26
27
  import { NativeBadge } from "../../components/badge";
27
28
  import { NativeImage } from "../../components/image";
28
29
  import { NativeButton } from "../../components/button";
29
30
  import { NativeEmptyState } from "../../components/empty-state";
31
+ import { NativeGalleryGrid } from "../../components/gallery-grid";
30
32
  import { NativeInlineAlert } from "../../components/inline-alert";
31
33
  import { NativeListItem } from "../../components/list-item";
32
34
  import { NativeLoadingState } from "../../components/loading-state";
@@ -121,6 +123,12 @@ export interface NativeResourceViewProps<T extends Row = Row> extends NativeReso
121
123
  mode?: NativeResourceViewMode;
122
124
  /** Columns in grid mode (React Native's FlatList name). Default 2. */
123
125
  numColumns?: number;
126
+ /**
127
+ * With `mode="grid"`: overrides the view's `gallery` block, or adds one. With a gallery, grid mode
128
+ * draws a photo per row in justified rows (NativeGalleryGrid, the web's layout) in place of
129
+ * cards; a row without an image is a placeholder tile, and a press opens the row as a card's does.
130
+ */
131
+ gallery?: Partial<ViewGallery>;
124
132
  /**
125
133
  * Draws each row (list) or card (grid) yourself, as the web's `renderCard`. Spread
126
134
  * `card.pressableProps` on your Pressable for the press, long press and accessibility; the
@@ -460,6 +468,7 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
460
468
  searchable,
461
469
  mode = "list",
462
470
  numColumns: columnsProp,
471
+ gallery: screenGallery,
463
472
  renderCard,
464
473
  scopeTimeZone: _zone,
465
474
  testID = "native-resource-view",
@@ -692,42 +701,80 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
692
701
  const { formFields } = state;
693
702
  const createFields = useMemo(() => formFields("create"), [formFields]);
694
703
  const editFields = useMemo(() => formFields("edit"), [formFields]);
704
+ // A gallery block draws grid mode as photos: every loaded row, in order (no image: a placeholder).
705
+ const galleryKey = JSON.stringify(screenGallery ?? null);
706
+ const photos = useMemo(() => {
707
+ if (!grid || !(view.definition.gallery || screenGallery?.image)) return null;
708
+ const byId = new Map<string, T>();
709
+ const items: GalleryItem[] = [];
710
+ for (const section of state.sections) {
711
+ for (const row of section.data) {
712
+ const photo = view.galleryItem(row as never, screenGallery);
713
+ if (!photo) continue;
714
+ byId.set(photo.id, row);
715
+ items.push(photo);
716
+ }
717
+ }
718
+ return { items, byId };
719
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the override by value, not identity
720
+ }, [grid, view, galleryKey, state.sections]);
721
+ const galleryRowHeight = screenGallery?.rowHeight ?? view.definition.gallery?.rowHeight;
695
722
  const peekActions = peek ? actionsFor(peek, handlers) : [];
696
723
  const editLoading = sheet?.mode === "edit" && editRow.data === undefined && !editRow.isError;
697
724
 
698
725
  return (
699
726
  <SafeAreaView testID={testID} edges={["left", "right", "bottom"]} style={{ flex: 1, backgroundColor: colors.groupedBackground }}>
700
- <SectionList<T, NativeResourceSection<T>>
701
- testID={`${testID}-list`}
702
- // Grid mode hands the list lines of cards in place of rows; everything else is the same list.
703
- sections={grid ? (gridSections as unknown as NativeResourceSection<T>[]) : state.sections}
704
- keyExtractor={grid ? (gridKey as unknown as (row: T) => string) : keyExtractor}
705
- renderItem={grid ? (renderGridLine as unknown as typeof renderItem) : renderItem}
706
- renderSectionHeader={renderSectionHeader}
707
- // Rows read their item and actions besides `sections`; they change only with the view,
708
- // the bin capability or the words, never per keystroke.
709
- extraData={actionsFor}
710
- stickySectionHeadersEnabled={false}
711
- contentInsetAdjustmentBehavior="automatic"
712
- keyboardShouldPersistTaps="handled"
713
- ListHeaderComponent={listHeader}
714
- ListEmptyComponent={empty}
715
- ListFooterComponent={
716
- state.loadingMore ? (
717
- <NativeLoadingState fullScreen={false} size="small" label={messages.list.loadingMore} testID={`${testID}-more`} />
718
- ) : null
719
- }
720
- contentContainerStyle={{ flexGrow: 1, paddingBottom: 32 }}
721
- onEndReached={state.hasMore ? state.loadMore : undefined}
722
- onEndReachedThreshold={0.5}
723
- // maxPages drops pages from the front; reaching the top loads them back, and the rows on
724
- // screen keep their place while they're added above (VirtualizedList's onStartReached and
725
- // ScrollView's maintainVisibleContentPosition, both inherited by SectionList).
726
- onStartReached={state.hasPrevious ? state.loadPrevious : undefined}
727
- onStartReachedThreshold={0.5}
728
- maintainVisibleContentPosition={{ minIndexForVisible: 0 }}
729
- refreshControl={<NativeRefreshControl testID={`${testID}-refresh`} refreshing={state.refreshing} onRefresh={() => void state.refresh()} />}
730
- />
727
+ {photos ? (
728
+ <NativeGalleryGrid
729
+ testID={`${testID}-gallery`}
730
+ items={photos.items}
731
+ {...(galleryRowHeight !== undefined ? { rowHeight: galleryRowHeight } : {})}
732
+ onItemPress={(photo) => {
733
+ const row = photos.byId.get(photo.id);
734
+ if (row) press(row);
735
+ }}
736
+ header={
737
+ <>
738
+ {listHeader}
739
+ {photos.items.length === 0 ? empty : null}
740
+ </>
741
+ }
742
+ footer={state.loadingMore ? <NativeLoadingState fullScreen={false} size="small" label={messages.list.loadingMore} testID={`${testID}-more`} /> : null}
743
+ {...(state.hasMore ? { loadMore: state.loadMore } : {})}
744
+ />
745
+ ) : (
746
+ <SectionList<T, NativeResourceSection<T>>
747
+ testID={`${testID}-list`}
748
+ // Grid mode hands the list lines of cards in place of rows; everything else is the same list.
749
+ sections={grid ? (gridSections as unknown as NativeResourceSection<T>[]) : state.sections}
750
+ keyExtractor={grid ? (gridKey as unknown as (row: T) => string) : keyExtractor}
751
+ renderItem={grid ? (renderGridLine as unknown as typeof renderItem) : renderItem}
752
+ renderSectionHeader={renderSectionHeader}
753
+ // Rows read their item and actions besides `sections`; they change only with the view,
754
+ // the bin capability or the words, never per keystroke.
755
+ extraData={actionsFor}
756
+ stickySectionHeadersEnabled={false}
757
+ contentInsetAdjustmentBehavior="automatic"
758
+ keyboardShouldPersistTaps="handled"
759
+ ListHeaderComponent={listHeader}
760
+ ListEmptyComponent={empty}
761
+ ListFooterComponent={
762
+ state.loadingMore ? (
763
+ <NativeLoadingState fullScreen={false} size="small" label={messages.list.loadingMore} testID={`${testID}-more`} />
764
+ ) : null
765
+ }
766
+ contentContainerStyle={{ flexGrow: 1, paddingBottom: 32 }}
767
+ onEndReached={state.hasMore ? state.loadMore : undefined}
768
+ onEndReachedThreshold={0.5}
769
+ // maxPages drops pages from the front; reaching the top loads them back, and the rows on
770
+ // screen keep their place while they're added above (VirtualizedList's onStartReached and
771
+ // ScrollView's maintainVisibleContentPosition, both inherited by SectionList).
772
+ onStartReached={state.hasPrevious ? state.loadPrevious : undefined}
773
+ onStartReachedThreshold={0.5}
774
+ maintainVisibleContentPosition={{ minIndexForVisible: 0 }}
775
+ refreshControl={<NativeRefreshControl testID={`${testID}-refresh`} refreshing={state.refreshing} onRefresh={() => void state.refresh()} />}
776
+ />
777
+ )}
731
778
 
732
779
  <NativeSheet open={peek !== null} onOpenChange={(open) => (open ? undefined : setPeekId(null))} testID={`${testID}-peek`}>
733
780
  {peek ? (
@@ -12,7 +12,7 @@ import { QueryClient } from "@tanstack/react-query";
12
12
  import { useState, type ReactNode } from "react";
13
13
  import { ActionSheetIOS, Alert, Platform } from "react-native";
14
14
  import { beforeEach, describe, expect, it, vi } from "vitest";
15
- import { defineResource, GenesisProvider, ViewerScope, type DataProvider, type ListParams, type Viewer } from "@marktiderman/genesis-core";
15
+ import { DataWriteError, defineResource, GenesisProvider, ViewerScope, type DataProvider, type ListParams, type Viewer } from "@marktiderman/genesis-core";
16
16
  import { defineView, defineRecordView } from "@marktiderman/genesis-core/resource-view";
17
17
  import { getNativeRecordViewStackOptions, NativeRecordView, NativeRecordViewMenu, parseSettingNumber } from "..";
18
18
 
@@ -282,6 +282,100 @@ describe("NativeRecordView", () => {
282
282
  expect(within(screen.getByTestId("own-list")).getByTestId("native-resource-workspace-sections")).toBeTruthy();
283
283
  });
284
284
 
285
+ it("a conflict opens the conflict sheet: theirs above mine, then keep mine at the new version", async () => {
286
+ let calls = 0;
287
+ const update = vi.fn(async (_r: string, params: { id: unknown; data: unknown; expectedVersion?: string }) => {
288
+ calls += 1;
289
+ if (calls === 1) {
290
+ throw new DataWriteError("conflict", "Someone else changed this brand after you opened it.", {
291
+ current: { ...brand, website: "https://theirs.example" },
292
+ currentVersion: "7",
293
+ });
294
+ }
295
+ return { data: { ...brand, ...(params.data as object) } };
296
+ });
297
+ const p = provider({ update: update as unknown as DataProvider["update"] });
298
+ render(<NativeRecordView view={page} row={brand} section="settings" />, { wrapper: wrap(p) });
299
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-website-input"), { target: { value: "https://mine.example" } });
300
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
301
+ const field = await screen.findByTestId("native-resource-workspace-settings-conflict-field-website");
302
+ expect(field.textContent).toMatch(/Theirs.*theirs\.example.*Yours.*mine\.example/);
303
+ expect(screen.queryByTestId("native-resource-workspace-settings-refusal")).toBeNull();
304
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-conflict-keep-mine"));
305
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(2));
306
+ expect(update.mock.calls[1]![1]).toMatchObject({ data: { website: "https://mine.example" }, expectedVersion: "7" });
307
+ });
308
+
309
+ it("take theirs drops the section's edits", async () => {
310
+ const update = vi.fn(async () => {
311
+ throw new DataWriteError("conflict", "x", { current: { ...brand, website: "https://theirs.example" }, currentVersion: "7" });
312
+ });
313
+ const p = provider({ update: update as unknown as DataProvider["update"] });
314
+ render(<NativeRecordView view={page} row={brand} section="settings" />, { wrapper: wrap(p) });
315
+ const input = screen.getByTestId("native-resource-workspace-settings-website-input") as HTMLInputElement;
316
+ fireEvent.change(input, { target: { value: "https://mine.example" } });
317
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
318
+ fireEvent.click(await screen.findByTestId("native-resource-workspace-settings-conflict-take-theirs"));
319
+ await waitFor(() => expect(screen.queryByTestId("native-resource-workspace-settings-conflict-field-website")).toBeNull());
320
+ // Their value at once, before the record refetches.
321
+ expect((screen.getByTestId("native-resource-workspace-settings-website-input") as HTMLInputElement).value).toBe("https://theirs.example");
322
+ expect(update).toHaveBeenCalledTimes(1);
323
+ });
324
+
325
+ it("checks a settings save against the row the edit started on, not one that refreshed meanwhile", async () => {
326
+ const p = provider({
327
+ capabilities: vi.fn(async () => ({
328
+ search: false,
329
+ sort: false,
330
+ filterOperators: [],
331
+ bulkWrites: false,
332
+ versionedWrites: true,
333
+ compositeKeys: false,
334
+ version: { field: "version", kind: "integer" as const },
335
+ })),
336
+ });
337
+ const start = { ...brand, is_default: false, version: 1 };
338
+ const { rerender } = render(<NativeRecordView view={page} row={start} section="settings" />, { wrapper: wrap(p) });
339
+ await waitFor(() => expect(p.capabilities).toHaveBeenCalled());
340
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-website-input"), { target: { value: "https://mine.example" } });
341
+ rerender(<NativeRecordView view={page} row={{ ...start, public: true, version: 2 }} section="settings" />);
342
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
343
+ await waitFor(() => expect(p.update).toHaveBeenCalledTimes(1));
344
+ expect((p.update as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({ expectedVersion: "1" });
345
+ });
346
+
347
+ it("saves settings through the resource's write path: the version it commits reaches every cached copy", async () => {
348
+ const p = provider({
349
+ capabilities: vi.fn(async () => ({
350
+ search: false,
351
+ sort: false,
352
+ filterOperators: [],
353
+ bulkWrites: false,
354
+ versionedWrites: true,
355
+ compositeKeys: false,
356
+ version: { field: "version", kind: "integer" as const },
357
+ })),
358
+ update: vi.fn(async (_r: string, params: { data: unknown }) => ({ data: { ...brand, is_default: false, ...(params.data as object), version: 2 } })) as unknown as DataProvider["update"],
359
+ });
360
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
361
+ // Another screen's list of brands, read at version 1.
362
+ const listKey = ["brands", "list", { pagination: { page: 1, perPage: 25 } }];
363
+ queryClient.setQueryData(listKey, { data: [{ ...brand, is_default: false, version: 1 }], total: 1 });
364
+ render(
365
+ <GenesisProvider provider={p} queryClient={queryClient}>
366
+ <NativeRecordView view={page} row={{ ...brand, is_default: false, version: 1 }} section="settings" />
367
+ </GenesisProvider>,
368
+ );
369
+ await waitFor(() => expect(p.capabilities).toHaveBeenCalled());
370
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-website-input"), { target: { value: "https://mine.example" } });
371
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
372
+ await waitFor(() => expect(p.update).toHaveBeenCalledTimes(1));
373
+ expect((p.update as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({ expectedVersion: "1" });
374
+ // The list's copy carries the version this save left, so the next write of the row from that
375
+ // list is checked against it, not a false conflict with this save.
376
+ await waitFor(() => expect((queryClient.getQueryData(listKey) as { data: { version: unknown }[] }).data[0]!.version).toBe(2));
377
+ });
378
+
285
379
  it("shows a zero-row save as a refusal, inline", async () => {
286
380
  const p = provider({ update: vi.fn(async () => ({ data: null })) as unknown as DataProvider["update"] });
287
381
  render(<NativeRecordView view={page} row={brand} section="settings" />, { wrapper: wrap(p) });
@@ -0,0 +1,125 @@
1
+ // @feat:media-gallery @feat:resource-view-gallery @feat:native-components
2
+ /**
3
+ * NativeResourceView `mode="grid"` over a view's `gallery` block: a photo per row in
4
+ * NativeGalleryGrid's justified rows (the web's layout, from genesis-core), in place of cards.
5
+ * - a row without an image is still a tile; a press opens the row (onRowPress, else the peek);
6
+ * - list mode and a view without a gallery keep their cards and rows;
7
+ * - a screen's `gallery` overrides the view's block, or adds one.
8
+ */
9
+ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
10
+ import { QueryClient } from "@tanstack/react-query";
11
+ import type { ReactNode } from "react";
12
+ import { describe, expect, it, vi } from "vitest";
13
+ import { defineResource, GenesisProvider, type DataProvider } from "@marktiderman/genesis-core";
14
+ import { defineView } from "@marktiderman/genesis-core/resource-view";
15
+ import { NativeResourceView } from "..";
16
+
17
+ type Photo = { id: string; title: string; url: string | null; w: number | null; h: number | null; place: string };
18
+
19
+ const photos = defineResource<Photo>()({
20
+ name: "photos",
21
+ key: "id",
22
+ labelField: "title",
23
+ fields: [
24
+ { name: "id", type: "string", hasDefault: true },
25
+ { name: "title", type: "string" },
26
+ { name: "url", type: "string", nullable: true },
27
+ { name: "w", type: "number", nullable: true },
28
+ { name: "h", type: "number", nullable: true },
29
+ { name: "place", type: "string" },
30
+ ],
31
+ });
32
+
33
+ const ROWS: Photo[] = [
34
+ { id: "p1", title: "Harbour", url: "https://example.test/p1.jpg", w: 1600, h: 900, place: "Bay" },
35
+ { id: "p2", title: "Ridge", url: "https://example.test/p2.jpg", w: 900, h: 1200, place: "Hills" },
36
+ { id: "p3", title: "Not shot yet", url: null, w: null, h: null, place: "Town" },
37
+ ];
38
+
39
+ const view = defineView(photos, { columns: { default: ["title", "place"] }, gallery: { image: "url", width: "w", height: "h" } });
40
+ const plain = defineView(photos, { columns: { default: ["title", "place"] } });
41
+
42
+ function provider(): DataProvider {
43
+ return {
44
+ getList: vi.fn(async () => ({ data: ROWS, total: ROWS.length })),
45
+ getOne: vi.fn(async (_r, { id }) => ({ data: ROWS.find((r) => r.id === id) })),
46
+ getMany: vi.fn(async () => ({ data: [] })),
47
+ create: vi.fn(),
48
+ update: vi.fn(),
49
+ deleteOne: vi.fn(),
50
+ } as unknown as DataProvider;
51
+ }
52
+
53
+ function wrap(p: DataProvider) {
54
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
55
+ return ({ children }: { children: ReactNode }) => (
56
+ <GenesisProvider provider={p} queryClient={queryClient}>
57
+ {children}
58
+ </GenesisProvider>
59
+ );
60
+ }
61
+
62
+ /** The gallery lays out from its measured width: the shim turns a `layout` DOM event into onLayout. */
63
+ async function measured() {
64
+ const grid = await screen.findByTestId("native-resource-view-gallery");
65
+ act(() => {
66
+ grid.dispatchEvent(new CustomEvent("layout", { detail: { width: 400, height: 0 } }));
67
+ });
68
+ }
69
+ const tile = (id: string) => screen.queryByTestId(`native-resource-view-gallery-item-${id}`);
70
+
71
+ describe("NativeResourceView gallery", () => {
72
+ it("draws a photo per row with an image, in place of cards", async () => {
73
+ render(<NativeResourceView view={view} mode="grid" onRowPress={() => undefined} />, { wrapper: wrap(provider()) });
74
+ await measured();
75
+ await waitFor(() => expect(tile("p1")).not.toBeNull());
76
+ expect(tile("p2")).not.toBeNull();
77
+ expect(tile("p3")).not.toBeNull();
78
+ expect(screen.queryByTestId("native-resource-view-list")).toBeNull();
79
+ });
80
+
81
+ it("opens the row on a press: onRowPress, else the peek", async () => {
82
+ const onRowPress = vi.fn();
83
+ const { unmount } = render(<NativeResourceView view={view} mode="grid" onRowPress={onRowPress} />, { wrapper: wrap(provider()) });
84
+ await measured();
85
+ await waitFor(() => expect(tile("p2")).not.toBeNull());
86
+ fireEvent.click(tile("p2")!);
87
+ expect(onRowPress).toHaveBeenCalledWith(ROWS[1]);
88
+ unmount();
89
+ render(<NativeResourceView view={view} mode="grid" />, { wrapper: wrap(provider()) });
90
+ await measured();
91
+ await waitFor(() => expect(tile("p2")).not.toBeNull());
92
+ fireEvent.click(tile("p2")!);
93
+ expect(await screen.findByText("Hills")).toBeTruthy();
94
+ });
95
+
96
+ it("draws rows without an image as tiles that open, never the empty state over rows that exist", async () => {
97
+ const bare = provider();
98
+ (bare.getList as ReturnType<typeof vi.fn>).mockImplementation(async () => ({ data: [ROWS[2]], total: 1 }));
99
+ const onRowPress = vi.fn();
100
+ render(<NativeResourceView view={view} mode="grid" onRowPress={onRowPress} emptyState={<span>Nothing here</span>} />, { wrapper: wrap(bare) });
101
+ await measured();
102
+ await waitFor(() => expect(tile("p3")).not.toBeNull());
103
+ expect(screen.queryByText("Nothing here")).toBeNull();
104
+ expect(screen.queryByTestId("native-resource-view-gallery-placeholder-p3")).not.toBeNull();
105
+ fireEvent.click(tile("p3")!);
106
+ expect(onRowPress).toHaveBeenCalledWith(ROWS[2]);
107
+ });
108
+
109
+ it("keeps list mode, and a view without a gallery, as they were", async () => {
110
+ const { unmount } = render(<NativeResourceView view={view} />, { wrapper: wrap(provider()) });
111
+ expect(await screen.findByText("Not shot yet")).toBeTruthy();
112
+ expect(screen.queryByTestId("native-resource-view-gallery")).toBeNull();
113
+ unmount();
114
+ render(<NativeResourceView view={plain} mode="grid" />, { wrapper: wrap(provider()) });
115
+ expect(await screen.findByText("Not shot yet")).toBeTruthy();
116
+ expect(screen.queryByTestId("native-resource-view-gallery")).toBeNull();
117
+ });
118
+
119
+ it("takes a screen's gallery, on a view without one", async () => {
120
+ render(<NativeResourceView view={plain} mode="grid" gallery={{ image: "url" }} />, { wrapper: wrap(provider()) });
121
+ await measured();
122
+ await waitFor(() => expect(tile("p1")).not.toBeNull());
123
+ expect(tile("p3")).not.toBeNull();
124
+ });
125
+ });