@marktiderman/genesis-ui-native 3.3.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.
- package/README.md +24 -0
- package/dist/{chunk-VZ3PQLZ4.js → chunk-ABVSSJNT.js} +3 -3
- package/dist/{chunk-VZ3PQLZ4.js.map → chunk-ABVSSJNT.js.map} +1 -1
- package/dist/{chunk-ZHVQTMNV.js → chunk-ONH2PCGH.js} +7 -4
- package/dist/chunk-ONH2PCGH.js.map +1 -0
- package/dist/data/index.d.ts +104 -7
- package/dist/data/index.js +407 -79
- package/dist/data/index.js.map +1 -1
- package/dist/{inbox-page-DZUR-PJ1.d.ts → inbox-page-BEarNEIP.d.ts} +11 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/layouts/index.d.ts +2 -2
- package/dist/layouts/index.js +2 -2
- package/package.json +3 -3
- package/src/data/NativeResourceFormField.tsx +12 -3
- package/src/data/resource-view/NativeLinkPicker.tsx +191 -0
- package/src/data/resource-view/NativeRecordView.tsx +15 -5
- package/src/data/resource-view/NativeResourceFormSheet.tsx +25 -1
- package/src/data/resource-view/NativeResourceView.tsx +296 -50
- package/src/data/resource-view/__tests__/native-link-picker.test.tsx +201 -0
- package/src/data/resource-view/__tests__/native-record-view.test.tsx +11 -0
- package/src/data/resource-view/__tests__/native-resource-view-delete.test.tsx +171 -0
- package/src/data/resource-view/__tests__/native-resource-view.test.tsx +226 -2
- package/src/data/resource-view/__tests__/native-tel-field.test.tsx +79 -0
- package/src/data/resource-view/index.ts +8 -1
- package/src/data/resource-view/mapping.ts +60 -7
- package/src/data/resource-view/messages.ts +25 -0
- package/src/data/resource-view/use-native-resource-view.ts +62 -13
- package/src/layouts/__tests__/screen-container.test.tsx +51 -2
- package/src/layouts/screen-container.tsx +20 -1
- package/dist/chunk-ZHVQTMNV.js.map +0 -1
|
@@ -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 {
|
|
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 (`
|
|
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:
|
|
193
|
-
const
|
|
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 =
|
|
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
|
|
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
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
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
|
-
|
|
458
|
-
|
|
459
|
-
|
|
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.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// @feat:resource-view-links
|
|
2
|
+
/**
|
|
3
|
+
* A link's picker in NativeResourceView's form sheet: the linked rows through the provider, under
|
|
4
|
+
* the linked view's scope and default filter; the picked key saved; None clears to null; a link
|
|
5
|
+
* the screen's filter pins stays read-only.
|
|
6
|
+
*/
|
|
7
|
+
import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
|
|
8
|
+
import { QueryClient } from "@tanstack/react-query";
|
|
9
|
+
import type { ReactNode } from "react";
|
|
10
|
+
import { describe, expect, it, vi } from "vitest";
|
|
11
|
+
import { defineResource, GenesisProvider, ViewerScope, type DataProvider, type FilterParam, type ListParams } from "@marktiderman/genesis-core";
|
|
12
|
+
import { defineView } from "@marktiderman/genesis-core/resource-view";
|
|
13
|
+
import { formFieldsFor, NativeResourceView, useNativeResourceView, writableValues } from "..";
|
|
14
|
+
|
|
15
|
+
type Task = { id: string; org_id: string; title: string; owner_id: string; reviewer_id: string | null };
|
|
16
|
+
type Person = { id: string; org_id: string; full_name: string; active: boolean };
|
|
17
|
+
|
|
18
|
+
const tasks = defineResource<Task>()({
|
|
19
|
+
name: "tasks",
|
|
20
|
+
key: "id",
|
|
21
|
+
labelField: "title",
|
|
22
|
+
fields: [
|
|
23
|
+
{ name: "id", type: "string", hasDefault: true },
|
|
24
|
+
{ name: "org_id", type: "string" },
|
|
25
|
+
{ name: "title", type: "string" },
|
|
26
|
+
{ name: "owner_id", type: "string", references: { resource: "people", field: "id" } },
|
|
27
|
+
{ name: "reviewer_id", type: "string", nullable: true, references: { resource: "people", field: "id" } },
|
|
28
|
+
],
|
|
29
|
+
});
|
|
30
|
+
const people = defineResource<Person>()({
|
|
31
|
+
name: "people",
|
|
32
|
+
key: "id",
|
|
33
|
+
labelField: "full_name",
|
|
34
|
+
fields: [
|
|
35
|
+
{ name: "id", type: "string" },
|
|
36
|
+
{ name: "org_id", type: "string" },
|
|
37
|
+
{ name: "full_name", type: "string" },
|
|
38
|
+
{ name: "active", type: "boolean" },
|
|
39
|
+
],
|
|
40
|
+
});
|
|
41
|
+
const peopleView = defineView(people, { scope: ["org_id"], presets: { default: { filter: { active: true } } } });
|
|
42
|
+
const tasksView = defineView(tasks, {
|
|
43
|
+
scope: ["org_id"],
|
|
44
|
+
form: ["title", "owner_id", "reviewer_id"],
|
|
45
|
+
fields: { owner_id: { label: "Owner", link: { view: peopleView } }, reviewer_id: { label: "Reviewer", link: { view: peopleView } } },
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const PEOPLE: Person[] = [
|
|
49
|
+
{ id: "ada", org_id: "o1", full_name: "Ada Lovelace", active: true },
|
|
50
|
+
{ id: "grace", org_id: "o1", full_name: "Grace Hopper", active: true },
|
|
51
|
+
{ id: "gone", org_id: "o1", full_name: "Former Person", active: false },
|
|
52
|
+
{ id: "other", org_id: "o2", full_name: "Elsewhere Person", active: true },
|
|
53
|
+
];
|
|
54
|
+
const TASK: Task = { id: "t1", org_id: "o1", title: "Write", owner_id: "ada", reviewer_id: "grace" };
|
|
55
|
+
|
|
56
|
+
const matches = (row: Record<string, unknown>, f: FilterParam) =>
|
|
57
|
+
f.operator === "eq" ? row[f.field] === f.value : f.operator === "in" ? (f.value as unknown[]).includes(row[f.field]) : true;
|
|
58
|
+
|
|
59
|
+
function setup() {
|
|
60
|
+
const getList = vi.fn(async (resource: string, params: ListParams) => {
|
|
61
|
+
if (resource === "tasks") return { data: [TASK], total: 1 };
|
|
62
|
+
let rows = PEOPLE.filter((p) => (params.filters ?? []).every((f) => matches(p, f)));
|
|
63
|
+
if (params.search?.query) rows = rows.filter((p) => p.full_name.toLowerCase().includes(params.search!.query.toLowerCase()));
|
|
64
|
+
return { data: rows, total: rows.length };
|
|
65
|
+
});
|
|
66
|
+
const provider: DataProvider = {
|
|
67
|
+
getList: getList as unknown as DataProvider["getList"],
|
|
68
|
+
getOne: vi.fn(async () => ({ data: TASK })) as DataProvider["getOne"],
|
|
69
|
+
getMany: vi.fn(async () => ({ data: [] })),
|
|
70
|
+
create: vi.fn(async (_r, { data }) => ({ data: { id: "new", ...(data as object) } })) as DataProvider["create"],
|
|
71
|
+
update: vi.fn(async (_r, { id, data }) => ({ data: { id, ...(data as object) } })) as DataProvider["update"],
|
|
72
|
+
deleteOne: vi.fn(),
|
|
73
|
+
};
|
|
74
|
+
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
75
|
+
const Wrapper = ({ children }: { children: ReactNode }) => (
|
|
76
|
+
<GenesisProvider provider={provider} queryClient={queryClient}>
|
|
77
|
+
<ViewerScope viewer="u1" scope={{ orgId: "o1" }} timeZone="UTC">
|
|
78
|
+
{children}
|
|
79
|
+
</ViewerScope>
|
|
80
|
+
</GenesisProvider>
|
|
81
|
+
);
|
|
82
|
+
const peopleLists = () => getList.mock.calls.filter(([r, p]) => r === "people" && !(p.filters ?? []).some((f) => f.field === "id"));
|
|
83
|
+
return { Wrapper, provider, peopleLists };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const field = (key: string) => `native-resource-view-form-field-${key}`;
|
|
87
|
+
|
|
88
|
+
describe("a link's picker in the native form sheet", () => {
|
|
89
|
+
it("is a picker, not a typed id", () => {
|
|
90
|
+
const fields = formFieldsFor(tasksView, "create");
|
|
91
|
+
expect(fields.find((f) => f.key === "owner_id")).toMatchObject({ kind: "link", readOnly: false, required: true });
|
|
92
|
+
expect(fields.find((f) => f.key === "reviewer_id")).toMatchObject({ kind: "link", required: false });
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("lists the linked rows through the provider under the linked view's scope and default filter, and saves the picked key", async () => {
|
|
96
|
+
const { Wrapper, provider, peopleLists } = setup();
|
|
97
|
+
render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
|
|
98
|
+
fireEvent.click(await screen.findByTestId("native-resource-view-create"));
|
|
99
|
+
const form = await screen.findByTestId("native-resource-view-form");
|
|
100
|
+
fireEvent.change(within(form).getByTestId(field("title")).querySelector("input")!, { target: { value: "Ship" } });
|
|
101
|
+
expect(peopleLists()).toHaveLength(0);
|
|
102
|
+
fireEvent.click(within(form).getByTestId(`${field("owner_id")}-trigger`));
|
|
103
|
+
await waitFor(() => expect(within(form).getByTestId(`${field("owner_id")}-option-grace`)).toBeTruthy());
|
|
104
|
+
expect(peopleLists()[0]![1].filters).toEqual([
|
|
105
|
+
{ field: "org_id", operator: "eq", value: "o1" },
|
|
106
|
+
{ field: "active", operator: "eq", value: true },
|
|
107
|
+
]);
|
|
108
|
+
expect(within(form).queryByTestId(`${field("owner_id")}-option-gone`)).toBeNull();
|
|
109
|
+
expect(within(form).queryByTestId(`${field("owner_id")}-option-other`)).toBeNull();
|
|
110
|
+
// A required link has no None.
|
|
111
|
+
expect(within(form).queryByTestId(`${field("owner_id")}-none`)).toBeNull();
|
|
112
|
+
fireEvent.click(within(form).getByTestId(`${field("owner_id")}-option-grace`));
|
|
113
|
+
await waitFor(() => expect(within(form).getByTestId(`${field("owner_id")}-trigger`).textContent).toContain("Grace Hopper"));
|
|
114
|
+
fireEvent.click(within(form).getByTestId("native-resource-view-form-save"));
|
|
115
|
+
await waitFor(() => expect(provider.create).toHaveBeenCalled());
|
|
116
|
+
expect((provider.create as ReturnType<typeof vi.fn>).mock.calls[0]![1].data).toMatchObject({ title: "Ship", owner_id: "grace" });
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("clears an optional link to null with None", () => {
|
|
120
|
+
const fields = formFieldsFor(tasksView, "edit");
|
|
121
|
+
expect(writableValues(tasksView, "edit", fields, { ...TASK, reviewer_id: null }, new Set(["reviewer_id"]))).toEqual({ reviewer_id: null });
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("offers None for an optional link, and saves null", async () => {
|
|
125
|
+
const { Wrapper, provider } = setup();
|
|
126
|
+
render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
|
|
127
|
+
const row = await screen.findByTestId("native-resource-view-row-t1");
|
|
128
|
+
act(() => {
|
|
129
|
+
row.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "edit" }));
|
|
130
|
+
});
|
|
131
|
+
const form = await screen.findByTestId("native-resource-view-form");
|
|
132
|
+
const trigger = await within(form).findByTestId(`${field("reviewer_id")}-trigger`);
|
|
133
|
+
await waitFor(() => expect(trigger.textContent).toContain("Grace Hopper"));
|
|
134
|
+
fireEvent.click(trigger);
|
|
135
|
+
fireEvent.click(await within(form).findByTestId(`${field("reviewer_id")}-none`));
|
|
136
|
+
fireEvent.click(within(form).getByTestId("native-resource-view-form-save"));
|
|
137
|
+
await waitFor(() => expect(provider.update).toHaveBeenCalled());
|
|
138
|
+
expect((provider.update as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toEqual({ id: "t1", data: { reviewer_id: null } });
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("keeps a link the screen's filter pins read-only on edit, and never sends it", async () => {
|
|
142
|
+
const { Wrapper, provider } = setup();
|
|
143
|
+
const { result } = renderHook(() => useNativeResourceView(tasksView, { filter: { owner_id: "ada" } }), { wrapper: Wrapper });
|
|
144
|
+
await waitFor(() => expect(result.current.rows).toHaveLength(1));
|
|
145
|
+
expect(result.current.formFields("create").map((f) => f.key)).toEqual(["title", "reviewer_id"]);
|
|
146
|
+
expect(result.current.formFields("edit").find((f) => f.key === "owner_id")).toMatchObject({ readOnly: true });
|
|
147
|
+
await act(async () => {
|
|
148
|
+
await result.current.save("edit", { ...TASK, owner_id: "grace", title: "Changed" }, TASK, new Set(["owner_id", "title"]));
|
|
149
|
+
});
|
|
150
|
+
expect((provider.update as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toEqual({ id: "t1", data: { title: "Changed" } });
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("draws each choice as a radio, checked when it's the link's row", async () => {
|
|
154
|
+
const { Wrapper } = setup();
|
|
155
|
+
render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
|
|
156
|
+
const row = await screen.findByTestId("native-resource-view-row-t1");
|
|
157
|
+
act(() => {
|
|
158
|
+
row.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "edit" }));
|
|
159
|
+
});
|
|
160
|
+
const form = await screen.findByTestId("native-resource-view-form");
|
|
161
|
+
fireEvent.click(await within(form).findByTestId(`${field("owner_id")}-trigger`));
|
|
162
|
+
const ada = await within(form).findByTestId(`${field("owner_id")}-option-ada`);
|
|
163
|
+
const grace = within(form).getByTestId(`${field("owner_id")}-option-grace`);
|
|
164
|
+
expect(ada.getAttribute("role")).toBe("radio");
|
|
165
|
+
expect(ada.getAttribute("aria-checked")).toBe("true");
|
|
166
|
+
expect(grace.getAttribute("aria-checked")).toBe("false");
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("announces an error: in the trigger's label and as an alert", async () => {
|
|
170
|
+
const { Wrapper } = setup();
|
|
171
|
+
render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
|
|
172
|
+
fireEvent.click(await screen.findByTestId("native-resource-view-create"));
|
|
173
|
+
const form = await screen.findByTestId("native-resource-view-form");
|
|
174
|
+
fireEvent.change(within(form).getByTestId(field("title")).querySelector("input")!, { target: { value: "Ship" } });
|
|
175
|
+
fireEvent.click(within(form).getByTestId("native-resource-view-form-save"));
|
|
176
|
+
const error = await within(form).findByTestId(`${field("owner_id")}-error`);
|
|
177
|
+
expect(error.getAttribute("role")).toBe("alert");
|
|
178
|
+
expect(within(form).getByTestId(`${field("owner_id")}-trigger`).getAttribute("aria-label")).toContain(error.textContent!);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("offers only the rows of a list (in) filter on the link", () => {
|
|
182
|
+
const fields = formFieldsFor(tasksView, "edit", { within: { owner_id: ["ada", "gone"] } });
|
|
183
|
+
const owner = fields.find((f) => f.key === "owner_id")!;
|
|
184
|
+
expect(owner.link!.filters({ orgId: "o1" })).toEqual([
|
|
185
|
+
{ field: "org_id", operator: "eq", value: "o1" },
|
|
186
|
+
{ field: "active", operator: "eq", value: true },
|
|
187
|
+
{ field: "id", operator: "in", value: ["ada", "gone"] },
|
|
188
|
+
]);
|
|
189
|
+
expect(owner.link!.labelField).toBe("full_name");
|
|
190
|
+
// Other links are as they were.
|
|
191
|
+
expect(fields.find((f) => f.key === "reviewer_id")!.link!.filters({ orgId: "o1" })).toHaveLength(2);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("holds the picker to a screen's list filter", async () => {
|
|
195
|
+
const { Wrapper } = setup();
|
|
196
|
+
const { result } = renderHook(() => useNativeResourceView(tasksView, { filter: { owner_id: ["ada", "grace"] } }), { wrapper: Wrapper });
|
|
197
|
+
await waitFor(() => expect(result.current.rows).toHaveLength(1));
|
|
198
|
+
const owner = result.current.formFields("create").find((f) => f.key === "owner_id")!;
|
|
199
|
+
expect(owner.link!.filters({ orgId: "o1" }).at(-1)).toEqual({ field: "id", operator: "in", value: ["ada", "grace"] });
|
|
200
|
+
});
|
|
201
|
+
});
|
|
@@ -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", () => {
|