@marktiderman/genesis-ui-native 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{chunk-YJV5MMZX.js → chunk-7HWS2JGX.js} +7 -741
  2. package/dist/chunk-7HWS2JGX.js.map +1 -0
  3. package/dist/{chunk-IDHW2NOP.js → chunk-C6Q5ZAVT.js} +232 -6
  4. package/dist/chunk-C6Q5ZAVT.js.map +1 -0
  5. package/dist/{chunk-YI7XVY2D.js → chunk-ON7WP4T6.js} +13 -479
  6. package/dist/chunk-ON7WP4T6.js.map +1 -0
  7. package/dist/chunk-PO3MK6IY.js +1231 -0
  8. package/dist/chunk-PO3MK6IY.js.map +1 -0
  9. package/dist/chunk-SXCG2REG.js +479 -0
  10. package/dist/chunk-SXCG2REG.js.map +1 -0
  11. package/dist/components/index.d.ts +10 -3
  12. package/dist/components/index.js +3 -4
  13. package/dist/data/index.d.ts +482 -4
  14. package/dist/data/index.js +1480 -17
  15. package/dist/data/index.js.map +1 -1
  16. package/dist/inbox-page-DZUR-PJ1.d.ts +199 -0
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.js +5 -5
  19. package/dist/layouts/index.d.ts +4 -195
  20. package/dist/layouts/index.js +3 -3
  21. package/package.json +2 -2
  22. package/src/components/__tests__/button-a11y.test.tsx +17 -0
  23. package/src/components/button.tsx +8 -2
  24. package/src/components/image.tsx +5 -0
  25. package/src/data/NativeDetailPanel.tsx +8 -1
  26. package/src/data/index.ts +1 -0
  27. package/src/data/resource-view/NativeResourceFormSheet.tsx +305 -0
  28. package/src/data/resource-view/NativeResourceView.tsx +536 -0
  29. package/src/data/resource-view/NativeResourceWorkspace.tsx +657 -0
  30. package/src/data/resource-view/__tests__/native-resource-view.test.tsx +977 -0
  31. package/src/data/resource-view/__tests__/native-resource-workspace.test.tsx +356 -0
  32. package/src/data/resource-view/display.tsx +259 -0
  33. package/src/data/resource-view/index.ts +61 -0
  34. package/src/data/resource-view/mapping.ts +333 -0
  35. package/src/data/resource-view/messages.ts +121 -0
  36. package/src/data/resource-view/use-native-resource-view.ts +309 -0
  37. package/dist/chunk-EFXCJ5AN.js +0 -234
  38. package/dist/chunk-EFXCJ5AN.js.map +0 -1
  39. package/dist/chunk-FIITITXO.js +0 -492
  40. package/dist/chunk-FIITITXO.js.map +0 -1
  41. package/dist/chunk-IDHW2NOP.js.map +0 -1
  42. package/dist/chunk-YI7XVY2D.js.map +0 -1
  43. package/dist/chunk-YJV5MMZX.js.map +0 -1
@@ -0,0 +1,356 @@
1
+ // @feat:native-components
2
+ /**
3
+ * NativeResourceWorkspace: one record's screen from a genesis-core workspace, natively.
4
+ * - the title and the header menu come from getNativeResourceWorkspaceStackOptions;
5
+ * - up to four sections are a segmented control, more are pushed rows;
6
+ * - a list section is an embedded NativeResourceView filtered by the row;
7
+ * - a settings section saves only its changed listed keys; a zero-row save is a refusal, inline;
8
+ * - readiness is a group of checks with their tones.
9
+ */
10
+ import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
11
+ import { QueryClient } from "@tanstack/react-query";
12
+ import { useState, type ReactNode } from "react";
13
+ import { ActionSheetIOS, Alert, Platform } from "react-native";
14
+ import { beforeEach, describe, expect, it, vi } from "vitest";
15
+ import { defineResource, GenesisProvider, ViewerScope, type DataProvider, type ListParams, type Viewer } from "@marktiderman/genesis-core";
16
+ import { defineView, defineWorkspace } from "@marktiderman/genesis-core/resource-view";
17
+ import { getNativeResourceWorkspaceStackOptions, NativeResourceWorkspace, NativeResourceWorkspaceMenu, parseSettingNumber } from "..";
18
+
19
+ type Brand = { id: string; name: string; website: string | null; public: boolean; is_default: boolean };
20
+ type Product = { id: string; brand_id: string; title: string };
21
+
22
+ const brands = defineResource<Brand>()({
23
+ name: "brands",
24
+ key: "id",
25
+ labelField: "name",
26
+ fields: [
27
+ { name: "id", type: "string", hasDefault: true },
28
+ { name: "name", type: "string" },
29
+ { name: "website", type: "string", widget: "url", nullable: true },
30
+ { name: "public", type: "boolean", hasDefault: true },
31
+ { name: "is_default", type: "boolean", hasDefault: true },
32
+ ],
33
+ });
34
+ const products = defineResource<Product>()({
35
+ name: "products",
36
+ key: "id",
37
+ labelField: "title",
38
+ fields: [
39
+ { name: "id", type: "string", hasDefault: true },
40
+ { name: "brand_id", type: "string" },
41
+ { name: "title", type: "string" },
42
+ ],
43
+ });
44
+
45
+ const brandsView = defineView(brands, {
46
+ actions: [
47
+ { name: "archive", label: "Archive", confirm: "Archive this brand?", can: (b) => (b.is_default ? "The default brand stays." : true) },
48
+ { name: "publish", label: "Publish" },
49
+ { name: "purge", label: "Purge", destructive: true },
50
+ ],
51
+ });
52
+ const productsView = defineView(products);
53
+
54
+ const sections = [
55
+ { id: "products", label: "Products", list: { view: productsView, filter: (b: Brand) => ({ brand_id: b.id }) } },
56
+ { id: "settings", label: "Settings", settings: ["website", "public"] as const },
57
+ { id: "activity", label: "Activity" },
58
+ ];
59
+ const workspace = defineWorkspace(brandsView, {
60
+ sections,
61
+ readiness: (b) => [
62
+ { title: "Has a website", ok: !!b.website, reason: "Add the website.", tone: "danger" },
63
+ { title: "Has a name", ok: !!b.name },
64
+ ],
65
+ });
66
+
67
+ const brand: Brand = { id: "b1", name: "Northwind", website: null, public: false, is_default: true };
68
+
69
+ function provider(over: Partial<DataProvider> = {}): DataProvider {
70
+ return {
71
+ getList: vi.fn(async () => ({ data: [{ id: "p1", brand_id: "b1", title: "Kettle" }], total: 1 })) as DataProvider["getList"],
72
+ getOne: vi.fn(async () => ({ data: brand })) as DataProvider["getOne"],
73
+ getMany: vi.fn(async () => ({ data: [] })),
74
+ create: vi.fn(async (_r, { data }) => ({ data: { id: "new", ...(data as object) } })) as DataProvider["create"],
75
+ update: vi.fn(async (_r, { id, data }) => ({ data: { ...brand, id, ...(data as object) } })) as DataProvider["update"],
76
+ deleteOne: vi.fn(async (_r, { id }) => ({ data: { id } })),
77
+ runAction: vi.fn(async () => ({ data: brand })),
78
+ ...over,
79
+ };
80
+ }
81
+
82
+ function wrap(p: DataProvider) {
83
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
84
+ return ({ children }: { children: ReactNode }) => (
85
+ <GenesisProvider provider={p} queryClient={queryClient}>
86
+ {children}
87
+ </GenesisProvider>
88
+ );
89
+ }
90
+
91
+ beforeEach(() => {
92
+ vi.restoreAllMocks();
93
+ // The react-native mock's Alert and ActionSheetIOS are module-level fns: start each test clean.
94
+ (Alert.alert as unknown as { mockClear: () => void }).mockClear();
95
+ (ActionSheetIOS.showActionSheetWithOptions as unknown as { mockClear: () => void }).mockClear();
96
+ });
97
+
98
+ describe("NativeResourceWorkspace", () => {
99
+ it("puts the title in the navigation bar and the actions in the header menu", () => {
100
+ const options = getNativeResourceWorkspaceStackOptions({ workspace, row: brand });
101
+ expect(options.title).toBe("Northwind");
102
+ expect(typeof options.headerRight).toBe("function");
103
+ const none = defineWorkspace(brandsView, { header: { actions: [] }, sections: [{ id: "a", label: "A" }] });
104
+ expect(getNativeResourceWorkspaceStackOptions({ workspace: none, row: brand }).headerRight).toBeUndefined();
105
+ });
106
+
107
+ it("iOS: the menu is an action sheet; a refused action explains, a confirm asks, then the provider runs it", async () => {
108
+ const alert = vi.spyOn(Alert, "alert").mockImplementation(() => {});
109
+ const sheet = vi.spyOn(ActionSheetIOS, "showActionSheetWithOptions").mockImplementation(() => {});
110
+ const p = provider();
111
+ render(<NativeResourceWorkspaceMenu workspace={workspace} row={brand} />, { wrapper: wrap(p) });
112
+ fireEvent.click(screen.getByTestId("native-resource-workspace-menu"));
113
+ const [options, pick] = sheet.mock.calls[0]!;
114
+ expect(options.options).toEqual(["Archive (The default brand stays.)", "Publish", "Purge", "Cancel"]);
115
+ expect(options.cancelButtonIndex).toBe(3);
116
+ expect(options.destructiveButtonIndex).toEqual([2]);
117
+ pick(0);
118
+ expect(alert).toHaveBeenLastCalledWith("Archive", "The default brand stays.");
119
+ pick(1);
120
+ await waitFor(() => expect(p.runAction).toHaveBeenCalledWith("brands", { id: "b1", action: "publish" }));
121
+
122
+ alert.mockClear();
123
+ const onAction = vi.fn();
124
+ render(<NativeResourceWorkspaceMenu workspace={workspace} row={{ ...brand, is_default: false }} onAction={onAction} testID="menu2" />, {
125
+ wrapper: wrap(provider()),
126
+ });
127
+ fireEvent.click(screen.getByTestId("menu2"));
128
+ sheet.mock.calls.at(-1)![1](0);
129
+ const [title, , confirm] = alert.mock.calls[0]!;
130
+ expect(title).toBe("Archive this brand?");
131
+ expect(confirm!.length).toBe(2);
132
+ expect(onAction).not.toHaveBeenCalled();
133
+ confirm![1]!.onPress!();
134
+ await waitFor(() => expect(onAction).toHaveBeenCalledWith("archive", { ...brand, is_default: false }));
135
+ });
136
+
137
+ it("Android: the menu is a sheet of rows, never an alert with too many buttons", async () => {
138
+ const os = Platform.OS;
139
+ Platform.OS = "android";
140
+ const alert = vi.spyOn(Alert, "alert").mockImplementation(() => {});
141
+ try {
142
+ const p = provider();
143
+ render(<NativeResourceWorkspaceMenu workspace={workspace} row={{ ...brand, is_default: false }} />, { wrapper: wrap(p) });
144
+ fireEvent.click(screen.getByTestId("native-resource-workspace-menu"));
145
+ expect(alert).not.toHaveBeenCalled();
146
+ expect((await screen.findByTestId("native-resource-workspace-menu-purge")).textContent).toContain("Purge");
147
+ fireEvent.click(screen.getByTestId("native-resource-workspace-menu-publish"));
148
+ await waitFor(() => expect(p.runAction).toHaveBeenCalledTimes(1));
149
+ } finally {
150
+ Platform.OS = os;
151
+ }
152
+ });
153
+
154
+ it("runs one action at a time", async () => {
155
+ let finish!: () => void;
156
+ const runAction = vi.fn(() => new Promise<{ data: null }>((resolve) => (finish = () => resolve({ data: null }))));
157
+ const sheet = vi.spyOn(ActionSheetIOS, "showActionSheetWithOptions").mockImplementation(() => {});
158
+ render(<NativeResourceWorkspaceMenu workspace={workspace} row={brand} />, { wrapper: wrap(provider({ runAction: runAction as never })) });
159
+ fireEvent.click(screen.getByTestId("native-resource-workspace-menu"));
160
+ const pick = sheet.mock.calls[0]![1];
161
+ pick(1);
162
+ pick(1);
163
+ await waitFor(() => expect(runAction).toHaveBeenCalledTimes(1));
164
+ await waitFor(() => expect(screen.getByTestId("native-resource-workspace-menu").getAttribute("aria-disabled")).toBe("true"));
165
+ finish();
166
+ await waitFor(() => expect(screen.getByTestId("native-resource-workspace-menu").getAttribute("aria-disabled")).not.toBe("true"));
167
+ });
168
+
169
+ it("names accessibility actions with a prefix, so 'activate' can't take over the button", async () => {
170
+ const view = defineView(brands, { actions: [{ name: "activate", label: "Activate" }] });
171
+ const ws = defineWorkspace(view, { sections: [{ id: "a", label: "A" }] });
172
+ const p = provider();
173
+ render(<NativeResourceWorkspaceMenu workspace={ws} row={brand} />, { wrapper: wrap(p) });
174
+ const button = screen.getByTestId("native-resource-workspace-menu");
175
+ expect(button.getAttribute("data-a11y-actions")).toBe("action:activate");
176
+ // The platform's own "activate" does nothing here; the prefixed one runs the action.
177
+ button.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "activate" }));
178
+ expect(p.runAction).not.toHaveBeenCalled();
179
+ button.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "action:activate" }));
180
+ await waitFor(() => expect(p.runAction).toHaveBeenCalledWith("brands", { id: "b1", action: "activate" }));
181
+ });
182
+
183
+ it("hides actions when nothing can run them, or the screen turns them off", () => {
184
+ render(<NativeResourceWorkspaceMenu workspace={workspace} row={brand} testID="none" />, { wrapper: wrap(provider({ runAction: undefined })) });
185
+ expect(screen.queryByTestId("none")).toBeNull();
186
+ const sheet = vi.spyOn(ActionSheetIOS, "showActionSheetWithOptions").mockImplementation(() => {});
187
+ render(<NativeResourceWorkspaceMenu workspace={workspace} row={brand} can={(name) => name !== "publish"} />, { wrapper: wrap(provider()) });
188
+ fireEvent.click(screen.getByTestId("native-resource-workspace-menu"));
189
+ expect(sheet.mock.calls.at(-1)![0].options).not.toContain("Publish");
190
+ });
191
+
192
+ it("shows up to four sections as a segmented control, and the readiness checks", () => {
193
+ render(<NativeResourceWorkspace workspace={workspace} row={brand} section="activity" slots={{ activity: <></> }} switcher={<></>} />, {
194
+ wrapper: wrap(provider()),
195
+ });
196
+ const control = screen.getByTestId("native-resource-workspace-sections");
197
+ expect(within(control).getByTestId("native-resource-workspace-sections-option-settings")).toBeTruthy();
198
+ expect(screen.getByTestId("native-resource-workspace-readiness").textContent).toBe("1 problem to fix");
199
+ expect(screen.getByTestId("native-resource-workspace-check-0-chip").textContent).toBe("To do");
200
+ expect(screen.getByText("Add the website.")).toBeTruthy();
201
+ expect(screen.getByTestId("native-resource-workspace-check-1-chip").textContent).toBe("Done");
202
+ });
203
+
204
+ it("shows the summary chip alone once every check is met", () => {
205
+ render(<NativeResourceWorkspace workspace={workspace} row={{ ...brand, website: "https://x.example" }} section="activity" messages={{ ready: "Ready to go" }} />, {
206
+ wrapper: wrap(provider()),
207
+ });
208
+ expect(screen.getByTestId("native-resource-workspace-readiness").textContent).toBe("Ready to go");
209
+ expect(screen.queryByTestId("native-resource-workspace-checks")).toBeNull();
210
+ });
211
+
212
+ it("pushes sections when there are more than four", () => {
213
+ const wide = defineWorkspace(brandsView, {
214
+ sections: ["a", "b", "c", "d", "e"].map((id) => ({ id, label: id.toUpperCase() })),
215
+ });
216
+ const onOpenSection = vi.fn();
217
+ render(<NativeResourceWorkspace workspace={wide} row={brand} onOpenSection={onOpenSection} />, { wrapper: wrap(provider()) });
218
+ expect(screen.queryByTestId("native-resource-workspace-sections-option-a")).toBeNull();
219
+ fireEvent.click(screen.getByTestId("native-resource-workspace-section-e"));
220
+ expect(onOpenSection).toHaveBeenCalledWith("e");
221
+ });
222
+
223
+ it("draws a list section as an embedded NativeResourceView filtered by the row", async () => {
224
+ const p = provider();
225
+ render(<NativeResourceWorkspace workspace={workspace} row={brand} />, { wrapper: wrap(p) });
226
+ expect(await screen.findByText("Kettle")).toBeTruthy();
227
+ const params = (p.getList as ReturnType<typeof vi.fn>).mock.calls[0]![1] as ListParams;
228
+ expect(params.filters).toContainEqual({ field: "brand_id", operator: "eq", value: "b1" });
229
+ });
230
+
231
+ it("switches sections and saves only the changed listed keys", async () => {
232
+ const p = provider();
233
+ const onSaved = vi.fn();
234
+ render(<NativeResourceWorkspace workspace={workspace} row={brand} onSaved={onSaved} />, { wrapper: wrap(p) });
235
+ fireEvent.click(screen.getByTestId("native-resource-workspace-sections-option-settings"));
236
+ const input = screen.getByTestId("native-resource-workspace-settings-website-input");
237
+ fireEvent.change(input, { target: { value: "https://northwind.example" } });
238
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
239
+ await waitFor(() => expect(p.update).toHaveBeenCalledWith("brands", { id: "b1", data: { website: "https://northwind.example" } }));
240
+ await waitFor(() => expect(onSaved).toHaveBeenCalled());
241
+ });
242
+
243
+ it("shows a zero-row save as a refusal, inline", async () => {
244
+ const p = provider({ update: vi.fn(async () => ({ data: null })) as unknown as DataProvider["update"] });
245
+ render(<NativeResourceWorkspace workspace={workspace} row={brand} section="settings" />, { wrapper: wrap(p) });
246
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-website-input"), { target: { value: "https://x.example" } });
247
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
248
+ expect((await screen.findByTestId("native-resource-workspace-settings-refusal")).textContent).toContain("This brand was not changed.");
249
+ });
250
+ });
251
+
252
+ describe("NativeResourceWorkspace review fixes", () => {
253
+ const locking = defineWorkspace(
254
+ defineView(brands, {
255
+ fields: { website: { visible: (v) => v["public"] === true } },
256
+ can: { update: (b) => (b.is_default ? "Locked." : true) },
257
+ }),
258
+ { sections: [{ id: "settings", label: "Settings", settings: ["public", "website", "name"] }] },
259
+ );
260
+
261
+ it("shows settings read-only with the reason when the view refuses update", () => {
262
+ render(<NativeResourceWorkspace workspace={locking} row={brand} />, { wrapper: wrap(provider()) });
263
+ expect(screen.getByTestId("native-resource-workspace-settings-locked").textContent).toContain("Locked.");
264
+ expect(screen.queryByTestId("native-resource-workspace-settings-save")).toBeNull();
265
+ });
266
+
267
+ it("leaves a field hidden by `visible` out of the save", async () => {
268
+ const p = provider();
269
+ render(<NativeResourceWorkspace workspace={locking} row={{ ...brand, is_default: false, public: true }} />, { wrapper: wrap(p) });
270
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-website-input"), { target: { value: "https://x.example" } });
271
+ fireEvent.change(screen.getByTestId("native-resource-workspace-settings-name-input"), { target: { value: "Southwind" } });
272
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-public-input"));
273
+ expect(screen.queryByTestId("native-resource-workspace-settings-website-input")).toBeNull();
274
+ fireEvent.click(screen.getByTestId("native-resource-workspace-settings-save"));
275
+ await waitFor(() => expect(p.update).toHaveBeenCalledWith("brands", { id: "b1", data: { public: false, name: "Southwind" } }));
276
+ });
277
+
278
+ it("opens a section in place with a way back when there are more than four and no onOpenSection", () => {
279
+ const wide = defineWorkspace(brandsView, { sections: ["a", "b", "c", "d", "e"].map((id) => ({ id, label: id.toUpperCase() })) });
280
+ render(<NativeResourceWorkspace workspace={wide} row={brand} slots={{ e: <p>Section E</p> }} />, { wrapper: wrap(provider()) });
281
+ fireEvent.click(screen.getByTestId("native-resource-workspace-section-e"));
282
+ expect(screen.getByText("Section E")).toBeTruthy();
283
+ fireEvent.click(screen.getByTestId("native-resource-workspace-all-sections"));
284
+ expect(screen.getByTestId("native-resource-workspace-section-a")).toBeTruthy();
285
+ });
286
+
287
+ it("parses a number as typed, comma decimals too, never NaN", () => {
288
+ expect(parseSettingNumber("1.5")).toBe(1.5);
289
+ expect(parseSettingNumber("1,50")).toBe(1.5);
290
+ expect(parseSettingNumber(" -2 ")).toBe(-2);
291
+ expect(parseSettingNumber("1,5,0")).toBeNull();
292
+ expect(parseSettingNumber("abc")).toBeNull();
293
+ expect(parseSettingNumber("")).toBeNull();
294
+ });
295
+ });
296
+
297
+ describe("NativeResourceWorkspace when only the viewer's roles change", () => {
298
+ const isEditor = (v?: Viewer) => ((v?.roles as { teamRoles?: readonly string[] } | undefined)?.teamRoles ?? []).includes("editor");
299
+ const guarded = defineWorkspace(
300
+ defineView(brands, {
301
+ can: { update: (_b, v) => (isEditor(v) ? true : "Only editors change brands.") },
302
+ actions: [{ name: "publish", label: "Publish", can: (_b, v) => (isEditor(v) ? true : "Only editors publish.") }],
303
+ }),
304
+ { sections: [{ id: "settings", label: "Settings", settings: ["name"] }] },
305
+ );
306
+
307
+ // ViewerScope keeps the same viewer's screen mounted when the roles change, so the menu's action
308
+ // guards and the settings' update guard must be asked again with the new viewer.
309
+ it("asks the action and settings guards again, without remounting", async () => {
310
+ const sheet = vi.spyOn(ActionSheetIOS, "showActionSheetWithOptions").mockImplementation(() => {});
311
+ let mounts = 0;
312
+ function Mounts() {
313
+ useState(() => (mounts += 1));
314
+ return null;
315
+ }
316
+ const Base = wrap(provider());
317
+ const at = (roles?: { teamRoles: string[] }) => (
318
+ <Base>
319
+ <ViewerScope viewer="ann" roles={roles as never}>
320
+ <Mounts />
321
+ <NativeResourceWorkspaceMenu workspace={guarded} row={brand} />
322
+ <NativeResourceWorkspace workspace={guarded} row={brand} />
323
+ </ViewerScope>
324
+ </Base>
325
+ );
326
+ const menu = () => {
327
+ fireEvent.click(screen.getByTestId("native-resource-workspace-menu"));
328
+ return sheet.mock.calls.at(-1)![0].options;
329
+ };
330
+ const locked = () => screen.queryByTestId("native-resource-workspace-settings-locked")?.textContent ?? null;
331
+ const name = () => screen.getByTestId("native-resource-workspace-settings-name-input") as HTMLInputElement;
332
+ const save = () => screen.queryByTestId("native-resource-workspace-settings-save");
333
+
334
+ // Roles not known yet: the action is refused with its reason, the settings are read-only.
335
+ const { rerender } = render(at(undefined));
336
+ expect(menu()).toEqual(["Publish (Only editors publish.)", "Cancel"]);
337
+ expect(locked()).toContain("Only editors change brands.");
338
+ expect(name().disabled).toBe(true);
339
+ expect(save()).toBeNull();
340
+
341
+ // Roles arrive (undefined → editor): the same mounted screen allows both.
342
+ rerender(at({ teamRoles: ["editor"] }));
343
+ await waitFor(() => expect(locked()).toBeNull());
344
+ expect(menu()).toEqual(["Publish", "Cancel"]);
345
+ expect(name().disabled).toBe(false);
346
+ expect(save()).toBeTruthy();
347
+
348
+ // Roles change (editor → reader): refused and read-only again, still the same mount.
349
+ rerender(at({ teamRoles: ["reader"] }));
350
+ await waitFor(() => expect(locked()).toContain("Only editors change brands."));
351
+ expect(menu()).toEqual(["Publish (Only editors publish.)", "Cancel"]);
352
+ expect(name().disabled).toBe(true);
353
+ expect(save()).toBeNull();
354
+ expect(mounts).toBe(1);
355
+ });
356
+ });
@@ -0,0 +1,259 @@
1
+ // How a view's display hints draw on native. The same shape as genesis-ui's web renderers
2
+ // (`DisplayRenderers`, `DisplayRenderersProvider`, `useDisplayCell`): a view says
3
+ // `status: { display: "badge" }` and never imports a component, and an app replaces any hint with
4
+ // DisplayRenderersProvider. Links and images go through core's `isSafeUrl`; a calendar day is
5
+ // formatted from its parts, never `new Date(day)`. Rows show only `summary(row)`; these draw the
6
+ // peek and read-only form values.
7
+
8
+ import { createContext, useContext, useMemo, type ReactNode } from "react";
9
+ import { Linking, Text } from "react-native";
10
+ import { titleCase } from "@marktiderman/genesis-core";
11
+ import { isTimeZone, personTimeZone, wallClock } from "@marktiderman/genesis-core/dates";
12
+ import { useViewer } from "@marktiderman/genesis-core/hooks";
13
+ import { isSafeUrl } from "@marktiderman/genesis-core/urls";
14
+ import type { DisplayHint, ResolvedColumn, ViewTone } from "@marktiderman/genesis-core/resource-view";
15
+ import { NativeBadge } from "../../components/badge";
16
+ import { NativeImage } from "../../components/image";
17
+ import { NativeText } from "../../components/text";
18
+ import { defaultNativeResourceViewMessages, type NativeResourceViewMessages } from "./messages";
19
+
20
+ /** The clocks a timestamp can be read on: the viewer's and the practice's (IANA names). */
21
+ export interface DisplayTimeZones {
22
+ viewer: string;
23
+ practice: string;
24
+ }
25
+
26
+ /** What a renderer gets besides the value (as on the web, with native's messages and clocks). */
27
+ export interface DisplayContext {
28
+ row: Record<string, unknown>;
29
+ column: ResolvedColumn<Record<string, unknown>>;
30
+ messages: NativeResourceViewMessages;
31
+ zones: DisplayTimeZones;
32
+ }
33
+
34
+ export type DisplayRenderer = (value: unknown, context: DisplayContext) => ReactNode;
35
+ export type DisplayRenderers = Readonly<Record<DisplayHint, DisplayRenderer>>;
36
+
37
+ export const isEmptyValue = (value: unknown) => value === null || value === undefined || value === "";
38
+
39
+ const NUMBER = new Intl.NumberFormat();
40
+ const DECIMAL = new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
41
+ const PERCENT = new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 1 });
42
+ const DAY = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
43
+
44
+ function numeric(value: unknown, format: Intl.NumberFormat): string {
45
+ const n = typeof value === "number" ? value : Number(value);
46
+ return Number.isFinite(n) ? format.format(n) : String(value);
47
+ }
48
+
49
+ const DAY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
50
+
51
+ /** A `YYYY-MM-DD` day as a local Date at midnight, from its parts (the picker's value). Null when it isn't a day. */
52
+ export function dayToDate(value: unknown): Date | null {
53
+ const day = typeof value === "string" ? DAY_PATTERN.exec(value) : null;
54
+ if (!day) return null;
55
+ return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]));
56
+ }
57
+
58
+ /** A picked Date back to the `YYYY-MM-DD` day it shows, from its local parts (never `toISOString`). */
59
+ export function dateToDay(date: Date): string {
60
+ const pad = (n: number) => String(n).padStart(2, "0");
61
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
62
+ }
63
+
64
+ /** A calendar day, the same day on every clock. */
65
+ export function formatDay(value: unknown): string {
66
+ const date = dayToDate(value);
67
+ return date ? DAY.format(date) : String(value);
68
+ }
69
+
70
+ /** A column's clock: "viewer" (the default) and "practice" from `zones`, else a valid IANA name. */
71
+ export function resolveZone(zone: string | undefined, zones: DisplayTimeZones): string {
72
+ if (!zone || zone === "viewer") return zones.viewer;
73
+ if (zone === "practice") return zones.practice;
74
+ return isTimeZone(zone) ? zone : zones.viewer;
75
+ }
76
+
77
+ // The wall clock's parts are drawn as UTC, so one formatter serves every zone.
78
+ const WALL = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
79
+
80
+ /** A timestamp as the clock on the wall in `zone` shows it (core's `wallClock`), not the device's. */
81
+ export function formatInstant(value: unknown, zone: string): string {
82
+ const at = new Date(String(value));
83
+ if (Number.isNaN(at.getTime()) || !isTimeZone(zone)) return String(value);
84
+ const wall = wallClock(zone, at);
85
+ return WALL.format(new Date(Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second)));
86
+ }
87
+
88
+ /** A link a row may open: http(s), mailto or tel that passes `isSafeUrl`. Root-relative paths mean nothing on a phone. */
89
+ export function openableUrl(value: unknown): string | null {
90
+ if (!isSafeUrl(value)) return null;
91
+ const url = value.trim();
92
+ return /^(https?:|mailto:|tel:)/i.test(url) ? url : null;
93
+ }
94
+
95
+ /**
96
+ * One value as plain text, for the places that take a string (a row's subtitle, a section title,
97
+ * a read-only form row). Renderers use the same words.
98
+ */
99
+ export function displayText(
100
+ hint: DisplayHint,
101
+ value: unknown,
102
+ messages: NativeResourceViewMessages,
103
+ /** The resolved IANA zone a timestamp is read on (`resolveZone`). Default: the device's. */
104
+ timeZone: string = personTimeZone(),
105
+ ): string {
106
+ if (isEmptyValue(value)) return messages.common.empty;
107
+ switch (hint) {
108
+ case "number":
109
+ return numeric(value, NUMBER);
110
+ case "currency":
111
+ return numeric(value, DECIMAL);
112
+ case "percent":
113
+ return numeric(value, PERCENT);
114
+ case "boolean":
115
+ return value === true || value === "true" ? messages.common.yes : messages.common.no;
116
+ case "badge":
117
+ return titleCase(String(value));
118
+ case "date":
119
+ return formatDay(value);
120
+ case "datetime":
121
+ return formatInstant(value, timeZone);
122
+ case "url": {
123
+ const url = openableUrl(value);
124
+ return url ? url.replace(/^https?:\/\//i, "") : String(value);
125
+ }
126
+ case "json":
127
+ return typeof value === "string" ? value : JSON.stringify(value);
128
+ default:
129
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
130
+ }
131
+ }
132
+
133
+ const BADGE_VARIANT: Record<ViewTone, "success" | "warning" | "destructive" | "info" | "muted"> = {
134
+ success: "success",
135
+ warning: "warning",
136
+ danger: "destructive",
137
+ info: "info",
138
+ muted: "muted",
139
+ };
140
+
141
+ /** A chip's tone as a NativeBadge variant. */
142
+ export function badgeVariant(tone: ViewTone | undefined) {
143
+ return BADGE_VARIANT[tone ?? "muted"];
144
+ }
145
+
146
+ function LinkText({ url, label }: { url: string; label: string }) {
147
+ return (
148
+ <Text
149
+ accessibilityRole="link"
150
+ className="text-base text-primary underline"
151
+ onPress={() => void Linking.openURL(url)}
152
+ >
153
+ {label}
154
+ </Text>
155
+ );
156
+ }
157
+
158
+ const text = (hint: DisplayHint): DisplayRenderer => (value, { messages, column, zones }) => (
159
+ <NativeText preset="body">{displayText(hint, value, messages, resolveZone(column.timeZone, zones))}</NativeText>
160
+ );
161
+
162
+ /** Genesis's native renderers. Every one shows text it can't draw, never a broken row. */
163
+ export const nativeDisplayRenderers: DisplayRenderers = {
164
+ text: text("text"),
165
+ longText: (value) => (
166
+ <NativeText preset="body" numberOfLines={3}>
167
+ {String(value)}
168
+ </NativeText>
169
+ ),
170
+ number: text("number"),
171
+ currency: text("currency"),
172
+ percent: text("percent"),
173
+ boolean: text("boolean"),
174
+ badge: (value, { column }) => (
175
+ <NativeBadge variant={badgeVariant(column.tones?.[String(value)])}>{titleCase(String(value))}</NativeBadge>
176
+ ),
177
+ date: text("date"),
178
+ datetime: text("datetime"),
179
+ // The linked row's id until relation labels arrive (batched per page, never per row).
180
+ relation: text("relation"),
181
+ url: (value, { messages }) => {
182
+ const url = openableUrl(value);
183
+ return url && /^https?:/i.test(url) ? (
184
+ <LinkText url={url} label={displayText("url", value, messages)} />
185
+ ) : (
186
+ <NativeText preset="body">{String(value)}</NativeText>
187
+ );
188
+ },
189
+ email: (value) => {
190
+ const address = String(value).trim();
191
+ // A plain address only: no `?subject=` or `&body=` riding along in the mailto link.
192
+ const url = /^[^\s@?&#/]+@[^\s@?&#/]+$/.test(address) ? openableUrl(`mailto:${address}`) : null;
193
+ return url ? <LinkText url={url} label={address} /> : <NativeText preset="body">{address}</NativeText>;
194
+ },
195
+ image: (value) => {
196
+ const url = openableUrl(value);
197
+ return url && /^https?:/i.test(url) ? (
198
+ <NativeImage src={url} width={64} height={64} className="rounded-md" />
199
+ ) : (
200
+ <NativeText preset="body">{String(value)}</NativeText>
201
+ );
202
+ },
203
+ json: (value) => (
204
+ <NativeText preset="caption" numberOfLines={2}>
205
+ {typeof value === "string" ? value : JSON.stringify(value)}
206
+ </NativeText>
207
+ ),
208
+ };
209
+
210
+ const DisplayRenderersContext = createContext<DisplayRenderers>(nativeDisplayRenderers);
211
+ const MessagesContext = createContext<NativeResourceViewMessages>(defaultNativeResourceViewMessages);
212
+ const TimeZonesContext = createContext<DisplayTimeZones | null>(null);
213
+
214
+ /** The clocks timestamps are read on below. NativeResourceView sets it from ViewerScope. */
215
+ export const DisplayTimeZonesProvider = TimeZonesContext.Provider;
216
+
217
+ /** The clocks for timestamps: the nearest provider's, else the device's for both. */
218
+ export function useDisplayTimeZones(): DisplayTimeZones {
219
+ const zones = useContext(TimeZonesContext);
220
+ return useMemo(() => zones ?? { viewer: personTimeZone(), practice: personTimeZone() }, [zones]);
221
+ }
222
+
223
+ /** Replace some of the renderers for everything below (nested providers build on each other). */
224
+ export function DisplayRenderersProvider({
225
+ renderers,
226
+ children,
227
+ }: {
228
+ renderers: Partial<Record<DisplayHint, DisplayRenderer>>;
229
+ children: ReactNode;
230
+ }) {
231
+ const parent = useContext(DisplayRenderersContext);
232
+ const value = useMemo(() => ({ ...parent, ...renderers }), [parent, renderers]);
233
+ return <DisplayRenderersContext.Provider value={value}>{children}</DisplayRenderersContext.Provider>;
234
+ }
235
+
236
+ /** The words NativeResourceView shows, for everything below. Pass a stable object. */
237
+ export const NativeResourceViewMessagesProvider = MessagesContext.Provider;
238
+
239
+ export function useNativeResourceViewMessages(): NativeResourceViewMessages {
240
+ return useContext(MessagesContext);
241
+ }
242
+
243
+ /** Draw one value: the empty mark for no value or a value the row (or viewer) hides (`when`), else its hint's renderer. */
244
+ export function useDisplayCell(): (column: ResolvedColumn<Record<string, unknown>>, row: Record<string, unknown>) => ReactNode {
245
+ const renderers = useContext(DisplayRenderersContext);
246
+ const messages = useNativeResourceViewMessages();
247
+ const zones = useDisplayTimeZones();
248
+ // `when` reads the viewer too: a new viewer or new roles redraws the cells.
249
+ const viewer = useViewer();
250
+ return useMemo(
251
+ () => (column, row) => {
252
+ if (column.when && !column.when(row, viewer)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
253
+ const value = column.value(row);
254
+ if (isEmptyValue(value)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
255
+ return renderers[column.display](value, { row, column, messages, zones });
256
+ },
257
+ [renderers, messages, zones, viewer],
258
+ );
259
+ }
@@ -0,0 +1,61 @@
1
+ // NativeResourceView: ResourceView's native renderer (docs/RESOURCE-VIEW.md, "Native").
2
+ export { NativeResourceView, type NativeResourceViewProps, type NativeResourceSwipeableProps } from "./NativeResourceView";
3
+ export {
4
+ useNativeResourceView,
5
+ SEARCH_DEBOUNCE_MS,
6
+ screenValues,
7
+ serverSort,
8
+ DEFAULT_MAX_PAGES,
9
+ type NativeResourceViewOptions,
10
+ type SaveResult,
11
+ type UseNativeResourceViewReturn,
12
+ } from "./use-native-resource-view";
13
+ export { NativeResourceFormSheet, type NativeResourceFormSheetProps } from "./NativeResourceFormSheet";
14
+ export {
15
+ DisplayRenderersProvider,
16
+ DisplayTimeZonesProvider,
17
+ useDisplayTimeZones,
18
+ resolveZone,
19
+ formatInstant,
20
+ NativeResourceViewMessagesProvider,
21
+ nativeDisplayRenderers,
22
+ useDisplayCell,
23
+ useNativeResourceViewMessages,
24
+ displayText,
25
+ dayToDate,
26
+ dateToDay,
27
+ formatDay,
28
+ openableUrl,
29
+ type DisplayContext,
30
+ type DisplayTimeZones,
31
+ type DisplayRenderer,
32
+ type DisplayRenderers,
33
+ } from "./display";
34
+ export {
35
+ allowed,
36
+ formFieldsFor,
37
+ rowItem,
38
+ sectionsFor,
39
+ swipeActionsFor,
40
+ validateValues,
41
+ writableValues,
42
+ type AnyResourceView,
43
+ type NativeFormField,
44
+ type NativeFormFieldKind,
45
+ type NativeResourceRowItem,
46
+ type NativeResourceScreenCan,
47
+ type NativeResourceSection,
48
+ type NativeResourceSwipeAction,
49
+ } from "./mapping";
50
+ export { defaultNativeResourceViewMessages, type NativeResourceViewMessages } from "./messages";
51
+ export {
52
+ NativeResourceWorkspace,
53
+ NativeResourceWorkspaceMenu,
54
+ getNativeResourceWorkspaceStackOptions,
55
+ defaultNativeResourceWorkspaceMessages,
56
+ SEGMENTED_SECTIONS_MAX,
57
+ parseSettingNumber,
58
+ type NativeResourceWorkspaceProps,
59
+ type NativeResourceWorkspaceHeaderProps,
60
+ type NativeResourceWorkspaceMessages,
61
+ } from "./NativeResourceWorkspace";