@marktiderman/genesis-ui-native 3.4.0 → 3.5.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.
@@ -42,6 +42,16 @@ interface ScreenContainerProps {
42
42
  loading?: boolean;
43
43
  /** Text under the spinner while `loading`, and what screen readers announce: pass translated text. */
44
44
  loadingLabel?: string;
45
+ /**
46
+ * Pull to refresh: a theme-tinted `NativeRefreshControl` on the body, as InboxPage and
47
+ * NotificationsPage have. Pulling needs a scroll view, so passing it makes the body scroll
48
+ * (as `scroll`). Off unless passed. Never with a list child (FlatList, SectionList,
49
+ * NativeResourceView, InboxPage): a list inside a ScrollView loses virtualization, and those
50
+ * lists have their own pull to refresh.
51
+ */
52
+ onRefresh?: () => void | Promise<void>;
53
+ /** The refresh spinner shows while `true`: pass your query's refetching state. Default `false`. */
54
+ refreshing?: boolean;
45
55
  /** Style on the root, e.g. a theme-role background color. */
46
56
  style?: ViewStyle;
47
57
  /** testID on the root container. */
@@ -82,7 +92,7 @@ interface ScreenHeaderProps {
82
92
  * return <><Stack.Screen options={opts} /><ScreenContainer>...</ScreenContainer></>;
83
93
  */
84
94
  declare function composeHeaderOptions(props: ScreenHeaderProps): Record<string, unknown>;
85
- declare function ScreenContainer({ children, scroll, safeAreaEdges, statusBar, themeMode, className, contentClassName, keyboardShouldPersistTaps, loading, loadingLabel, style, testID, }: ScreenContainerProps): react.JSX.Element;
95
+ declare function ScreenContainer({ children, scroll, safeAreaEdges, statusBar, themeMode, className, contentClassName, keyboardShouldPersistTaps, loading, loadingLabel, onRefresh, refreshing, style, testID, }: ScreenContainerProps): react.JSX.Element;
86
96
 
87
97
  /** An action on a row: swipe, long press, or an accessibility action. */
88
98
  interface InboxSwipeAction {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { Box, BoxBackground, BoxProps, FULL_SCREEN_DARK, FlexAlign, FlexJustify, Grid, GridProps, Inline, InlineProps, NativeAccordion, NativeAccordionContent, NativeAccordionContentProps, NativeAccordionItem, NativeAccordionItemProps, NativeAccordionProps, NativeAccordionTrigger, NativeAccordionTriggerProps, NativeAccordionType, NativeAlert, NativeAlertDescription, NativeAlertDescriptionProps, NativeAlertProps, NativeAlertTitle, NativeAlertTitleProps, NativeAvatar, NativeAvatarProps, NativeBadge, NativeBadgeProps, NativeBanner, NativeBannerProps, NativeButton, NativeButtonProps, NativeCard, NativeCardContent, NativeCardDescription, NativeCardFooter, NativeCardHeader, NativeCardProps, NativeCardTitle, NativeCardTitleProps, NativeCheckbox, NativeCheckboxProps, NativeChip, NativeChipGroup, NativeChipGroupMode, NativeChipGroupProps, NativeChipProps, NativeCombobox, NativeComboboxOption, NativeComboboxProps, NativeDatePicker, NativeDatePickerProps, NativeDialog, NativeDialogContent, NativeDialogContentProps, NativeDialogDescription, NativeDialogDescriptionProps, NativeDialogFooter, NativeDialogFooterProps, NativeDialogHeader, NativeDialogHeaderProps, NativeDialogProps, NativeDialogTitle, NativeDialogTitleProps, NativeDrawer, NativeDrawerProps, NativeDropdownMenu, NativeDropdownMenuContent, NativeDropdownMenuContentProps, NativeDropdownMenuItem, NativeDropdownMenuItemProps, NativeDropdownMenuProps, NativeDropdownMenuTrigger, NativeDropdownMenuTriggerProps, NativeEmptyState, NativeEmptyStateProps, NativeEmptyStateVariant, NativeFullScreenModal, NativeFullScreenModalProps, NativeGlassSurface, NativeGlassSurfaceProps, NativeHeaderCard, NativeHeaderCardProps, NativeIcon, NativeIconProps, NativeImage, NativeImageProps, NativeInlineAlert, NativeInlineAlertProps, NativeInlineAlertVariant, NativeInput, NativeInputProps, NativeLabel, NativeLabelProps, NativeListItem, NativeListItemDivider, NativeListItemProps, NativeLoadingState, NativeLoadingStateEdge, NativeLoadingStateProps, NativeNumberInput, NativeNumberInputProps, NativePagination, NativePaginationProps, NativePopover, NativePopoverContent, NativePopoverContentProps, NativePopoverProps, NativePopoverTrigger, NativePopoverTriggerProps, NativeProgress, NativeProgressProps, NativeRadioGroup, NativeRadioGroupItem, NativeRadioGroupItemProps, NativeRadioGroupProps, NativeRangeSlider, NativeRangeSliderProps, NativeRefreshControl, NativeRefreshControlProps, NativeSearchBar, NativeSearchBarProps, NativeSectionListHeader, NativeSectionListHeaderProps, NativeSegmentedControl, NativeSegmentedControlOption, NativeSegmentedControlProps, NativeSelect, NativeSelectContent, NativeSelectContentProps, NativeSelectItem, NativeSelectItemProps, NativeSelectProps, NativeSelectTrigger, NativeSelectTriggerProps, NativeSeparator, NativeSeparatorProps, NativeSheet, NativeSheetLibrary, NativeSheetProps, NativeSheetProvider, NativeSheetProviderProps, NativeSheetScrollView, NativeSkeleton, NativeSkeletonProps, NativeSlider, NativeSliderProps, NativeStepper, NativeStepperProps, NativeStepperStep, NativeSwitch, NativeSwitchProps, NativeTabs, NativeTabsContent, NativeTabsContentProps, NativeTabsList, NativeTabsListProps, NativeTabsProps, NativeTabsTrigger, NativeTabsTriggerProps, NativeText, NativeTextProps, NativeTextarea, NativeTextareaProps, NativeTimePicker, NativeTimePickerProps, NativeToastOptions, NativeToastProvider, NativeToastProviderProps, NativeToastVariant, NativeToggle, NativeToggleProps, NativeTooltip, NativeTooltipContent, NativeTooltipContentProps, NativeTooltipProps, NativeTooltipTrigger, NativeTooltipTriggerProps, SpaceToken, SpacingPrefix, Stack, StackProps, TextPreset, alertVariants, badgeTextVariants, badgeVariants, buttonTextVariants, buttonVariants, spaceScale, spacingClass, textVariants, toggleVariants, useLiquidGlass, useReduceTransparency, useToast } from './components/index.js';
2
2
  export { G as GenesisDatePickerComponent, a as GenesisDatePickerProps, b as GenesisGlassModule, c as GenesisIconComponent, d as GenesisIconSet, e as GenesisImageComponent, f as GenesisImageProps, g as GenesisListComponent, h as GenesisListProps, i as GenesisModules, j as GenesisModulesProvider, k as GenesisModulesProviderProps, l as GenesisNavigationModule, m as GenesisNavigationTheme, n as GenesisReanimatedModule, o as GenesisSymbolComponent, p as GenesisSymbolProps, N as NATIVE_ICON_NAMES, q as NativeIconName, S as SF_SYMBOLS, u as useGenesisModules } from './native-modules-PwnGltOU.js';
3
3
  export { BrandExtensionsProvider, BrandExtensionsProviderProps, BrandExtensionsValue, ThemeMode, ThemeRoleColors, UseThemeRolesOptions, useGenesisExtension, useReducedMotion, useThemeMode, useThemeRoles } from './hooks/index.js';
4
- export { I as InboxItem, a as InboxPage, b as InboxPageProps, c as InboxPageSlotMap, d as InboxSwipeAction, S as SafeAreaEdge, e as ScreenContainer, f as ScreenContainerProps, g as ScreenHeaderProps, h as ScrollEdgeBehavior, i as composeHeaderOptions, j as formatInboxTime, k as getInboxPageStackOptions, s as showInboxActions } from './inbox-page-DZUR-PJ1.js';
4
+ export { I as InboxItem, a as InboxPage, b as InboxPageProps, c as InboxPageSlotMap, d as InboxSwipeAction, S as SafeAreaEdge, e as ScreenContainer, f as ScreenContainerProps, g as ScreenHeaderProps, h as ScrollEdgeBehavior, i as composeHeaderOptions, j as formatInboxTime, k as getInboxPageStackOptions, s as showInboxActions } from './inbox-page-BEarNEIP.js';
5
5
  export { AppleButtonModuleLike, AppleProviderOptions, AppleSignInButton, AppleSignInButtonProps, AuthBranding, AuthBrandingProps, AuthForm, AuthFormProps, AuthFormValues, AuthScreen, AuthScreenProps, AuthScreenSlotMap, ForgotPasswordLink, GoogleProviderOptions, KEYBOARD_TOOLBAR_HEIGHT, KeyboardScrollProps, KeyboardScrollProvider, KeyboardToolbarProps, NavBarSaveButton, NavBarSaveButtonProps, NavBarSearchBar, NavBarSearchBarProps, NavBarTitle, NavBarTitleProps, NotificationItem, NotificationsPage, NotificationsPageProps, NotificationsPageSlotMap, SettingsPage, SettingsPageDangerousAction, SettingsPageProps, SettingsPageRow, SettingsPageSection, SettingsPageSlotMap, SettingsSubPage, SettingsSubPageProps, SocialAuthProvider, SocialAuthRow, SocialAuthRowProps, ThreadAttachment, ThreadComposer, ThreadLabels, ThreadMessage, ThreadPage, ThreadPageProps, ThreadPageSlotMap, appleProvider, confirmDiscardChanges, defaultStickyHeaderOffset, getNotificationsPageStackOptions, getSettingsPageStackOptions, getSettingsSubPageStackOptions, getThreadPageStackOptions, googleProvider, iosCompactNavigationBarHeight, readReceiptFor, useKeyboardScroll, useKeyboardToolbar } from './layouts/index.js';
6
6
  export { cn } from './utils.js';
7
7
  import 'react';
package/dist/index.js CHANGED
@@ -2,8 +2,8 @@ export { Box, FULL_SCREEN_DARK, Grid, Inline, NativeAccordion, NativeAccordionCo
2
2
  export { NativeAlert, NativeAlertDescription, NativeAlertTitle, NativeAvatar, NativeBanner, NativeCard, NativeCardContent, NativeCardDescription, NativeCardFooter, NativeCardHeader, NativeCardTitle, NativeCheckbox, NativeDatePicker, NativeImage, NativeInlineAlert, NativeLabel, NativeSearchBar, NativeSegmentedControl, NativeSelect, NativeSelectContent, NativeSelectItem, NativeSelectTrigger, NativeSeparator, NativeSheet, NativeSheetProvider, NativeSheetScrollView, NativeSkeleton, NativeSwitch, NativeTextarea, NativeTimePicker, alertVariants } from './chunk-GHYUNNNU.js';
3
3
  export { BrandExtensionsProvider, useGenesisExtension } from './chunk-D5RKSPMH.js';
4
4
  export { useReducedMotion } from './chunk-7PCWEY6R.js';
5
- export { AppleSignInButton, AuthBranding, AuthForm, AuthScreen, ForgotPasswordLink, KEYBOARD_TOOLBAR_HEIGHT, KeyboardScrollProvider, NotificationsPage, SettingsPage, SettingsSubPage, SocialAuthRow, ThreadPage, appleProvider, confirmDiscardChanges, defaultStickyHeaderOffset, getNotificationsPageStackOptions, getSettingsPageStackOptions, getSettingsSubPageStackOptions, getThreadPageStackOptions, googleProvider, iosCompactNavigationBarHeight, readReceiptFor, useKeyboardScroll, useKeyboardToolbar } from './chunk-VZ3PQLZ4.js';
6
- export { InboxPage, NavBarSaveButton, NavBarSearchBar, NavBarTitle, ScreenContainer, composeHeaderOptions, formatInboxTime, getInboxPageStackOptions, showInboxActions } from './chunk-ZHVQTMNV.js';
5
+ export { AppleSignInButton, AuthBranding, AuthForm, AuthScreen, ForgotPasswordLink, KEYBOARD_TOOLBAR_HEIGHT, KeyboardScrollProvider, NotificationsPage, SettingsPage, SettingsSubPage, SocialAuthRow, ThreadPage, appleProvider, confirmDiscardChanges, defaultStickyHeaderOffset, getNotificationsPageStackOptions, getSettingsPageStackOptions, getSettingsSubPageStackOptions, getThreadPageStackOptions, googleProvider, iosCompactNavigationBarHeight, readReceiptFor, useKeyboardScroll, useKeyboardToolbar } from './chunk-ABVSSJNT.js';
6
+ export { InboxPage, NavBarSaveButton, NavBarSearchBar, NavBarTitle, ScreenContainer, composeHeaderOptions, formatInboxTime, getInboxPageStackOptions, showInboxActions } from './chunk-ONH2PCGH.js';
7
7
  export { GenesisModulesProvider, NATIVE_ICON_NAMES, NativeBadge, NativeButton, NativeEmptyState, NativeIcon, NativeInput, NativeListItem, NativeListItemDivider, NativeLoadingState, NativeRefreshControl, NativeSectionListHeader, NativeText, SF_SYMBOLS, badgeTextVariants, badgeVariants, buttonTextVariants, buttonVariants, textVariants, useGenesisModules } from './chunk-6KWEAGRD.js';
8
8
  export { useThemeMode, useThemeRoles } from './chunk-Z3AQYVUA.js';
9
9
  export { cn } from './chunk-OHZD7KRO.js';
@@ -1,5 +1,5 @@
1
- import { g as ScreenHeaderProps } from '../inbox-page-DZUR-PJ1.js';
2
- export { I as InboxItem, a as InboxPage, b as InboxPageProps, c as InboxPageSlotMap, d as InboxSwipeAction, S as SafeAreaEdge, e as ScreenContainer, f as ScreenContainerProps, h as ScrollEdgeBehavior, i as composeHeaderOptions, j as formatInboxTime, k as getInboxPageStackOptions, s as showInboxActions } from '../inbox-page-DZUR-PJ1.js';
1
+ import { g as ScreenHeaderProps } from '../inbox-page-BEarNEIP.js';
2
+ export { I as InboxItem, a as InboxPage, b as InboxPageProps, c as InboxPageSlotMap, d as InboxSwipeAction, S as SafeAreaEdge, e as ScreenContainer, f as ScreenContainerProps, h as ScrollEdgeBehavior, i as composeHeaderOptions, j as formatInboxTime, k as getInboxPageStackOptions, s as showInboxActions } from '../inbox-page-BEarNEIP.js';
3
3
  import * as react from 'react';
4
4
  import { ReactNode, ComponentType } from 'react';
5
5
  import { Slots, SlotPropsFor } from '@marktiderman/genesis-core/slots';
@@ -1,5 +1,5 @@
1
- export { AppleSignInButton, AuthBranding, AuthForm, AuthScreen, ForgotPasswordLink, KEYBOARD_TOOLBAR_HEIGHT, KeyboardScrollProvider, NotificationsPage, SettingsPage, SettingsSubPage, SocialAuthRow, ThreadPage, appleProvider, confirmDiscardChanges, defaultStickyHeaderOffset, getNotificationsPageStackOptions, getSettingsPageStackOptions, getSettingsSubPageStackOptions, getThreadPageStackOptions, googleProvider, iosCompactNavigationBarHeight, readReceiptFor, useKeyboardScroll, useKeyboardToolbar } from '../chunk-VZ3PQLZ4.js';
2
- export { InboxPage, NavBarSaveButton, NavBarSearchBar, NavBarTitle, ScreenContainer, composeHeaderOptions, formatInboxTime, getInboxPageStackOptions, showInboxActions } from '../chunk-ZHVQTMNV.js';
1
+ export { AppleSignInButton, AuthBranding, AuthForm, AuthScreen, ForgotPasswordLink, KEYBOARD_TOOLBAR_HEIGHT, KeyboardScrollProvider, NotificationsPage, SettingsPage, SettingsSubPage, SocialAuthRow, ThreadPage, appleProvider, confirmDiscardChanges, defaultStickyHeaderOffset, getNotificationsPageStackOptions, getSettingsPageStackOptions, getSettingsSubPageStackOptions, getThreadPageStackOptions, googleProvider, iosCompactNavigationBarHeight, readReceiptFor, useKeyboardScroll, useKeyboardToolbar } from '../chunk-ABVSSJNT.js';
2
+ export { InboxPage, NavBarSaveButton, NavBarSearchBar, NavBarTitle, ScreenContainer, composeHeaderOptions, formatInboxTime, getInboxPageStackOptions, showInboxActions } from '../chunk-ONH2PCGH.js';
3
3
  import '../chunk-6KWEAGRD.js';
4
4
  import '../chunk-Z3AQYVUA.js';
5
5
  import '../chunk-OHZD7KRO.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-ui-native",
3
- "version": "3.4.0",
3
+ "version": "3.5.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -83,7 +83,7 @@
83
83
  "@expo/ui": ">=58.0.0",
84
84
  "@gorhom/bottom-sheet": ">=5.0.0",
85
85
  "@hookform/resolvers": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0",
86
- "@marktiderman/genesis-core": "^2.6.0",
86
+ "@marktiderman/genesis-core": "^2.8.0",
87
87
  "@marktiderman/genesis-design-system": "^1.7.0",
88
88
  "@react-native-community/datetimepicker": ">=8.0.0",
89
89
  "@shopify/flash-list": ">=2.0.0",
@@ -9,12 +9,12 @@
9
9
  // - readiness → a summary chip, then the checks while any is unmet.
10
10
  // A section with neither list nor settings is the screen's own, through `slots[id]`.
11
11
 
12
- import { useMemo, useRef, useState, type ReactNode } from "react";
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
15
  import { DataWriteError, resourceKeys, useCapabilities, useDataProvider, useViewer, type DataRow, type ResourceContract } from "@marktiderman/genesis-core";
16
16
  import { readinessChip, type ReadinessLabels } from "@marktiderman/genesis-core/resource";
17
- import type { Allowed, RecordView as RecordViewDef, RecordViewHeaderAction } from "@marktiderman/genesis-core/resource-view";
17
+ import { sameFormValue, type Allowed, type RecordView as RecordViewDef, type RecordViewHeaderAction } from "@marktiderman/genesis-core/resource-view";
18
18
  import { NativeBadge } from "../../components/badge";
19
19
  import { NativeButton } from "../../components/button";
20
20
  import { NativeIcon } from "../../components/icon";
@@ -498,19 +498,29 @@ function SettingsGroup({
498
498
  // The view's update guard, for this viewer: when it refuses, the settings are read-only with its reason.
499
499
  const viewer = useViewer();
500
500
  const locked = recordView.settingsLocked(row, viewer);
501
- const [draft, setDraft] = useState<Values>(() => Object.fromEntries(fields.map((f) => [f.key, row[f.key]])));
501
+ // Only the fields this person changed are theirs: the others show the row as it is now (a live
502
+ // refresh updates them) and are never sent, so a stale draft can't overwrite someone else's change.
503
+ const [edits, setEdits] = useState<Values>({});
504
+ const draft = useMemo<Values>(() => ({ ...Object.fromEntries(fields.map((f) => [f.key, row[f.key]])), ...edits }), [fields, row, edits]);
505
+ // An edit the row now holds (after a save, or someone else's same change) is no longer an edit.
506
+ useEffect(() => {
507
+ setEdits((current) => {
508
+ const left = Object.fromEntries(Object.entries(current).filter(([k, v]) => !sameFormValue(v, row[k])));
509
+ return Object.keys(left).length === Object.keys(current).length ? current : left;
510
+ });
511
+ }, [row]);
502
512
  const [invalid, setInvalid] = useState<Record<string, string>>({});
503
513
  const [saving, setSaving] = useState(false);
504
514
  const [refusal, setRefusal] = useState<string | null>(null);
505
515
  const shown = fields.filter((f) => !f.visible || f.visible(draft));
506
516
  const changed: Values = {};
507
- for (const f of shown) if (draft[f.key] !== row[f.key]) changed[f.key] = draft[f.key];
517
+ for (const f of shown) if (f.key in edits && !sameFormValue(draft[f.key], row[f.key])) changed[f.key] = draft[f.key];
508
518
  const dirty = Object.keys(changed).length > 0 && !shown.some((f) => invalid[f.key]);
509
519
 
510
520
  const set = (key: string, value: unknown, error?: string) => {
511
521
  setRefusal(null);
512
522
  setInvalid(({ [key]: _old, ...rest }) => (error ? { ...rest, [key]: error } : rest));
513
- setDraft((d) => ({ ...d, [key]: value }));
523
+ setEdits((d) => ({ ...d, [key]: value }));
514
524
  };
515
525
  const save = async () => {
516
526
  setSaving(true);
@@ -6,6 +6,8 @@
6
6
  // the `swipeable` slot for the gesture), every refusal with its reason;
7
7
  // - `view.form(mode)` + `view.writable(mode)` → the form sheet, over the row fetched by id,
8
8
  // sending only the writable fields the person changed.
9
+ // - `mode="grid"` → cards in `numColumns` columns (as the web's `mode="grid"`); `renderCard` →
10
+ // the app's own row or card, wired by the screen (press, long press, accessibility, swipe).
9
11
  // Paging is by cursor on `onEndReached`, search is debounced 300 ms, a delete is optimistic and
10
12
  // comes back if the server refuses, and a refusal shows inline in plain words.
11
13
  //
@@ -13,10 +15,10 @@
13
15
  // VirtualizedList and a PureComponent): a memoised row component, a stable `renderItem` and
14
16
  // `keyExtractor`, and `extraData` only for what rows read besides their item.
15
17
 
16
- import { memo, useCallback, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";
18
+ import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";
17
19
  import { Alert, Platform, Pressable, SectionList, View } from "react-native";
18
20
  import { SafeAreaView } from "react-native-safe-area-context";
19
- import { encodeRecordKey, type BaseRecord, type DataRow } from "@marktiderman/genesis-core";
21
+ import type { BaseRecord, DataRow } from "@marktiderman/genesis-core";
20
22
  import { personTimeZone } from "@marktiderman/genesis-core/dates";
21
23
  import { scopeClock, useOne, useOptionalViewerScope } from "@marktiderman/genesis-core/hooks";
22
24
  import type { RowPicture } from "@marktiderman/genesis-core/resource-view";
@@ -47,6 +49,7 @@ import type { AnyResourceView, NativeResourceRowItem, NativeResourceSection, Nat
47
49
  import { fill } from "./messages";
48
50
  import { NativeResourceFormSheet } from "./NativeResourceFormSheet";
49
51
  import {
52
+ recordKey,
50
53
  useNativeResourceView,
51
54
  type NativeResourceViewOptions,
52
55
  type UseNativeResourceViewReturn,
@@ -59,6 +62,41 @@ export type NativeResourceSwipeableProps = Omit<InboxPageSlotMap["swipeable"], "
59
62
  actions: NativeResourceSwipeAction[];
60
63
  };
61
64
 
65
+ /** How rows show: a list (the default) or cards in columns, as the web's `mode`. */
66
+ export type NativeResourceViewMode = "list" | "grid";
67
+
68
+ /**
69
+ * Spread onto your card's Pressable: the press (the screen's `onRowPress`, else the peek), the
70
+ * long press (the row's actions), and the label and actions screen readers use. The same wiring
71
+ * the built-in rows have, so a custom card never hand-rolls it.
72
+ */
73
+ export interface NativeResourceCardPressableProps {
74
+ testID: string;
75
+ accessibilityRole: "button";
76
+ accessibilityLabel: string;
77
+ accessibilityActions: { name: string; label: string }[];
78
+ onAccessibilityAction: (event: { nativeEvent: { actionName: string } }) => void;
79
+ onPress: () => void;
80
+ onLongPress: (() => void) | undefined;
81
+ }
82
+
83
+ /** What `renderCard` gets beside the row: the native counterpart of the web's ResourceCardActions. */
84
+ export interface NativeResourceCardActions {
85
+ /** `view.summary(row)`: the title, subtitle, chips and picture the built-in row draws. */
86
+ item: NativeResourceRowItem;
87
+ /** The row's actions (edit, delete), each refusal with its reason; pressing one acts or explains. */
88
+ actions: NativeResourceSwipeAction[];
89
+ /** Opens the row, as pressing a built-in row does. */
90
+ open: () => void;
91
+ /** Shows the row's actions in an action sheet (what a long press does). */
92
+ showActions: () => void;
93
+ /** Everything above, for a Pressable: `<Pressable {...card.pressableProps}>`. */
94
+ pressableProps: NativeResourceCardPressableProps;
95
+ /** First and last in its section (list mode), for rounded group corners and separators. */
96
+ first: boolean;
97
+ last: boolean;
98
+ }
99
+
62
100
  export interface NativeResourceViewProps<T extends Row = Row> extends NativeResourceViewOptions<T> {
63
101
  view: AnyResourceView<T>;
64
102
  /** The heading above the list. Default the view's title; `false` when the navigation bar shows it. */
@@ -75,6 +113,22 @@ export interface NativeResourceViewProps<T extends Row = Row> extends NativeReso
75
113
  header?: ReactNode;
76
114
  /** Replaces the empty state. */
77
115
  emptyState?: ReactNode;
116
+ /**
117
+ * `"grid"`: cards in `numColumns` columns, as the web's `mode="grid"`. Sections, paging, pull to
118
+ * refresh, the empty and error states, long press, accessibility and swipe actions all stay.
119
+ * Default `"list"`.
120
+ */
121
+ mode?: NativeResourceViewMode;
122
+ /** Columns in grid mode (React Native's FlatList name). Default 2. */
123
+ numColumns?: number;
124
+ /**
125
+ * Draws each row (list) or card (grid) yourself, as the web's `renderCard`. Spread
126
+ * `card.pressableProps` on your Pressable for the press, long press and accessibility; the
127
+ * screen still wraps it in `swipeable`. It owns the whole row: no inset group cell or separator
128
+ * is drawn around it. `index` is the row's place in its section. Pass a stable function
129
+ * (`useCallback`) so rows redraw only when their data does.
130
+ */
131
+ renderCard?: (row: T, index: number, card: NativeResourceCardActions) => ReactNode;
78
132
  /** Hide the search box. Shown by default when the view has something to search. */
79
133
  searchable?: boolean;
80
134
  /**
@@ -92,14 +146,7 @@ const IOS_GROUP_MARGIN = 16;
92
146
  const GROUP_RADIUS = Number.parseFloat(String(Platform.Version)) >= 26 ? 26 : 10;
93
147
  const IOS = Platform.OS === "ios";
94
148
 
95
- // Rows are keyed by the view's key fields (`keyFields`), so composite keys never collide.
96
- const recordKey = (view: AnyResourceView<Row>, row: Row) => {
97
- try {
98
- return String(encodeRecordKey(view.contract, row as DataRow));
99
- } catch {
100
- return String((row as DataRow).id);
101
- }
102
- };
149
+ // Rows are keyed by the view's key fields (`recordKey`, shared with the hook), so composite keys never collide.
103
150
 
104
151
  /**
105
152
  * A native list screen from a view:
@@ -125,6 +172,7 @@ export function NativeResourceView<T extends Row = Row>(props: NativeResourceVie
125
172
  }
126
173
 
127
174
  interface RowProps<T extends Row> {
175
+ view: AnyResourceView<T>;
128
176
  row: T;
129
177
  first: boolean;
130
178
  last: boolean;
@@ -173,6 +221,47 @@ function RowLeading({ picture, testID }: { picture: RowPicture; testID: string }
173
221
  );
174
222
  }
175
223
 
224
+ /** The press, long press and accessibility of one row or card: shared by every way a row draws. */
225
+ function cardFor<T extends Row>(
226
+ row: T,
227
+ { item: itemFor, actions: actionsFor, handlers, onPress, cancelLabel, testID, first, last }: Pick<RowProps<T>, "item" | "actions" | "handlers" | "onPress" | "cancelLabel" | "testID" | "first" | "last">,
228
+ ): NativeResourceCardActions {
229
+ const item: NativeResourceRowItem = itemFor(row);
230
+ const actions = actionsFor(row, handlers);
231
+ const chip = item.chips[0];
232
+ const picture = item.picture;
233
+ const open = () => onPress(row);
234
+ const showActions = () => showInboxActions(item.title, actions, cancelLabel);
235
+ return {
236
+ item,
237
+ actions,
238
+ open,
239
+ showActions,
240
+ first,
241
+ last,
242
+ pressableProps: {
243
+ testID: `${testID}-row-${item.id}`,
244
+ accessibilityRole: "button",
245
+ accessibilityLabel: [picture?.kind === "image" ? picture.alt : null, item.title, item.subtitle, chip?.label].filter(Boolean).join(", "),
246
+ accessibilityActions: actions.map((a) => ({ name: a.id, label: a.reason ? `${a.label}: ${a.reason}` : a.label })),
247
+ onAccessibilityAction: (event) => actions.find((a) => a.id === event.nativeEvent.actionName)?.onPress(),
248
+ onPress: open,
249
+ onLongPress: actions.length ? showActions : undefined,
250
+ },
251
+ };
252
+ }
253
+
254
+ /** Wraps a row in the screen's swipe gesture when it has actions and the screen passed one. */
255
+ function withSwipe(content: ReactNode, card: NativeResourceCardActions, Swipeable: ComponentType<NativeResourceSwipeableProps> | undefined) {
256
+ return card.actions.length && Swipeable ? (
257
+ <Swipeable actions={card.actions} testID={`${card.pressableProps.testID}-swipe`}>
258
+ {content}
259
+ </Swipeable>
260
+ ) : (
261
+ content
262
+ );
263
+ }
264
+
176
265
  /** One row. Memoised: it redraws only when its row or what it reads changes, not per keystroke. */
177
266
  const ResourceRow = memo(function ResourceRow<T extends Row>({
178
267
  row,
@@ -189,11 +278,11 @@ const ResourceRow = memo(function ResourceRow<T extends Row>({
189
278
  separator,
190
279
  testID,
191
280
  }: RowProps<T>) {
192
- const item: NativeResourceRowItem = itemFor(row);
193
- const actions = actionsFor(row, handlers);
281
+ const card = cardFor(row, { item: itemFor, actions: actionsFor, handlers, onPress, cancelLabel, testID, first, last });
282
+ const { item, pressableProps } = card;
194
283
  const chip = item.chips[0];
195
284
  const picture = item.picture;
196
- const rowTestID = `${testID}-row-${item.id}`;
285
+ const rowTestID = pressableProps.testID;
197
286
  const content = (
198
287
  <View
199
288
  testID={`${rowTestID}-cell`}
@@ -211,15 +300,7 @@ const ResourceRow = memo(function ResourceRow<T extends Row>({
211
300
  : null,
212
301
  ]}
213
302
  >
214
- <Pressable
215
- testID={rowTestID}
216
- accessibilityRole="button"
217
- accessibilityLabel={[picture?.kind === "image" ? picture.alt : null, item.title, item.subtitle, chip?.label].filter(Boolean).join(", ")}
218
- accessibilityActions={actions.map((a) => ({ name: a.id, label: a.reason ? `${a.label}: ${a.reason}` : a.label }))}
219
- onAccessibilityAction={(event) => actions.find((a) => a.id === event.nativeEvent.actionName)?.onPress()}
220
- onPress={() => onPress(row)}
221
- onLongPress={actions.length ? () => showInboxActions(item.title, actions, cancelLabel) : undefined}
222
- >
303
+ <Pressable {...pressableProps}>
223
304
  <NativeListItem
224
305
  testID={`${rowTestID}-item`}
225
306
  title={item.title}
@@ -239,15 +320,134 @@ const ResourceRow = memo(function ResourceRow<T extends Row>({
239
320
  {!last ? <View style={{ height: 0.5, marginLeft: 16, backgroundColor: separator }} /> : null}
240
321
  </View>
241
322
  );
242
- return actions.length && Swipeable ? (
243
- <Swipeable actions={actions} testID={`${rowTestID}-swipe`}>
244
- {content}
245
- </Swipeable>
246
- ) : (
247
- content
248
- );
323
+ return withSwipe(content, card, Swipeable);
249
324
  }) as <T extends Row>(props: RowProps<T>) => ReactNode;
250
325
 
326
+ type RenderCard<T extends Row> = NonNullable<NativeResourceViewProps<T>["renderCard"]>;
327
+
328
+ /** A row the app draws (`renderCard`), with the screen's wiring and swipe around it. */
329
+ const CustomRow = memo(function CustomRow<T extends Row>(props: RowProps<T> & { index: number; renderCard: RenderCard<T> }) {
330
+ const card = cardFor(props.row, props);
331
+ return withSwipe(props.renderCard(props.row, props.index, card), card, props.Swipeable);
332
+ }) as <T extends Row>(props: RowProps<T> & { index: number; renderCard: RenderCard<T> }) => ReactNode;
333
+
334
+ /** The space between grid cards and around the grid, in points. */
335
+ const GRID_GAP = 12;
336
+
337
+ /** The built-in grid card: the row's picture, title, subtitle and chip on the surface. */
338
+ function GridCard<T extends Row>(props: RowProps<T>) {
339
+ const card = cardFor(props.row, props);
340
+ const { item, pressableProps } = card;
341
+ const chip = item.chips[0];
342
+ const content = (
343
+ <Pressable
344
+ {...pressableProps}
345
+ style={{ backgroundColor: props.surface, borderRadius: GROUP_RADIUS, padding: 12, gap: 8, minHeight: 44, flexGrow: 1 }}
346
+ >
347
+ {item.picture ? <RowLeading picture={item.picture} testID={pressableProps.testID} /> : null}
348
+ <NativeText preset="label" numberOfLines={2}>
349
+ {item.title}
350
+ </NativeText>
351
+ {item.subtitle ? (
352
+ <NativeText preset="body-sm" className="text-muted-foreground" numberOfLines={2}>
353
+ {item.subtitle}
354
+ </NativeText>
355
+ ) : null}
356
+ {chip ? (
357
+ <View style={{ flexDirection: "row" }}>
358
+ <NativeBadge testID={`${pressableProps.testID}-chip`} variant={badgeVariant(chip.tone)}>
359
+ {chip.label}
360
+ </NativeBadge>
361
+ </View>
362
+ ) : null}
363
+ </Pressable>
364
+ );
365
+ return withSwipe(content, card, props.Swipeable);
366
+ }
367
+
368
+ /**
369
+ * A grid line: line `n` of a section holds the section's rows `n * numColumns` up to the next
370
+ * line, counted from the section's real start, rows `maxPages` dropped included. So a line is
371
+ * the same line whatever pages are loaded, and its key never changes while it's on screen.
372
+ */
373
+ interface GridLine<T> {
374
+ key: string;
375
+ /** The first row's place in its section. */
376
+ index: number;
377
+ /** Empty columns before the first row: the rest of the line was dropped from the front. */
378
+ lead: number;
379
+ rows: T[];
380
+ /** The section's last row's place, when this line holds it; else -1. */
381
+ lastIndex: number;
382
+ }
383
+
384
+ type GridLineProps<T extends Row> = Omit<RowProps<T>, "row" | "first" | "last"> & {
385
+ line: GridLine<T>;
386
+ numColumns: number;
387
+ renderCard: RenderCard<T> | undefined;
388
+ };
389
+
390
+ /** One line of the grid. Memoised like a row; spacers keep each card in its column. */
391
+ const GridRow = memo(function GridRow<T extends Row>({ line, numColumns, renderCard, ...shared }: GridLineProps<T>) {
392
+ const cells: ReactNode[] = [];
393
+ for (let i = 0; i < line.lead; i += 1) cells.push(<View key={`lead-${i}`} style={{ flex: 1 }} />);
394
+ line.rows.forEach((row, offset) => {
395
+ const index = line.index + offset;
396
+ const props = { ...shared, row, first: index === 0, last: index === line.lastIndex };
397
+ cells.push(
398
+ <View key={recordKey(shared.view as AnyResourceView<Row>, row)} style={{ flex: 1 }}>
399
+ {renderCard ? <CustomRow<T> {...props} index={index} renderCard={renderCard} /> : <GridCard<T> {...props} />}
400
+ </View>,
401
+ );
402
+ });
403
+ for (let i = line.lead + line.rows.length; i < numColumns; i += 1) cells.push(<View key={`spacer-${i}`} style={{ flex: 1 }} />);
404
+ return (
405
+ <View testID={`${shared.testID}-grid-line-${line.key}`} style={{ flexDirection: "row", gap: GRID_GAP, paddingHorizontal: 16, paddingBottom: GRID_GAP }}>
406
+ {cells}
407
+ </View>
408
+ );
409
+ }) as <T extends Row>(props: GridLineProps<T>) => ReactNode;
410
+
411
+ /**
412
+ * A section's loaded rows cut into grid lines of `numColumns`, `above` of its rows being above
413
+ * the loaded window. A line whose rows haven't changed is the same object as last time
414
+ * (`previous`), so its memoised GridRow skips the redraw.
415
+ */
416
+ export function gridLines<T>(
417
+ sectionKey: string,
418
+ rows: T[],
419
+ above: number,
420
+ numColumns: number,
421
+ previous: Map<string, GridLine<T>> = new Map(),
422
+ ): GridLine<T>[] {
423
+ const lines: GridLine<T>[] = [];
424
+ const lastIndex = above + rows.length - 1;
425
+ let j = 0;
426
+ while (j < rows.length) {
427
+ const index = above + j;
428
+ const n = Math.floor(index / numColumns);
429
+ const lead = index - n * numColumns;
430
+ const take = numColumns - lead;
431
+ const next: GridLine<T> = {
432
+ key: `${sectionKey || "none"}-${n}`,
433
+ index,
434
+ lead,
435
+ rows: rows.slice(j, j + take),
436
+ lastIndex: index + take > lastIndex ? lastIndex : -1,
437
+ };
438
+ const old = previous.get(next.key);
439
+ const same =
440
+ old !== undefined &&
441
+ old.index === next.index &&
442
+ old.lastIndex === next.lastIndex &&
443
+ old.rows.length === next.rows.length &&
444
+ old.rows.every((row, i) => row === next.rows[i]);
445
+ lines.push(same ? old : next);
446
+ j += take;
447
+ }
448
+ return lines;
449
+ }
450
+
251
451
  function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
252
452
  const {
253
453
  view,
@@ -258,6 +458,9 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
258
458
  header,
259
459
  emptyState,
260
460
  searchable,
461
+ mode = "list",
462
+ numColumns: columnsProp,
463
+ renderCard,
261
464
  scopeTimeZone: _zone,
262
465
  testID = "native-resource-view",
263
466
  ...options
@@ -304,25 +507,67 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
304
507
  const press = useCallback((row: T) => (rowPress.current ? rowPress.current(row) : setPeekId({ row })), []);
305
508
  const chevron = !!onRowPress;
306
509
 
510
+ const shared = useMemo(
511
+ () => ({
512
+ view,
513
+ item: itemFor,
514
+ actions: actionsFor,
515
+ handlers,
516
+ onPress: press,
517
+ chevron,
518
+ Swipeable,
519
+ cancelLabel: messages.common.cancel,
520
+ surface: colors.surface as string,
521
+ separator: colors.separator as string,
522
+ testID,
523
+ }),
524
+ [view, itemFor, actionsFor, handlers, press, chevron, Swipeable, messages, colors.surface, colors.separator, testID],
525
+ );
307
526
  const renderItem = useCallback(
308
- ({ item: row, index, section }: { item: T; index: number; section: NativeResourceSection<T> }) => (
309
- <ResourceRow<T>
310
- row={row}
311
- first={index === 0}
312
- last={index === section.data.length - 1}
313
- item={itemFor}
314
- actions={actionsFor}
315
- handlers={handlers}
316
- onPress={press}
317
- chevron={chevron}
318
- Swipeable={Swipeable}
319
- cancelLabel={messages.common.cancel}
320
- surface={colors.surface as string}
321
- separator={colors.separator as string}
322
- testID={testID}
323
- />
324
- ),
325
- [itemFor, actionsFor, handlers, press, chevron, Swipeable, messages, colors.surface, colors.separator, testID],
527
+ ({ item: row, index, section }: { item: T; index: number; section: NativeResourceSection<T> }) => {
528
+ const props = { ...shared, row, first: index === 0, last: index === section.data.length - 1 };
529
+ return renderCard ? <CustomRow<T> {...props} index={index} renderCard={renderCard} /> : <ResourceRow<T> {...props} />;
530
+ },
531
+ [shared, renderCard],
532
+ );
533
+
534
+ // Grid mode: each section's rows in lines of `numColumns`. SectionList has no columns of its
535
+ // own, so a line is one item; sections, paging and refresh stay the list's.
536
+ const numColumns = Math.max(1, Math.floor(columnsProp ?? 2));
537
+ const grid = mode === "grid";
538
+ // Each section's real start, so a section cut by `maxPages` keeps its lines; and last time's
539
+ // lines, so unchanged ones stay the same objects. Only the first loaded section can be cut.
540
+ const sectionStarts = useRef(new Map<string, number>());
541
+ const lastLines = useRef(new Map<string, GridLine<T>>());
542
+ const { rowOffset, hasPrevious } = state;
543
+ // Both refs are read here and written in the layout effect below, after commit, so a render
544
+ // React throws away never moves them.
545
+ const gridState = useMemo(() => {
546
+ const starts = new Map<string, number>();
547
+ const lines = new Map<string, GridLine<T>>();
548
+ let at = rowOffset;
549
+ if (!grid) return { sections: [], starts, lines };
550
+ const out = state.sections.map((section, i) => {
551
+ const seen = sectionStarts.current.get(section.key);
552
+ const start = i === 0 && hasPrevious && seen !== undefined ? Math.min(seen, at) : at;
553
+ starts.set(section.key, start);
554
+ const data = gridLines(section.key, section.data, at - start, numColumns, lastLines.current);
555
+ for (const line of data) lines.set(line.key, line);
556
+ at += section.data.length;
557
+ return { key: section.key, title: section.title, data };
558
+ });
559
+ return { sections: out, starts, lines };
560
+ }, [grid, state.sections, numColumns, rowOffset, hasPrevious]);
561
+ useLayoutEffect(() => {
562
+ if (!grid) return;
563
+ sectionStarts.current = gridState.starts;
564
+ lastLines.current = gridState.lines;
565
+ }, [grid, gridState]);
566
+ const gridSections = gridState.sections;
567
+ const gridKey = useCallback((line: GridLine<T>) => line.key, []);
568
+ const renderGridLine = useCallback(
569
+ ({ item: line }: { item: GridLine<T> }) => <GridRow<T> {...shared} line={line} numColumns={numColumns} renderCard={renderCard} />,
570
+ [shared, numColumns, renderCard],
326
571
  );
327
572
 
328
573
  // Rows are counted only as far as they're loaded, so the header shows the title alone.
@@ -454,9 +699,10 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
454
699
  <SafeAreaView testID={testID} edges={["left", "right", "bottom"]} style={{ flex: 1, backgroundColor: colors.groupedBackground }}>
455
700
  <SectionList<T, NativeResourceSection<T>>
456
701
  testID={`${testID}-list`}
457
- sections={state.sections}
458
- keyExtractor={keyExtractor}
459
- renderItem={renderItem}
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}
460
706
  renderSectionHeader={renderSectionHeader}
461
707
  // Rows read their item and actions besides `sections`; they change only with the view,
462
708
  // the bin capability or the words, never per keystroke.
@@ -289,6 +289,17 @@ describe("NativeRecordView", () => {
289
289
  fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
290
290
  expect((await screen.findByTestId("native-resource-workspace-settings-refusal")).textContent).toContain("This brand was not changed.");
291
291
  });
292
+
293
+ it("sends only the fields edited, so a refreshed row's other values aren't overwritten", async () => {
294
+ const p = provider();
295
+ const editable = { ...brand, is_default: false };
296
+ const { rerender } = render(<NativeRecordView view={page} row={editable} section="settings" />, { wrapper: wrap(p) });
297
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-website-input"), { target: { value: "https://mine.example" } });
298
+ // Someone else turns public on meanwhile; the refreshed row carries it.
299
+ rerender(<NativeRecordView view={page} row={{ ...editable, public: true }} section="settings" />);
300
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
301
+ await waitFor(() => expect(p.update).toHaveBeenCalledWith("brands", { id: "b1", data: { website: "https://mine.example" } }));
302
+ });
292
303
  });
293
304
 
294
305
  describe("NativeRecordView review fixes", () => {