@marktiderman/genesis-ui-native 3.10.0 → 3.12.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 (82) hide show
  1. package/README.md +69 -0
  2. package/dist/{chunk-ZUR4PK77.js → chunk-47CDRP43.js} +45 -166
  3. package/dist/chunk-47CDRP43.js.map +1 -0
  4. package/dist/{chunk-SG7LYX7Z.js → chunk-BQYT6TH2.js} +14 -6
  5. package/dist/chunk-BQYT6TH2.js.map +1 -0
  6. package/dist/{chunk-EAHK7D7N.js → chunk-C2ARUGT7.js} +146 -42
  7. package/dist/chunk-C2ARUGT7.js.map +1 -0
  8. package/dist/{chunk-VEWSY4TZ.js → chunk-D4UU6KIF.js} +236 -21
  9. package/dist/chunk-D4UU6KIF.js.map +1 -0
  10. package/dist/{chunk-GGH3ZQNO.js → chunk-TUDJDIGC.js} +4 -4
  11. package/dist/{chunk-GGH3ZQNO.js.map → chunk-TUDJDIGC.js.map} +1 -1
  12. package/dist/{chunk-PMS2V46D.js → chunk-VHUUOH46.js} +2 -2
  13. package/dist/{chunk-PMS2V46D.js.map → chunk-VHUUOH46.js.map} +1 -1
  14. package/dist/{chunk-IWWXERKQ.js → chunk-X5CPLUPZ.js} +1236 -136
  15. package/dist/chunk-X5CPLUPZ.js.map +1 -0
  16. package/dist/components/index.d.ts +510 -25
  17. package/dist/components/index.js +5 -5
  18. package/dist/data/index.d.ts +176 -34
  19. package/dist/data/index.js +1312 -985
  20. package/dist/data/index.js.map +1 -1
  21. package/dist/hooks/index.d.ts +2 -2
  22. package/dist/hooks/index.js +1 -1
  23. package/dist/icons/lucide.d.ts +1 -1
  24. package/dist/index.d.ts +6 -3
  25. package/dist/index.js +7 -7
  26. package/dist/layouts/index.d.ts +79 -6
  27. package/dist/layouts/index.js +5 -5
  28. package/dist/{native-modules-Bkm1jHO-.d.ts → native-modules-6JnyeGR-.d.ts} +55 -1
  29. package/package.json +70 -4
  30. package/src/components/__tests__/combobox.test.tsx +20 -0
  31. package/src/components/__tests__/number-input.test.tsx +112 -1
  32. package/src/components/__tests__/parity-controls.test.tsx +366 -0
  33. package/src/components/__tests__/parity-display.test.tsx +295 -0
  34. package/src/components/__tests__/twin-props.test.tsx +114 -0
  35. package/src/components/badge.tsx +3 -0
  36. package/src/components/button-group.tsx +50 -0
  37. package/src/components/calendar.tsx +183 -0
  38. package/src/components/carousel.tsx +175 -0
  39. package/src/components/chart.tsx +268 -0
  40. package/src/components/chip-group.tsx +34 -14
  41. package/src/components/choice-card.tsx +56 -19
  42. package/src/components/combobox.tsx +6 -5
  43. package/src/components/empty-state.tsx +40 -0
  44. package/src/components/flatten-children.ts +13 -0
  45. package/src/components/index.ts +49 -1
  46. package/src/components/inline-alert.tsx +3 -1
  47. package/src/components/input-group.tsx +99 -0
  48. package/src/components/input-otp.tsx +124 -0
  49. package/src/components/input.tsx +40 -12
  50. package/src/components/list-item.tsx +20 -4
  51. package/src/components/number-input.tsx +45 -15
  52. package/src/components/radio-group.tsx +5 -0
  53. package/src/components/resource.tsx +227 -0
  54. package/src/components/settings-row.tsx +194 -0
  55. package/src/components/slider.tsx +3 -9
  56. package/src/components/sortable-list.tsx +287 -0
  57. package/src/components/stat-card.tsx +106 -0
  58. package/src/components/stepper.tsx +4 -2
  59. package/src/components/widget-tile.tsx +66 -0
  60. package/src/components/workspace-switcher.tsx +217 -0
  61. package/src/data/NativeCustomView.tsx +117 -0
  62. package/src/data/NativeFormFields.tsx +312 -0
  63. package/src/data/NativeRecordPeek.tsx +130 -0
  64. package/src/data/NativeResourceFormField.tsx +32 -0
  65. package/src/data/__tests__/parity-data.test.tsx +350 -0
  66. package/src/data/index.ts +13 -0
  67. package/src/data/resource-view/NativeResourceView.tsx +17 -2
  68. package/src/data/resource-view/__tests__/native-resource-gallery.test.tsx +8 -0
  69. package/src/data/resource-view/index.ts +1 -0
  70. package/src/data/resource-view/mapping.ts +4 -4
  71. package/src/layouts/__tests__/keyboard-scroll.test.tsx +58 -2
  72. package/src/layouts/__tests__/notifications-page.test.tsx +12 -0
  73. package/src/layouts/index.ts +13 -0
  74. package/src/layouts/keyboard.tsx +22 -2
  75. package/src/layouts/notifications-page.tsx +13 -35
  76. package/src/layouts/pages.tsx +262 -0
  77. package/src/native-modules.tsx +37 -0
  78. package/dist/chunk-EAHK7D7N.js.map +0 -1
  79. package/dist/chunk-IWWXERKQ.js.map +0 -1
  80. package/dist/chunk-SG7LYX7Z.js.map +0 -1
  81. package/dist/chunk-VEWSY4TZ.js.map +0 -1
  82. package/dist/chunk-ZUR4PK77.js.map +0 -1
@@ -0,0 +1,130 @@
1
+ // NativeRecordPeek: a record's page in a sheet, the twin of genesis-ui's RecordPeek. It draws the
2
+ // view's record view (NativeRecordView) in a NativeSheet, with the record's title as the sheet's
3
+ // heading and, when the screen passes them, Edit and Delete beside it. A full page is the app's
4
+ // own route (getNativeRecordViewStackOptions); a peek is for a look without leaving the list.
5
+ // The record view scrolls itself, so the sheet holds it as it is.
6
+ //
7
+ // Edit and Delete go through the same rights as the list's swipe actions (`allowed`: the screen's
8
+ // `can` AND the view's update / delete guard): one the screen turns off is hidden, one a guard
9
+ // refuses stays and explains why. Delete is confirmed here, once, in the list's words (the bin's
10
+ // when the provider moves deleted rows to a recycle bin), so `onDelete` is the write itself.
11
+
12
+ import { useState, type ReactNode } from "react";
13
+ import { Alert, Text, View } from "react-native";
14
+ import type { DataRow } from "@marktiderman/genesis-core";
15
+ import { useCapabilities, useViewer } from "@marktiderman/genesis-core/hooks";
16
+ import { NativeButton } from "../components/button";
17
+ import { NativeSheet } from "../components/sheet";
18
+ import { useNativeResourceViewMessages } from "./resource-view/display";
19
+ import { allowed, refusalMessage, type NativeResourceScreenCan } from "./resource-view/mapping";
20
+ import { fill } from "./resource-view/messages";
21
+ import { NativeRecordView, type NativeRecordViewProps } from "./resource-view/NativeRecordView";
22
+
23
+ type Row = Record<string, unknown>;
24
+
25
+ export interface NativeRecordPeekProps<T extends Row = Row> extends Omit<NativeRecordViewProps<T>, "row"> {
26
+ /** The record, or null while none is open. */
27
+ row: T | null;
28
+ open: boolean;
29
+ onClose: () => void;
30
+ /** Shows Edit (where the screen's `can` and the view's update guard allow it): open the record's form. */
31
+ onEdit?: (row: T) => void;
32
+ /**
33
+ * Shows Delete (where `can` and the view's delete guard allow it). The peek confirms first, so
34
+ * pass the write itself (the provider's delete), never a handler that confirms again. Return its
35
+ * promise: the sheet closes when it resolves, and a rejection is shown in plain words.
36
+ */
37
+ onDelete?: (row: T) => unknown;
38
+ /** The screen's own rule, as NativeResourceView's `can`: `false` hides Edit or Delete, a sentence refuses it. Only narrows the view's guards. */
39
+ can?: NativeResourceScreenCan<T>;
40
+ /** Above the record (a link to its full page). */
41
+ header?: ReactNode;
42
+ /** The sheet's heights. Default `["60%", "92%"]`. */
43
+ snapPoints?: (string | number)[];
44
+ /** Overrides for the resource-view messages (`common.edit`, `delete` / `bin`, `common.cancel`). */
45
+ labels?: { edit?: string; delete?: string; deleteTitle?: string; deleteBody?: string; cancel?: string };
46
+ }
47
+
48
+ export function NativeRecordPeek<T extends Row = Row>({
49
+ row,
50
+ open,
51
+ onClose,
52
+ onEdit,
53
+ onDelete,
54
+ can,
55
+ header,
56
+ snapPoints = ["60%", "92%"],
57
+ labels = {},
58
+ testID = "record-peek",
59
+ ...rest
60
+ }: NativeRecordPeekProps<T>) {
61
+ const messages = useNativeResourceViewMessages();
62
+ const view = rest.view.view;
63
+ const viewer = useViewer();
64
+ const softDelete = useCapabilities(view.resource).data?.softDelete === true;
65
+ const [deleting, setDeleting] = useState(false);
66
+ const shown = open && row !== null;
67
+ const title = row ? view.summary(row as T & DataRow).title : "";
68
+ const canEdit = row && onEdit ? allowed(view, "update", row, can, viewer) : false;
69
+ const canDelete = row && onDelete ? allowed(view, "delete", row, can, viewer) : false;
70
+ const words = softDelete ? messages.bin : messages.delete;
71
+ const deleteLabel = labels.delete ?? words.action;
72
+ const editLabel = labels.edit ?? messages.common.edit;
73
+
74
+ const runDelete = async (r: T) => {
75
+ setDeleting(true);
76
+ try {
77
+ await onDelete?.(r);
78
+ onClose();
79
+ } catch (error) {
80
+ Alert.alert(deleteLabel, refusalMessage(error, fill(messages.refusal.deleteFailed, { noun: view.noun })));
81
+ } finally {
82
+ setDeleting(false);
83
+ }
84
+ };
85
+ const confirmDelete = (r: T) =>
86
+ Alert.alert(labels.deleteTitle ?? fill(words.confirmTitle, { name: title }), labels.deleteBody ?? words.confirmBody, [
87
+ { text: labels.cancel ?? messages.common.cancel, style: "cancel" },
88
+ { text: deleteLabel, style: "destructive", onPress: () => void runDelete(r) },
89
+ ]);
90
+
91
+ return (
92
+ <NativeSheet open={shown} onOpenChange={(next) => (next ? undefined : onClose())} snapPoints={snapPoints} testID={testID}>
93
+ {row ? (
94
+ <View style={{ flex: 1, paddingBottom: 16 }}>
95
+ <View className="flex-row items-center justify-between gap-2 px-4 pb-2">
96
+ <Text accessibilityRole="header" numberOfLines={2} className="flex-1 text-lg font-semibold text-foreground">
97
+ {title}
98
+ </Text>
99
+ {canEdit !== false ? (
100
+ <NativeButton
101
+ size="sm"
102
+ variant="outline"
103
+ testID={`${testID}-edit`}
104
+ accessibilityHint={canEdit === true ? undefined : canEdit}
105
+ onPress={() => (canEdit === true ? onEdit!(row) : Alert.alert(editLabel, canEdit))}
106
+ >
107
+ {editLabel}
108
+ </NativeButton>
109
+ ) : null}
110
+ {canDelete !== false ? (
111
+ <NativeButton
112
+ size="sm"
113
+ variant="ghost"
114
+ textClassName="text-destructive"
115
+ testID={`${testID}-delete`}
116
+ disabled={deleting}
117
+ accessibilityHint={canDelete === true ? undefined : canDelete}
118
+ onPress={() => (canDelete === true ? confirmDelete(row) : Alert.alert(deleteLabel, canDelete))}
119
+ >
120
+ {deleteLabel}
121
+ </NativeButton>
122
+ ) : null}
123
+ </View>
124
+ {header}
125
+ <NativeRecordView<T> {...rest} row={row} testID={`${testID}-page`} />
126
+ </View>
127
+ ) : null}
128
+ </NativeSheet>
129
+ );
130
+ }
@@ -14,6 +14,7 @@ import {
14
14
  import { NativeSwitch } from "../components/switch";
15
15
  import { NativeText } from "../components/text";
16
16
  import { NativeTextarea } from "../components/textarea";
17
+ import { NativeFieldArrayRenderer, NativeFileUploadField, NativeRelationField, type NativeFileUploadFieldProps } from "./NativeFormFields";
17
18
 
18
19
  // ---------------------------------------------------------------------------
19
20
  // Types
@@ -70,6 +71,11 @@ function NativeResourceFormFieldRenderer({
70
71
  return null;
71
72
  }
72
73
 
74
+ // Repeating groups, as the web's form (FieldArrayRenderer).
75
+ if (fieldType === "array" && field.arrayFields) {
76
+ return <NativeFieldArrayRenderer field={field} control={control} action={action} watchedValues={watchedValues} />;
77
+ }
78
+
73
79
  return (
74
80
  <Controller
75
81
  name={field.key}
@@ -77,6 +83,32 @@ function NativeResourceFormFieldRenderer({
77
83
  render={({ field: f, fieldState }) => {
78
84
  const errorMessage = fieldState.error?.message;
79
85
 
86
+ // ------------------------------------------------------------------
87
+ // Relation, file and image: the same pieces as the web's form.
88
+ // ------------------------------------------------------------------
89
+ if (fieldType === "relation" && field.relation) {
90
+ return (
91
+ <NativeRelationField
92
+ field={field}
93
+ value={f.value}
94
+ onChange={f.onChange}
95
+ values={watchedValues ?? {}}
96
+ {...(errorMessage ? { error: errorMessage } : {})}
97
+ />
98
+ );
99
+ }
100
+ if (fieldType === "file" || fieldType === "image") {
101
+ return (
102
+ <NativeFileUploadField
103
+ field={field}
104
+ value={(f.value as NativeFileUploadFieldProps["value"]) ?? null}
105
+ onChange={f.onChange}
106
+ disabled={isDisabled}
107
+ {...(errorMessage ? { error: errorMessage } : {})}
108
+ />
109
+ );
110
+ }
111
+
80
112
  // ------------------------------------------------------------------
81
113
  // Switch
82
114
  // ------------------------------------------------------------------
@@ -0,0 +1,350 @@
1
+ // @feat:native-components
2
+ /**
3
+ * The data-layer twins: repeating groups, file and link fields and a wizard on the phone's form,
4
+ * a custom view's states, and a record in a peek.
5
+ */
6
+ import { act, fireEvent, render, screen } from "@testing-library/react";
7
+ import { QueryClient } from "@tanstack/react-query";
8
+ import { useState, type ReactNode } from "react";
9
+ import { Alert, Text } from "react-native";
10
+ import { useForm } from "react-hook-form";
11
+ import { describe, expect, it, vi } from "vitest";
12
+ import { defineResource, GenesisProvider, ViewerScope, type DataProvider, type ResourceFormFieldDef } from "@marktiderman/genesis-core";
13
+ import { defineRecordView, defineView } from "@marktiderman/genesis-core/resource-view";
14
+ import { GenesisModulesProvider, type NativePickedFile } from "../../native-modules";
15
+ import { NativeCustomView } from "../NativeCustomView";
16
+ import { NativeFieldArrayRenderer, NativeFileUploadField, NativeRelationField, NativeWizardForm } from "../NativeFormFields";
17
+ import { NativeRecordPeek } from "../NativeRecordPeek";
18
+ import { NativeResourceFormFieldRenderer } from "../NativeResourceFormField";
19
+
20
+ type Person = { id: string; full_name: string };
21
+ const people = defineResource<Person>()({
22
+ name: "people",
23
+ key: "id",
24
+ labelField: "full_name",
25
+ fields: [
26
+ { name: "id", type: "string" },
27
+ { name: "full_name", type: "string" },
28
+ ],
29
+ });
30
+ const peopleView = defineView(people);
31
+ const PEOPLE: Person[] = [
32
+ { id: "ada", full_name: "Ada Lovelace" },
33
+ { id: "grace", full_name: "Grace Hopper" },
34
+ ];
35
+
36
+ function wrap(rows: Person[] = PEOPLE, over: Partial<DataProvider> = {}) {
37
+ const provider: DataProvider = {
38
+ getList: vi.fn(async () => ({ data: rows, total: rows.length })) as DataProvider["getList"],
39
+ getOne: vi.fn(async (_r, { id }) => ({ data: rows.find((p) => p.id === id) ?? rows[0] })) as DataProvider["getOne"],
40
+ getMany: vi.fn(async () => ({ data: rows })) as DataProvider["getMany"],
41
+ create: vi.fn(),
42
+ update: vi.fn(),
43
+ deleteOne: vi.fn(),
44
+ ...over,
45
+ };
46
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
47
+ return ({ children }: { children: ReactNode }) => (
48
+ <GenesisProvider provider={provider} queryClient={queryClient}>
49
+ <ViewerScope viewer="u1" timeZone="UTC">
50
+ {children}
51
+ </ViewerScope>
52
+ </GenesisProvider>
53
+ );
54
+ }
55
+
56
+ describe("NativeFieldArrayRenderer", () => {
57
+ const field: ResourceFormFieldDef = { key: "contacts", label: "Contacts", type: "array", arrayMax: 2, arrayFields: [{ key: "name", label: "Name" }] };
58
+ function Form() {
59
+ const form = useForm<Record<string, unknown>>({ defaultValues: { contacts: [] } });
60
+ return <NativeFieldArrayRenderer field={field} control={form.control} action="create" />;
61
+ }
62
+ it("adds items up to arrayMax and removes them", () => {
63
+ render(<Form />);
64
+ const add = screen.getByTestId("field-array-contacts-add");
65
+ expect(add.textContent).toBe("Add Contact");
66
+ fireEvent.click(add);
67
+ fireEvent.click(add);
68
+ expect(screen.getByTestId("field-array-contacts-1")).toBeTruthy();
69
+ expect(screen.getByTestId("field-array-contacts-add").getAttribute("aria-disabled")).toBe("true");
70
+ fireEvent.click(screen.getByTestId("field-array-contacts-0-remove"));
71
+ expect(screen.queryByTestId("field-array-contacts-1")).toBeNull();
72
+ });
73
+ it("takes the Remove button's visible word from labels", () => {
74
+ function Translated() {
75
+ const form = useForm<Record<string, unknown>>({ defaultValues: { contacts: [{ name: "" }] } });
76
+ return <NativeFieldArrayRenderer field={field} control={form.control} action="create" labels={{ removeButton: "Entfernen", remove: "Eintrag {n} entfernen" }} />;
77
+ }
78
+ render(<Translated />);
79
+ const remove = screen.getByTestId("field-array-contacts-0-remove");
80
+ expect(remove.textContent).toBe("Entfernen");
81
+ expect(remove.getAttribute("aria-label")).toBe("Eintrag 1 entfernen");
82
+ });
83
+ });
84
+
85
+ describe("NativeFileUploadField", () => {
86
+ const field: ResourceFormFieldDef = { key: "photo", label: "Photo", type: "image", multiple: true, maxSize: 1000 };
87
+ function Field() {
88
+ const [value, setValue] = useState<NativePickedFile | NativePickedFile[] | null>(null);
89
+ return <NativeFileUploadField field={field} value={value} onChange={setValue} />;
90
+ }
91
+ it("picks through GenesisModules.filePicker, keeps good files and says why others were refused", async () => {
92
+ const filePicker = vi.fn(async () => [
93
+ { uri: "file://a.jpg", name: "a.jpg", type: "image/jpeg", size: 512 },
94
+ { uri: "file://b.pdf", name: "b.pdf", type: "application/pdf", size: 10 },
95
+ { uri: "file://c.jpg", name: "c.jpg", type: "image/jpeg", size: 5000 },
96
+ ]);
97
+ render(
98
+ <GenesisModulesProvider modules={{ filePicker }}>
99
+ <Field />
100
+ </GenesisModulesProvider>,
101
+ );
102
+ await act(async () => {
103
+ fireEvent.click(screen.getByTestId("file-upload-photo-choose"));
104
+ });
105
+ expect(filePicker).toHaveBeenCalledWith({ multiple: true, accept: "image/*" });
106
+ expect(screen.getByTestId("file-upload-photo-file-0").textContent).toContain("512 B");
107
+ expect(screen.queryByTestId("file-upload-photo-file-1")).toBeNull();
108
+ expect(screen.getByText('"b.pdf" is not an accepted file type')).toBeTruthy();
109
+ expect(screen.getByText('"c.jpg" exceeds 1000 B limit')).toBeTruthy();
110
+ fireEvent.click(screen.getByTestId("file-upload-photo-remove-0"));
111
+ expect(screen.queryByTestId("file-upload-photo-file-0")).toBeNull();
112
+ })
113
+ it("says so when the picker rejects (a permission denied), and opens one picker at a time", async () => {
114
+ let reject!: (e: Error) => void;
115
+ const filePicker = vi.fn(
116
+ () =>
117
+ new Promise<NativePickedFile[]>((_, no) => {
118
+ reject = no;
119
+ }),
120
+ );
121
+ render(
122
+ <GenesisModulesProvider modules={{ filePicker }}>
123
+ <Field />
124
+ </GenesisModulesProvider>,
125
+ );
126
+ const choose = screen.getByTestId("file-upload-photo-choose");
127
+ fireEvent.click(choose);
128
+ fireEvent.click(choose);
129
+ expect(filePicker).toHaveBeenCalledTimes(1);
130
+ await act(async () => {
131
+ reject(Object.assign(new Error("User denied access"), { code: "E_NO_PERMISSIONS" }));
132
+ });
133
+ expect(screen.getByRole("alert").textContent).toBe("Couldn't open the picker. Check that the app may use your photos and files, then try again.");
134
+ // The button is back for another try.
135
+ filePicker.mockImplementationOnce(async () => []);
136
+ await act(async () => {
137
+ fireEvent.click(screen.getByTestId("file-upload-photo-choose"));
138
+ });
139
+ expect(filePicker).toHaveBeenCalledTimes(2);
140
+ });
141
+ });
142
+
143
+ describe("NativeRelationField", () => {
144
+ it("lists the linked rows through the provider and stores the picked key as text", async () => {
145
+ const onChange = vi.fn();
146
+ const field: ResourceFormFieldDef = { key: "owner_id", label: "Owner", type: "relation", required: true, relation: { resource: "people", labelField: "full_name" } };
147
+ render(<NativeRelationField field={field} value="" onChange={onChange} />, { wrapper: wrap() });
148
+ fireEvent.click(screen.getByTestId("relation-owner_id-trigger"));
149
+ fireEvent.click(await screen.findByTestId("relation-owner_id-option-grace"));
150
+ expect(onChange).toHaveBeenCalledWith("grace");
151
+ });
152
+ });
153
+
154
+ describe("NativeResourceFormFieldRenderer", () => {
155
+ const fields: ResourceFormFieldDef[] = [
156
+ { key: "contacts", label: "Contacts", type: "array", arrayFields: [{ key: "name", label: "Name" }] },
157
+ { key: "doc", label: "Document", type: "file" },
158
+ { key: "photo", label: "Photo", type: "image" },
159
+ { key: "owner_id", label: "Owner", type: "relation", relation: { resource: "people", labelField: "full_name" } },
160
+ ];
161
+ let values: Record<string, unknown> = {};
162
+ function Form() {
163
+ const form = useForm<Record<string, unknown>>({ defaultValues: { contacts: [], doc: null, photo: null, owner_id: "" } });
164
+ values = form.watch();
165
+ return (
166
+ <>
167
+ {fields.map((f) => (
168
+ <NativeResourceFormFieldRenderer key={f.key} field={f} control={form.control} action="create" />
169
+ ))}
170
+ </>
171
+ );
172
+ }
173
+
174
+ it("draws array, file, image and relation fields with their pieces, writing to the form", async () => {
175
+ const filePicker = vi.fn(async ({ accept }: { accept?: string }) => [
176
+ accept === "image/*" ? { uri: "file://p.jpg", name: "p.jpg", type: "image/jpeg", size: 9 } : { uri: "file://d.pdf", name: "d.pdf", type: "application/pdf", size: 4 },
177
+ ]);
178
+ const Wrapper = wrap();
179
+ render(
180
+ <Wrapper>
181
+ <GenesisModulesProvider modules={{ filePicker }}>
182
+ <Form />
183
+ </GenesisModulesProvider>
184
+ </Wrapper>,
185
+ );
186
+ // Array: one card per item.
187
+ fireEvent.click(screen.getByTestId("field-array-contacts-add"));
188
+ expect(screen.getByTestId("field-array-contacts-0")).toBeTruthy();
189
+ // File and image: the picker, asked for the field's types.
190
+ await act(async () => {
191
+ fireEvent.click(screen.getByTestId("file-upload-doc-choose"));
192
+ });
193
+ await act(async () => {
194
+ fireEvent.click(screen.getByTestId("file-upload-photo-choose"));
195
+ });
196
+ expect(filePicker).toHaveBeenCalledWith({ multiple: false, accept: undefined });
197
+ expect(filePicker).toHaveBeenCalledWith({ multiple: false, accept: "image/*" });
198
+ expect(screen.getByTestId("file-upload-doc-file-0").textContent).toContain("d.pdf");
199
+ expect(screen.getByTestId("file-upload-photo-file-0").textContent).toContain("p.jpg");
200
+ // Relation: the linked rows through the provider.
201
+ fireEvent.click(screen.getByTestId("relation-owner_id-trigger"));
202
+ fireEvent.click(await screen.findByTestId("relation-owner_id-option-ada"));
203
+ await act(async () => {});
204
+ expect(values).toMatchObject({
205
+ contacts: [{ name: "" }],
206
+ doc: { name: "d.pdf" },
207
+ photo: { name: "p.jpg" },
208
+ owner_id: "ada",
209
+ });
210
+ });
211
+ });
212
+
213
+ describe("NativeWizardForm", () => {
214
+ it("validates a step before moving on, then submits on the last", async () => {
215
+ const onSubmit = vi.fn(async () => {});
216
+ function Wizard() {
217
+ const form = useForm<Record<string, unknown>>({ defaultValues: { a: "x", b: "" } });
218
+ return (
219
+ <NativeWizardForm
220
+ steps={[
221
+ { id: "one", title: "First", fields: ["a"] },
222
+ { id: "two", title: "Second", fields: ["b"] },
223
+ ]}
224
+ form={form}
225
+ fields={[{ key: "a", label: "A" }, { key: "b", label: "B" }]}
226
+ onSubmit={onSubmit}
227
+ isSaving={false}
228
+ action="create"
229
+ />
230
+ );
231
+ }
232
+ render(<Wizard />);
233
+ expect(screen.getByText("Step 1 of 2")).toBeTruthy();
234
+ expect(screen.getByTestId("wizard-form-back").getAttribute("aria-disabled")).toBe("true");
235
+ await act(async () => {
236
+ fireEvent.click(screen.getByTestId("wizard-form-next"));
237
+ });
238
+ expect(await screen.findByText("Second")).toBeTruthy();
239
+ expect(screen.getByTestId("wizard-form-next").textContent).toBe("Create");
240
+ await act(async () => {
241
+ fireEvent.click(screen.getByTestId("wizard-form-next"));
242
+ });
243
+ expect(onSubmit).toHaveBeenCalled();
244
+ });
245
+ });
246
+
247
+ describe("NativeCustomView", () => {
248
+ it("draws loading, then hands the rows to the app", async () => {
249
+ render(
250
+ <NativeCustomView view={peopleView}>
251
+ {({ rows, status }) => <Text testID="mine">{`${status}:${rows.map((r) => r.full_name).join(",")}`}</Text>}
252
+ </NativeCustomView>,
253
+ { wrapper: wrap() },
254
+ );
255
+ expect(screen.getByTestId("custom-view-loading")).toBeTruthy();
256
+ expect((await screen.findByTestId("mine")).textContent).toBe("ready:Ada Lovelace,Grace Hopper");
257
+ });
258
+
259
+ it("draws the view's empty state, and an error with a retry", async () => {
260
+ const { unmount } = render(<NativeCustomView view={peopleView}>{() => <Text>never</Text>}</NativeCustomView>, { wrapper: wrap([]) });
261
+ expect(await screen.findByTestId("custom-view-empty")).toBeTruthy();
262
+ unmount();
263
+ render(<NativeCustomView view={peopleView}>{() => <Text>never</Text>}</NativeCustomView>, {
264
+ wrapper: wrap(PEOPLE, { getList: vi.fn(async () => Promise.reject(new Error("offline"))) as DataProvider["getList"] }),
265
+ });
266
+ expect(await screen.findByTestId("custom-view-retry")).toBeTruthy();
267
+ });
268
+ });
269
+
270
+ describe("NativeRecordPeek", () => {
271
+ const recordView = defineRecordView(peopleView, { sections: [{ id: "about", label: "About" }] });
272
+ it("draws the record in a sheet with its title, and forwards Edit and a confirmed Delete", async () => {
273
+ const onEdit = vi.fn();
274
+ const onDelete = vi.fn();
275
+ const onClose = vi.fn();
276
+ const alert = vi.spyOn(Alert, "alert").mockImplementation(() => {});
277
+ render(<NativeRecordPeek view={recordView} row={PEOPLE[0]!} open onClose={onClose} onEdit={onEdit} onDelete={onDelete} />, { wrapper: wrap() });
278
+ const peek = await screen.findByTestId("record-peek-page");
279
+ expect(peek).toBeTruthy();
280
+ expect(screen.getAllByText("Ada Lovelace").length).toBeGreaterThan(0);
281
+ fireEvent.click(screen.getByTestId("record-peek-edit"));
282
+ expect(onEdit).toHaveBeenCalledWith(PEOPLE[0]);
283
+ fireEvent.click(screen.getByTestId("record-peek-delete"));
284
+ const buttons = alert.mock.calls[0]![2] as { text: string; onPress?: () => void }[];
285
+ await act(async () => {
286
+ buttons.find((b) => b.text === "Delete")!.onPress!();
287
+ });
288
+ expect(onDelete).toHaveBeenCalledWith(PEOPLE[0]);
289
+ expect(onClose).toHaveBeenCalled();
290
+ alert.mockRestore();
291
+ });
292
+
293
+ it("hides what the screen's can turns off and explains what the view's guard refuses", async () => {
294
+ const guarded = defineRecordView(
295
+ defineView(people, { can: { delete: () => "Only owners delete people." } }),
296
+ { sections: [{ id: "about", label: "About" }] },
297
+ );
298
+ const onDelete = vi.fn();
299
+ const alert = vi.spyOn(Alert, "alert").mockImplementation(() => {});
300
+ render(
301
+ <NativeRecordPeek
302
+ view={guarded}
303
+ row={PEOPLE[0]!}
304
+ open
305
+ onClose={() => {}}
306
+ onEdit={() => {}}
307
+ onDelete={onDelete}
308
+ can={(action) => action !== "update"}
309
+ />,
310
+ { wrapper: wrap() },
311
+ );
312
+ await screen.findByTestId("record-peek-page");
313
+ expect(screen.queryByTestId("record-peek-edit")).toBeNull();
314
+ fireEvent.click(screen.getByTestId("record-peek-delete"));
315
+ // The guard's reason, not a confirm: no second step offers to delete.
316
+ expect(alert).toHaveBeenCalledTimes(1);
317
+ expect(alert.mock.calls[0]![1]).toBe("Only owners delete people.");
318
+ expect(alert.mock.calls[0]![2]).toBeUndefined();
319
+ expect(onDelete).not.toHaveBeenCalled();
320
+ alert.mockRestore();
321
+ });
322
+
323
+ it("confirms once in the bin's words, and keeps the sheet open with the refusal when the delete fails", async () => {
324
+ const onClose = vi.fn();
325
+ const refused = Object.assign(new Error("You can't delete Ada."), { name: "DataWriteError" });
326
+ const onDelete = vi.fn(async () => {
327
+ throw refused;
328
+ });
329
+ const alert = vi.spyOn(Alert, "alert").mockImplementation(() => {});
330
+ const capabilities = vi.fn(async () => ({ softDelete: true })) as unknown as DataProvider["capabilities"];
331
+ render(<NativeRecordPeek view={recordView} row={PEOPLE[0]!} open onClose={onClose} onDelete={onDelete} />, {
332
+ wrapper: wrap(PEOPLE, { capabilities }),
333
+ });
334
+ await screen.findByTestId("record-peek-page");
335
+ await act(async () => {});
336
+ expect(screen.getByTestId("record-peek-delete").textContent).toBe("Move to Bin");
337
+ fireEvent.click(screen.getByTestId("record-peek-delete"));
338
+ expect(alert.mock.calls[0]![0]).toBe("Move “Ada Lovelace” to the bin?");
339
+ expect(alert.mock.calls[0]![1]).toBe("You can restore it from the bin.");
340
+ const buttons = alert.mock.calls[0]![2] as { text: string; onPress?: () => void }[];
341
+ await act(async () => {
342
+ buttons.find((b) => b.text === "Move to Bin")!.onPress!();
343
+ });
344
+ expect(onDelete).toHaveBeenCalledTimes(1);
345
+ expect(onClose).not.toHaveBeenCalled();
346
+ expect(alert).toHaveBeenCalledTimes(2);
347
+ expect(alert.mock.calls[1]![1]).toBe("You can't delete Ada.");
348
+ alert.mockRestore();
349
+ });
350
+ });
package/src/data/index.ts CHANGED
@@ -10,3 +10,16 @@ export { NativeResourcePage, type NativeResourcePageProps, type NativeCardFieldD
10
10
  export * from "./resource-view";
11
11
  // A save that met someone else's change: theirs above yours, then keep mine or take theirs.
12
12
  export { NativeConflictSheet, type NativeConflictSheetProps, type NativeConflictSheetMessages } from "./NativeConflictSheet";
13
+ // Web parity twins: the form pieces beyond one input, a custom view, and a record in a peek.
14
+ export {
15
+ NativeFieldArrayRenderer,
16
+ NativeFileUploadField,
17
+ NativeRelationField,
18
+ NativeWizardForm,
19
+ type NativeFieldArrayRendererProps,
20
+ type NativeFileUploadFieldProps,
21
+ type NativeRelationFieldProps,
22
+ type NativeWizardFormProps,
23
+ } from "./NativeFormFields";
24
+ export { NativeCustomView, useNativeCustomView, type NativeCustomViewProps, type NativeCustomViewState } from "./NativeCustomView";
25
+ export { NativeRecordPeek, type NativeRecordPeekProps } from "./NativeRecordPeek";
@@ -67,6 +67,9 @@ export type NativeResourceSwipeableProps = Omit<InboxPageSlotMap["swipeable"], "
67
67
  /** How rows show: a list (the default) or cards in columns, as the web's `mode`. */
68
68
  export type NativeResourceViewMode = "list" | "grid";
69
69
 
70
+ /** The view types the phone draws: list, grid and gallery (ADR 0021). @stability Beta */
71
+ export type NativeResourceViewType = NativeResourceViewMode | "gallery";
72
+
70
73
  /**
71
74
  * Spread onto your card's Pressable: the press (the screen's `onRowPress`, else the peek), the
72
75
  * long press (the row's actions), and the label and actions screen readers use. The same wiring
@@ -118,9 +121,15 @@ export interface NativeResourceViewProps<T extends Row = Row> extends NativeReso
118
121
  /**
119
122
  * `"grid"`: cards in `numColumns` columns, as the web's `mode="grid"`. Sections, paging, pull to
120
123
  * refresh, the empty and error states, long press, accessibility and swipe actions all stay.
121
- * Default `"list"`.
124
+ * Default `"list"`. Prefer `type`; `mode` stays as its alias.
122
125
  */
123
126
  mode?: NativeResourceViewMode;
127
+ /**
128
+ * The view type (ADR 0021), as the web's `<ResourceView type>`: `"list"` (default), `"grid"`, or
129
+ * `"gallery"` (the grid as photos, from the view's `gallery` block). The phone has no board or
130
+ * calendar yet. Wins over `mode`.
131
+ */
132
+ type?: NativeResourceViewType;
124
133
  /** Columns in grid mode (React Native's FlatList name). Default 2. */
125
134
  numColumns?: number;
126
135
  /**
@@ -466,7 +475,8 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
466
475
  header,
467
476
  emptyState,
468
477
  searchable,
469
- mode = "list",
478
+ mode: modeProp = "list",
479
+ type,
470
480
  numColumns: columnsProp,
471
481
  gallery: screenGallery,
472
482
  renderCard,
@@ -474,6 +484,11 @@ function Screen<T extends Row = Row>(props: NativeResourceViewProps<T>) {
474
484
  testID = "native-resource-view",
475
485
  ...options
476
486
  } = props;
487
+ // `type` is the view type's name (ADR 0021); `mode` its alias. A gallery is the grid as photos.
488
+ const mode: NativeResourceViewMode = type === "gallery" ? "grid" : (type ?? modeProp);
489
+ if (type === "gallery" && !view.definition.gallery && !screenGallery?.image) {
490
+ throw new Error(`NativeResourceView(${view.resource}): type="gallery" needs a gallery block: the view's gallery.image, or gallery={{ image }}`);
491
+ }
477
492
  void _zone;
478
493
  const state = useNativeResourceView<T>(view, options);
479
494
  const keyExtractor = useCallback((row: T) => recordKey(view as AnyResourceView<Row>, row), [view]);
@@ -122,4 +122,12 @@ describe("NativeResourceView gallery", () => {
122
122
  await waitFor(() => expect(tile("p1")).not.toBeNull());
123
123
  expect(tile("p3")).not.toBeNull();
124
124
  });
125
+
126
+ it("takes the view type as `type` (ADR 0021): gallery is the grid as photos, and needs a gallery block", async () => {
127
+ render(<NativeResourceView view={view} type="gallery" onRowPress={() => undefined} />, { wrapper: wrap(provider()) });
128
+ await measured();
129
+ await waitFor(() => expect(tile("p1")).not.toBeNull());
130
+ vi.spyOn(console, "error").mockImplementation(() => {});
131
+ expect(() => render(<NativeResourceView view={plain} type="gallery" />, { wrapper: wrap(provider()) })).toThrow(/needs a gallery block/);
132
+ });
125
133
  });
@@ -4,6 +4,7 @@ export {
4
4
  type NativeResourceViewProps,
5
5
  type NativeResourceSwipeableProps,
6
6
  type NativeResourceViewMode,
7
+ type NativeResourceViewType,
7
8
  type NativeResourceCardActions,
8
9
  type NativeResourceCardPressableProps,
9
10
  } from "./NativeResourceView";
@@ -228,11 +228,11 @@ export interface NativeFormField {
228
228
  /** Choices that fit a segmented control; more go to a list. */
229
229
  const SEGMENTED_MAX = 4;
230
230
 
231
- function kindFor(display: DisplayHint, options: unknown[] | undefined, widget?: string): NativeFormFieldKind {
231
+ function kindFor(display: DisplayHint, options: unknown[] | undefined, control?: string): NativeFormFieldKind {
232
232
  if (options) return options.length <= SEGMENTED_MAX ? "segmented" : "select";
233
- // A phone number shows as text, so only the contract's `widget: "tel"` makes it one (as on the
233
+ // A phone number shows as text, so only the contract's `control: "tel"` (or its older `widget`) makes it one (as on the
234
234
  // web); a column's name is never read as a type.
235
- if (widget === "tel" && display === "text") return "tel";
235
+ if (control === "tel" && display === "text") return "tel";
236
236
  switch (display) {
237
237
  case "boolean":
238
238
  return "switch";
@@ -311,7 +311,7 @@ export function formFieldsFor<T extends Row>(
311
311
  return {
312
312
  key: f.field.name,
313
313
  label: f.label,
314
- kind: link ? ("link" as const) : kindFor(f.display, options, f.field.widget),
314
+ kind: link ? ("link" as const) : kindFor(f.display, options, f.field.control ?? f.field.widget),
315
315
  display: f.display,
316
316
  required: !readOnly && f.required,
317
317
  readOnly,