@marktiderman/genesis-ui-native 3.12.1 → 3.14.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 (35) hide show
  1. package/dist/{chunk-TUDJDIGC.js → chunk-DCCOZSGR.js} +4 -2
  2. package/dist/chunk-DCCOZSGR.js.map +1 -0
  3. package/dist/{chunk-47CDRP43.js → chunk-G5M2Q7OU.js} +77 -4
  4. package/dist/chunk-G5M2Q7OU.js.map +1 -0
  5. package/dist/{chunk-C2ARUGT7.js → chunk-SRCGQWE4.js} +3 -3
  6. package/dist/{chunk-C2ARUGT7.js.map → chunk-SRCGQWE4.js.map} +1 -1
  7. package/dist/{chunk-X5CPLUPZ.js → chunk-WTO3LIUS.js} +4 -77
  8. package/dist/chunk-WTO3LIUS.js.map +1 -0
  9. package/dist/components/index.js +2 -2
  10. package/dist/data/index.d.ts +170 -27
  11. package/dist/data/index.js +493 -24
  12. package/dist/data/index.js.map +1 -1
  13. package/dist/{inbox-page-BGqR_cBs.d.ts → inbox-page-DD1cQdF4.d.ts} +6 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +4 -4
  16. package/dist/layouts/index.d.ts +2 -2
  17. package/dist/layouts/index.js +2 -2
  18. package/package.json +3 -3
  19. package/src/data/NativeRecordPeek.tsx +12 -1
  20. package/src/data/__tests__/parity-data.test.tsx +26 -0
  21. package/src/data/resource-view/NativeRecordView.tsx +15 -2
  22. package/src/data/resource-view/NativeResourceView.tsx +153 -16
  23. package/src/data/resource-view/__tests__/native-record-view.test.tsx +24 -0
  24. package/src/data/resource-view/__tests__/native-resource-inbox.test.tsx +59 -0
  25. package/src/data/resource-view/__tests__/native-resource-lists.test.tsx +281 -0
  26. package/src/data/resource-view/index.ts +12 -1
  27. package/src/data/resource-view/list-controls.tsx +508 -0
  28. package/src/data/resource-view/mapping.ts +10 -0
  29. package/src/data/resource-view/messages.ts +70 -0
  30. package/src/data/resource-view/use-native-resource-view.ts +13 -3
  31. package/src/layouts/__tests__/inbox-page-start.test.tsx +39 -0
  32. package/src/layouts/inbox-page.tsx +7 -0
  33. package/dist/chunk-47CDRP43.js.map +0 -1
  34. package/dist/chunk-TUDJDIGC.js.map +0 -1
  35. package/dist/chunk-X5CPLUPZ.js.map +0 -1
@@ -0,0 +1,281 @@
1
+ // @feat:view-filters @feat:native-components
2
+ /**
3
+ * ADR 0017 on the phone: segments with counts and declared filters sent to the server, the
4
+ * view-type switcher, the view's own actions with their reasons, a board whose cards move through
5
+ * the resource's update, a calendar's agenda and month, and the inbox's markRead. Each reads the
6
+ * same core state and hooks the web's ResourceView does.
7
+ */
8
+ import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
9
+ import { QueryClient } from "@tanstack/react-query";
10
+ import type { ReactNode } from "react";
11
+ import { Alert, Pressable, Text, View } from "react-native";
12
+ import { afterEach, describe, expect, it, vi } from "vitest";
13
+ import { createMemoryStorageAdapter, defineResource, GenesisProvider, type DataProvider, type FilterParam, type ListParams } from "@marktiderman/genesis-core";
14
+ import { dayIn } from "@marktiderman/genesis-core/dates";
15
+ import { createLocalSavedViewStore, defineView } from "@marktiderman/genesis-core/resource-view";
16
+ import { NativeResourceView, type NativeResourceSwipeableProps } from "..";
17
+
18
+ type Task = { id: string; title: string; status: "todo" | "done"; due_on: string | null; unread: boolean };
19
+
20
+ const tasks = defineResource<Task>()({
21
+ name: "tasks",
22
+ key: "id",
23
+ labelField: "title",
24
+ fields: [
25
+ { name: "id", type: "string", hasDefault: true },
26
+ { name: "title", type: "string" },
27
+ { name: "status", type: "string", enumValues: ["todo", "done"] },
28
+ { name: "due_on", type: "datetime", dbType: "date", optional: true },
29
+ { name: "unread", type: "boolean" },
30
+ ],
31
+ });
32
+
33
+ const today = dayIn("UTC");
34
+ const ROWS: Task[] = [
35
+ { id: "a", title: "Write the plan", status: "todo", due_on: today, unread: true },
36
+ { id: "b", title: "Ship it", status: "done", due_on: today, unread: false },
37
+ { id: "c", title: "Tell people", status: "todo", due_on: null, unread: false },
38
+ ];
39
+
40
+ const matches = (row: Task, f: FilterParam) => {
41
+ const v = row[f.field as keyof Task] as unknown;
42
+ if (f.operator === "eq") return v === f.value;
43
+ if (f.operator === "in") return (f.value as unknown[]).includes(v);
44
+ if (f.operator === "is_null") return v === null;
45
+ if (f.operator === "gte") return v !== null && String(v) >= String(f.value);
46
+ if (f.operator === "lt") return v !== null && String(v) < String(f.value);
47
+ return true;
48
+ };
49
+
50
+ function provider(extra: Partial<DataProvider> = {}) {
51
+ return {
52
+ getList: vi.fn(async (_r: string, params: ListParams) => {
53
+ const data = ROWS.filter((row) => (params.filters ?? []).every((f) => matches(row, f)));
54
+ return { data, total: data.length };
55
+ }),
56
+ getOne: vi.fn(async (_r: string, { id }: { id: string }) => ({ data: ROWS.find((r) => r.id === id) })),
57
+ getMany: vi.fn(async () => ({ data: [] })),
58
+ create: vi.fn(),
59
+ update: vi.fn(async (_r: string, { id, data }: { id: string; data: Partial<Task> }) => ({ data: { ...ROWS.find((r) => r.id === id)!, ...data } })),
60
+ deleteOne: vi.fn(),
61
+ ...extra,
62
+ } as unknown as DataProvider & { getList: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> };
63
+ }
64
+
65
+ function wrap(p: DataProvider) {
66
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
67
+ return ({ children }: { children: ReactNode }) => (
68
+ <GenesisProvider provider={p} queryClient={queryClient}>
69
+ {children}
70
+ </GenesisProvider>
71
+ );
72
+ }
73
+
74
+ function TestSwipe({ actions, testID, children }: NativeResourceSwipeableProps) {
75
+ return (
76
+ <View testID={testID}>
77
+ {children}
78
+ {actions.map((action) => (
79
+ <Pressable key={action.id} testID={`${testID}-${action.id}`} onPress={() => action.onPress()}>
80
+ <Text>{action.reason ? `${action.label}: ${action.reason}` : action.label}</Text>
81
+ </Pressable>
82
+ ))}
83
+ </View>
84
+ );
85
+ }
86
+
87
+ const alert = Alert.alert as unknown as ReturnType<typeof vi.fn>;
88
+ function pressAlert(text: string) {
89
+ const buttons = alert.mock.calls.at(-1)?.[2] as { text: string; onPress?: () => void }[];
90
+ act(() => buttons.find((b) => b.text === text)?.onPress?.());
91
+ }
92
+ const lastFilters = (p: { getList: ReturnType<typeof vi.fn> }) => (p.getList.mock.calls.at(-1)![1] as ListParams).filters ?? [];
93
+
94
+ afterEach(() => alert.mockClear());
95
+
96
+ describe("segments and declared filters on the phone", () => {
97
+ const view = defineView(tasks, {
98
+ segments: [
99
+ { id: "open", label: "Open", where: { status: "todo" }, count: true },
100
+ { id: "all", label: "All" },
101
+ ],
102
+ filters: [{ field: "status" }],
103
+ });
104
+
105
+ it("opens on the first segment with its count, and switches", async () => {
106
+ const p = provider();
107
+ render(<NativeResourceView view={view} />, { wrapper: wrap(p) });
108
+ await screen.findByText("Write the plan");
109
+ expect(screen.queryByText("Ship it")).toBeNull();
110
+ expect(lastFilters(p)).toContainEqual({ field: "status", operator: "eq", value: "todo" });
111
+ await waitFor(() => expect(screen.getByTestId("native-resource-view-segment-open").textContent).toContain("2"));
112
+ fireEvent.click(screen.getByTestId("native-resource-view-segment-all"));
113
+ await screen.findByText("Ship it");
114
+ });
115
+
116
+ it("sends a declared filter set in the Filters sheet", async () => {
117
+ const p = provider();
118
+ render(<NativeResourceView view={view} defaultSegment="all" />, { wrapper: wrap(p) });
119
+ await screen.findByText("Ship it");
120
+ fireEvent.click(screen.getByTestId("native-resource-view-filters"));
121
+ fireEvent.click(await screen.findByTestId("native-resource-view-filters-status-done"));
122
+ await waitFor(() => expect(screen.queryByText("Write the plan")).toBeNull());
123
+ expect(lastFilters(p)).toContainEqual({ field: "status", operator: "eq", value: "done" });
124
+ });
125
+ });
126
+
127
+ describe("the view's actions on the phone", () => {
128
+ const view = defineView(tasks, {
129
+ actions: [{ name: "finish", label: "Finish", can: (t) => (t.status === "done" ? "It's already done." : true) }],
130
+ });
131
+
132
+ it("puts the view's actions on each row with their reasons, and runs an allowed one", async () => {
133
+ const runAction = vi.fn(async () => ({ data: null }));
134
+ render(<NativeResourceView view={view} swipeable={TestSwipe} />, { wrapper: wrap(provider({ runAction })) });
135
+ await screen.findByText("Ship it");
136
+ expect(screen.getByTestId("native-resource-view-row-b-swipe-finish").textContent).toContain("It's already done.");
137
+ fireEvent.click(screen.getByTestId("native-resource-view-row-b-swipe-finish"));
138
+ expect(runAction).not.toHaveBeenCalled();
139
+ fireEvent.click(screen.getByTestId("native-resource-view-row-a-swipe-finish"));
140
+ await waitFor(() => expect(runAction).toHaveBeenCalledWith("tasks", { id: "a", action: "finish" }));
141
+ });
142
+ });
143
+
144
+ describe("the switcher, the board and the calendar on the phone", () => {
145
+ const view = defineView(tasks, {
146
+ types: ["list", "board", "calendar"],
147
+ board: { field: "status" },
148
+ calendar: { field: "due_on" },
149
+ });
150
+
151
+ it("switches to the board, keeps the choice in the store, and moves a card through the resource's update", async () => {
152
+ const p = provider();
153
+ const store = createLocalSavedViewStore({ storage: createMemoryStorageAdapter() });
154
+ render(<NativeResourceView view={view} savedViews={store} />, { wrapper: wrap(p) });
155
+ await screen.findByText("Write the plan");
156
+ fireEvent.click(screen.getByText("Board"));
157
+ const todo = await screen.findByTestId("native-resource-view-board-column-todo");
158
+ await within(todo).findByText("Write the plan");
159
+ expect(store.forViewer!(null).readCurrent!("tasks")).toEqual({ type: "board" });
160
+ fireEvent.contextMenu(screen.getByTestId("native-resource-view-board-card-a"));
161
+ pressAlert("Move to Done");
162
+ await waitFor(() => expect(p.update).toHaveBeenCalledWith("tasks", expect.objectContaining({ id: "a", data: { status: "done" } })));
163
+ });
164
+
165
+ it("draws the calendar's agenda and month from the view's calendar block", async () => {
166
+ render(<NativeResourceView view={view} type="calendar" />, { wrapper: wrap(provider()) });
167
+ await screen.findByTestId("native-resource-view-calendar-agenda");
168
+ await screen.findByTestId("native-resource-view-calendar-event-a");
169
+ expect(screen.getByTestId("native-resource-view-calendar-event-b")).toBeTruthy();
170
+ fireEvent.click(screen.getByText("Month"));
171
+ await screen.findByTestId("native-resource-view-calendar-month");
172
+ fireEvent.click(screen.getByTestId(`native-resource-view-calendar-day-${today}`));
173
+ await screen.findByTestId("native-resource-view-calendar-event-a");
174
+ });
175
+ });
176
+
177
+ describe("the inbox on the phone", () => {
178
+ it("needs the view's inbox block", () => {
179
+ const plain = defineView(tasks, {});
180
+ expect(() => render(<NativeResourceView view={plain} type="inbox" />, { wrapper: wrap(provider()) })).toThrow(/inbox block/);
181
+ });
182
+
183
+ it("runs the view's markRead on opening an unread row", async () => {
184
+ const runAction = vi.fn(async () => ({ data: null }));
185
+ const inbox = defineView(tasks, { inbox: { unread: "unread" }, actions: [{ name: "markRead", label: "Mark read" }] });
186
+ render(<NativeResourceView view={inbox} type="inbox" onRowPress={vi.fn()} />, { wrapper: wrap(provider({ runAction })) });
187
+ fireEvent.click(await screen.findByText("Write the plan"));
188
+ await waitFor(() => expect(runAction).toHaveBeenCalledWith("tasks", { id: "a", action: "markRead" }));
189
+ fireEvent.click(screen.getByText("Ship it"));
190
+ expect(runAction).toHaveBeenCalledTimes(1);
191
+ });
192
+
193
+ it("doesn't run markRead when the provider serves no actions for the resource", async () => {
194
+ // @feat:declared-data-access
195
+ const runAction = vi.fn(async () => ({ data: null }));
196
+ const capabilities = vi.fn(async () => ({ search: true, sort: true, filterOperators: [], bulkWrites: false, versionedWrites: false, compositeKeys: false, actions: false }));
197
+ const inbox = defineView(tasks, { inbox: { unread: "unread" }, actions: [{ name: "markRead", label: "Mark read" }] });
198
+ render(<NativeResourceView view={inbox} type="inbox" onRowPress={vi.fn()} />, { wrapper: wrap(provider({ runAction, capabilities: capabilities as DataProvider["capabilities"] })) });
199
+ await waitFor(() => expect(capabilities).toHaveBeenCalled());
200
+ await act(async () => undefined);
201
+ fireEvent.click(await screen.findByText("Write the plan"));
202
+ await act(async () => undefined);
203
+ expect(runAction).not.toHaveBeenCalled();
204
+ });
205
+
206
+ // A row pressed before the capabilities answer opens without being marked read: a press is one
207
+ // tap, with no open row to come back to, so the next press after the answer marks it.
208
+ it("runs markRead through the provider only once its capabilities answer, at the row's version", async () => {
209
+ // @feat:declared-data-access
210
+ const runAction = vi.fn(async () => ({ data: null }));
211
+ type Caps = Awaited<ReturnType<NonNullable<DataProvider["capabilities"]>>>;
212
+ const waiting: ((c: Caps) => void)[] = [];
213
+ const capabilities = vi.fn(() => new Promise<Caps>((resolve) => waiting.push(resolve))) as DataProvider["capabilities"];
214
+ const answer = (c: Caps) => waiting.splice(0).forEach((resolve) => resolve(c));
215
+ const inbox = defineView(tasks, { inbox: { unread: "unread" }, actions: [{ name: "markRead", label: "Mark read" }] });
216
+ render(<NativeResourceView view={inbox} type="inbox" onRowPress={vi.fn()} />, { wrapper: wrap(provider({ runAction, capabilities })) });
217
+ fireEvent.click(await screen.findByText("Write the plan"));
218
+ await act(async () => undefined);
219
+ expect(runAction).not.toHaveBeenCalled();
220
+ answer({ search: true, sort: true, filterOperators: [], bulkWrites: false, versionedWrites: true, compositeKeys: false, actions: true, version: { field: "title", kind: "timestamp" } });
221
+ // Once the answer has rendered, opening the row runs markRead at the row's version.
222
+ await waitFor(() => {
223
+ fireEvent.click(screen.getByText("Write the plan"));
224
+ expect(runAction).toHaveBeenCalledWith("tasks", { id: "a", action: "markRead", expectedVersion: "Write the plan" });
225
+ });
226
+ });
227
+ });
228
+
229
+ describe("review fixes on the phone", () => {
230
+ it("fetches nothing while the screen holds enabled off, in every type, segment counts included", async () => {
231
+ const inbox = defineView(tasks, { inbox: { unread: "unread" }, calendar: { field: "due_on" }, board: { field: "status" }, segments: [{ id: "open", label: "Open", where: { status: "todo" }, count: true }] });
232
+ for (const type of ["list", "inbox", "calendar", "board"] as const) {
233
+ const p = provider();
234
+ const { unmount } = render(<NativeResourceView view={inbox} type={type} enabled={false} />, { wrapper: wrap(p) });
235
+ await act(async () => undefined);
236
+ expect(p.getList, type).not.toHaveBeenCalled();
237
+ unmount();
238
+ }
239
+ });
240
+
241
+ it("says a calendar read failed, with a retry, instead of an empty calendar", async () => {
242
+ const view = defineView(tasks, { calendar: { field: "due_on" } });
243
+ const p = provider({ getList: vi.fn(async () => Promise.reject(new Error("The server is down."))) } as never);
244
+ render(<NativeResourceView view={view} type="calendar" />, { wrapper: wrap(p) });
245
+ expect(await screen.findByTestId("native-resource-view-calendar-error")).toBeTruthy();
246
+ expect(screen.queryByText("Nothing on this day")).toBeNull();
247
+ fireEvent.click(screen.getByTestId("native-resource-view-calendar-retry"));
248
+ await waitFor(() => expect(p.getList.mock.calls.length).toBeGreaterThan(1));
249
+ });
250
+
251
+ it("places the calendar on the screen's scopeTimeZone, the clock its cells use", async () => {
252
+ type Session = { id: string; title: string; starts_at: string };
253
+ const sessions = defineResource<Session>()({
254
+ name: "sessions",
255
+ key: "id",
256
+ labelField: "title",
257
+ fields: [
258
+ { name: "id", type: "string" },
259
+ { name: "title", type: "string" },
260
+ { name: "starts_at", type: "datetime", dbType: "timestamptz" },
261
+ ],
262
+ });
263
+ const view = defineView(sessions, { fields: { starts_at: { timeZone: "scope" } }, calendar: { field: "starts_at" } });
264
+ const p = provider();
265
+ render(<NativeResourceView view={view} type="calendar" scopeTimeZone="Pacific/Kiritimati" />, { wrapper: wrap(p) });
266
+ await waitFor(() => expect(p.getList).toHaveBeenCalled());
267
+ const gte = (p.getList.mock.calls[0]![1] as ListParams).filters!.find((f) => f.operator === "gte") as { value: unknown };
268
+ // The window starts at a Kiritimati midnight (UTC+14): 10:00 UTC the day before.
269
+ expect(String(gte.value)).toMatch(/T10:00:00\.000Z$/);
270
+ });
271
+
272
+ it("reads the peeked record in the list's scope, as the web's table and inbox do", async () => {
273
+ const view = defineView(tasks, { segments: [{ id: "open", label: "Open", where: { status: "todo" } }] });
274
+ const p = provider();
275
+ render(<NativeResourceView view={view} />, { wrapper: wrap(p) });
276
+ fireEvent.click(await screen.findByText("Write the plan"));
277
+ await waitFor(() => expect(p.getOne).toHaveBeenCalled());
278
+ expect(vi.mocked(p.getOne).mock.calls[0]![1]).toMatchObject({ id: "a", scope: [{ field: "status", operator: "eq", value: "todo" }] });
279
+ });
280
+ });
281
+
@@ -20,6 +20,17 @@ export {
20
20
  type UseNativeResourceViewReturn,
21
21
  } from "./use-native-resource-view";
22
22
  export { NativeResourceFormSheet, type NativeResourceFormSheetProps } from "./NativeResourceFormSheet";
23
+ // A list's segments, filters and type switcher, and the board and calendar types, on core's list state.
24
+ export {
25
+ NativeResourceBoard,
26
+ NativeResourceCalendar,
27
+ NativeViewFilterControls,
28
+ NativeViewSegments,
29
+ NativeViewTypeSwitcher,
30
+ NATIVE_VIEW_TYPES,
31
+ nativeSwitchableTypes,
32
+ useNativeListMessages,
33
+ } from "./list-controls";
23
34
  export {
24
35
  DisplayRenderersProvider,
25
36
  DisplayTimeZonesProvider,
@@ -56,7 +67,7 @@ export {
56
67
  type NativeResourceSection,
57
68
  type NativeResourceSwipeAction,
58
69
  } from "./mapping";
59
- export { defaultNativeResourceViewMessages, type NativeResourceViewMessages } from "./messages";
70
+ export { defaultNativeListMessages, defaultNativeResourceViewMessages, type NativeListMessages, type NativeResourceViewMessages } from "./messages";
60
71
  export {
61
72
  NativeRecordView,
62
73
  NativeRecordViewMenu,