@marktiderman/genesis-ui-native 2.6.0 → 2.7.1

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 (30) hide show
  1. package/dist/{chunk-KZEIF4YI.js → chunk-7HWS2JGX.js} +3 -3
  2. package/dist/{chunk-KZEIF4YI.js.map → chunk-7HWS2JGX.js.map} +1 -1
  3. package/dist/{chunk-3S5XVER4.js → chunk-C6Q5ZAVT.js} +4 -3
  4. package/dist/chunk-C6Q5ZAVT.js.map +1 -0
  5. package/dist/{chunk-VMSIKSU2.js → chunk-ON7WP4T6.js} +4 -4
  6. package/dist/{chunk-VMSIKSU2.js.map → chunk-ON7WP4T6.js.map} +1 -1
  7. package/dist/{chunk-56QLEHHV.js → chunk-PO3MK6IY.js} +3 -3
  8. package/dist/{chunk-56QLEHHV.js.map → chunk-PO3MK6IY.js.map} +1 -1
  9. package/dist/{chunk-6JBNSW4D.js → chunk-SXCG2REG.js} +3 -3
  10. package/dist/{chunk-6JBNSW4D.js.map → chunk-SXCG2REG.js.map} +1 -1
  11. package/dist/components/index.d.ts +7 -2
  12. package/dist/components/index.js +3 -3
  13. package/dist/data/index.d.ts +122 -22
  14. package/dist/data/index.js +447 -31
  15. package/dist/data/index.js.map +1 -1
  16. package/dist/index.js +5 -5
  17. package/dist/layouts/index.js +3 -3
  18. package/package.json +2 -2
  19. package/src/components/__tests__/button-a11y.test.tsx +17 -0
  20. package/src/components/button.tsx +8 -2
  21. package/src/data/resource-view/NativeResourceFormSheet.tsx +4 -1
  22. package/src/data/resource-view/NativeResourceView.tsx +11 -3
  23. package/src/data/resource-view/NativeResourceWorkspace.tsx +657 -0
  24. package/src/data/resource-view/__tests__/native-resource-view.test.tsx +122 -1
  25. package/src/data/resource-view/__tests__/native-resource-workspace.test.tsx +356 -0
  26. package/src/data/resource-view/display.tsx +8 -5
  27. package/src/data/resource-view/index.ts +11 -0
  28. package/src/data/resource-view/mapping.ts +16 -10
  29. package/src/data/resource-view/use-native-resource-view.ts +7 -5
  30. package/dist/chunk-3S5XVER4.js.map +0 -1
@@ -31,15 +31,17 @@ vi.mock("@marktiderman/genesis-core/hooks", async (importOriginal) => {
31
31
 
32
32
  import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
33
33
  import { QueryClient } from "@tanstack/react-query";
34
- import type { ReactNode } from "react";
34
+ import { useState, type ReactNode } from "react";
35
35
  import { Alert, Linking } from "react-native";
36
36
  import { describe, expect, it, vi, beforeEach } from "vitest";
37
37
  import {
38
38
  DataWriteError,
39
39
  defineResource,
40
40
  GenesisProvider,
41
+ ViewerScope,
41
42
  type DataProvider,
42
43
  type ListParams,
44
+ type Viewer,
43
45
  } from "@marktiderman/genesis-core";
44
46
  import { defineView } from "@marktiderman/genesis-core/resource-view";
45
47
  import {
@@ -227,6 +229,20 @@ describe("sections", () => {
227
229
  ]);
228
230
  });
229
231
 
232
+ it("titles sections and form choices in the view's words", () => {
233
+ const labelled = defineView(brands, {
234
+ fields: { status: { labels: { active: "Published", draft: "In progress" } } },
235
+ form: ["name", "status"],
236
+ groupBy: "status",
237
+ });
238
+ expect(sectionsFor(labelled, ROWS, messages).map((s) => s.title)).toEqual(["Published", "Archived"]);
239
+ expect(formFieldsFor(labelled, "create").find((f) => f.key === "status")!.options).toEqual([
240
+ { value: "active", label: "Published" },
241
+ { value: "archived", label: "Archived" },
242
+ { value: "draft", label: "In progress" },
243
+ ]);
244
+ });
245
+
230
246
  it("is one untitled section without groupBy, and none for no rows", () => {
231
247
  expect(sectionsFor(summaryView, ROWS, messages).map((s) => s.title)).toEqual([""]);
232
248
  expect(sectionsFor(summaryView, [], messages)).toEqual([]);
@@ -283,6 +299,111 @@ describe("guards to swipe actions", () => {
283
299
  });
284
300
  });
285
301
 
302
+ describe("viewer-aware guards", () => {
303
+ const handlers = () => ({ onEdit: vi.fn(), onDelete: vi.fn(), onRefused: vi.fn() });
304
+ const isEditor = (v: Viewer) => ((v.roles as { teamRoles?: readonly string[] } | undefined)?.teamRoles ?? []).includes("editor");
305
+ const guarded = defineView(brands, {
306
+ form: ["name"],
307
+ can: {
308
+ create: (v) => (isEditor(v) ? true : "Only editors add brands."),
309
+ update: (_r, v) => (isEditor(v) ? true : "Only editors edit brands."),
310
+ },
311
+ });
312
+ const ann: Viewer = { id: "ann", scope: {}, roles: { teamRoles: ["editor"] } as never };
313
+ const bob: Viewer = { id: "bob", scope: {}, roles: { teamRoles: ["reader"] } as never };
314
+
315
+ it("refuses one viewer's swipe and allows another's; no viewer refuses", () => {
316
+ const edit = (viewer?: Viewer) =>
317
+ swipeActionsFor(guarded, ROWS[1]!, { messages, softDelete: false, editable: true, ...(viewer ? { viewer } : {}), ...handlers() }).find(
318
+ (a) => a.id === "edit",
319
+ )!.reason;
320
+ expect(edit(bob)).toBe("Only editors edit brands.");
321
+ expect(edit(ann)).toBeUndefined();
322
+ expect(edit()).toBe("Only editors edit brands.");
323
+ });
324
+
325
+ it("reads the viewer from ViewerScope for create, and fails closed without one", async () => {
326
+ const at = (viewer?: string, roles?: { teamRoles: string[] }) => {
327
+ const Base = wrap(provider());
328
+ return ({ children }: { children: ReactNode }) => (
329
+ <Base>{viewer ? <ViewerScope viewer={viewer} roles={roles as never}>{children}</ViewerScope> : children}</Base>
330
+ );
331
+ };
332
+ const editor = renderHook(() => useNativeResourceView(guarded), { wrapper: at("ann", { teamRoles: ["editor"] }) });
333
+ await waitFor(() => expect(editor.result.current.canCreate).toBe(true));
334
+ const reader = renderHook(() => useNativeResourceView(guarded), { wrapper: at("bob", { teamRoles: ["reader"] }) });
335
+ await waitFor(() => expect(reader.result.current.canCreate).toBe("Only editors add brands."));
336
+ const nobody = renderHook(() => useNativeResourceView(guarded), { wrapper: at() });
337
+ expect(nobody.result.current.canCreate).toBe("Only editors add brands.");
338
+ });
339
+ });
340
+
341
+ describe("viewer-aware guards when only the roles change", () => {
342
+ const isEditor = (v?: Viewer) => ((v?.roles as { teamRoles?: readonly string[] } | undefined)?.teamRoles ?? []).includes("editor");
343
+ const guarded = defineView(brands, {
344
+ fields: { secret: { label: "Secret", when: (_r, v) => isEditor(v) } },
345
+ columns: { default: ["name", "secret"] },
346
+ form: ["name"],
347
+ can: {
348
+ create: (v) => (isEditor(v) ? true : "Only editors add brands."),
349
+ update: (_r, v) => (isEditor(v) ? true : "Only editors edit brands."),
350
+ delete: (_r, v) => (isEditor(v) ? true : "Only editors delete brands."),
351
+ },
352
+ });
353
+
354
+ // ViewerScope keeps the same viewer's screen mounted when the roles change, so create, the row's
355
+ // actions and `when` must be asked again from the viewer in their memos' dependencies.
356
+ it("asks create, edit, delete and `when` again, without remounting", async () => {
357
+ let mounts = 0;
358
+ function Mounts() {
359
+ useState(() => (mounts += 1));
360
+ return null;
361
+ }
362
+ const Base = wrap(provider());
363
+ const at = (roles?: { teamRoles: string[] }) => (
364
+ <Base>
365
+ <ViewerScope viewer="ann" roles={roles as never}>
366
+ <Mounts />
367
+ <NativeResourceView view={guarded} />
368
+ </ViewerScope>
369
+ </Base>
370
+ );
371
+ const reason = (id: "edit" | "delete") => screen.queryByTestId(`native-resource-view-peek-${id}-reason`)?.textContent ?? null;
372
+ const peek = () => screen.getByTestId("native-resource-view-peek").textContent;
373
+ const pressCreate = () => fireEvent.click(screen.getByTestId("native-resource-view-create"));
374
+
375
+ // Roles not known yet: create explains instead of opening, edit and delete are refused, the value hidden.
376
+ const { rerender } = render(at(undefined));
377
+ fireEvent.click(await screen.findByTestId("native-resource-view-row-b2"));
378
+ await screen.findByTestId("native-resource-view-peek");
379
+ expect(peek()).toContain("Secret");
380
+ expect(peek()).not.toContain("shown");
381
+ expect(reason("edit")).toBe("Only editors edit brands.");
382
+ expect(reason("delete")).toBe("Only editors delete brands.");
383
+ pressCreate();
384
+ expect(alert).toHaveBeenLastCalledWith("New brand", "Only editors add brands.");
385
+
386
+ // Roles arrive (undefined → editor): the same mounted screen allows, and shows the value.
387
+ alert.mockClear();
388
+ rerender(at({ teamRoles: ["editor"] }));
389
+ await waitFor(() => expect(reason("edit")).toBeNull());
390
+ expect(reason("delete")).toBeNull();
391
+ expect(peek()).toContain("shown");
392
+ pressCreate();
393
+ expect(alert).not.toHaveBeenCalled();
394
+ fireEvent.click(await screen.findByTestId("native-resource-view-form-cancel"));
395
+
396
+ // Roles change (editor → reader): refused and hidden again, still the same mount.
397
+ rerender(at({ teamRoles: ["reader"] }));
398
+ await waitFor(() => expect(reason("edit")).toBe("Only editors edit brands."));
399
+ expect(reason("delete")).toBe("Only editors delete brands.");
400
+ await waitFor(() => expect(peek()).not.toContain("shown"));
401
+ pressCreate();
402
+ expect(alert).toHaveBeenLastCalledWith("New brand", "Only editors add brands.");
403
+ expect(mounts).toBe(1);
404
+ });
405
+ });
406
+
286
407
  describe("form sheet", () => {
287
408
  it("builds fields from form(mode); read-only columns are text in an edit and absent in a create", () => {
288
409
  const edit = formFieldsFor(plainView, "edit");
@@ -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
+ });
@@ -9,8 +9,9 @@ import { createContext, useContext, useMemo, type ReactNode } from "react";
9
9
  import { Linking, Text } from "react-native";
10
10
  import { titleCase } from "@marktiderman/genesis-core";
11
11
  import { isTimeZone, personTimeZone, wallClock } from "@marktiderman/genesis-core/dates";
12
+ import { useViewer } from "@marktiderman/genesis-core/hooks";
12
13
  import { isSafeUrl } from "@marktiderman/genesis-core/urls";
13
- import type { DisplayHint, ResolvedColumn, ViewTone } from "@marktiderman/genesis-core/resource-view";
14
+ import { valueText, type DisplayHint, type ResolvedColumn, type ViewTone } from "@marktiderman/genesis-core/resource-view";
14
15
  import { NativeBadge } from "../../components/badge";
15
16
  import { NativeImage } from "../../components/image";
16
17
  import { NativeText } from "../../components/text";
@@ -171,7 +172,7 @@ export const nativeDisplayRenderers: DisplayRenderers = {
171
172
  percent: text("percent"),
172
173
  boolean: text("boolean"),
173
174
  badge: (value, { column }) => (
174
- <NativeBadge variant={badgeVariant(column.tones?.[String(value)])}>{titleCase(String(value))}</NativeBadge>
175
+ <NativeBadge variant={badgeVariant(column.tones?.[String(value)])}>{valueText(column.labels, value)}</NativeBadge>
175
176
  ),
176
177
  date: text("date"),
177
178
  datetime: text("datetime"),
@@ -239,18 +240,20 @@ export function useNativeResourceViewMessages(): NativeResourceViewMessages {
239
240
  return useContext(MessagesContext);
240
241
  }
241
242
 
242
- /** Draw one value: the empty mark for no value or a value the row hides (`when`), else its hint's renderer. */
243
+ /** Draw one value: the empty mark for no value or a value the row (or viewer) hides (`when`), else its hint's renderer. */
243
244
  export function useDisplayCell(): (column: ResolvedColumn<Record<string, unknown>>, row: Record<string, unknown>) => ReactNode {
244
245
  const renderers = useContext(DisplayRenderersContext);
245
246
  const messages = useNativeResourceViewMessages();
246
247
  const zones = useDisplayTimeZones();
248
+ // `when` reads the viewer too: a new viewer or new roles redraws the cells.
249
+ const viewer = useViewer();
247
250
  return useMemo(
248
251
  () => (column, row) => {
249
- if (column.when && !column.when(row)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
252
+ if (column.when && !column.when(row, viewer)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
250
253
  const value = column.value(row);
251
254
  if (isEmptyValue(value)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
252
255
  return renderers[column.display](value, { row, column, messages, zones });
253
256
  },
254
- [renderers, messages, zones],
257
+ [renderers, messages, zones, viewer],
255
258
  );
256
259
  }
@@ -48,3 +48,14 @@ export {
48
48
  type NativeResourceSwipeAction,
49
49
  } from "./mapping";
50
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";
@@ -9,6 +9,7 @@ import type {
9
9
  ResourceView,
10
10
  RowPicture,
11
11
  RowSummary,
12
+ Viewer,
12
13
  } from "@marktiderman/genesis-core/resource-view";
13
14
  import { rowPicture } from "@marktiderman/genesis-core/resource-view";
14
15
  import type { InboxSwipeAction } from "../../layouts/inbox-page";
@@ -84,7 +85,9 @@ export function sectionsFor<T extends Row>(
84
85
  if (!group) {
85
86
  const title = isEmptyValue(value)
86
87
  ? fill(messages.list.noGroup, { label: view.label(field).toLowerCase() })
87
- : displayText(display, value, messages);
88
+ : display === "badge"
89
+ ? view.valueLabel(field, value)
90
+ : displayText(display, value, messages);
88
91
  group = { key, title, data: [] };
89
92
  groups.set(key, group);
90
93
  }
@@ -104,17 +107,21 @@ export interface NativeResourceSwipeAction extends InboxSwipeAction {
104
107
  /** A screen's own rule. It only narrows: `false` hides the action, a sentence shows it refused. */
105
108
  export type NativeResourceScreenCan<T> = (action: "create" | "update" | "delete", row?: T) => Allowed | boolean;
106
109
 
107
- /** The effective right: the screen's rule AND the view's guard (never OR). */
110
+ /**
111
+ * The effective right: the screen's rule AND the view's guard (never OR). The guard gets the
112
+ * viewer (`useViewer()`); without one it gets no one, so a guard that needs it refuses.
113
+ */
108
114
  export function allowed<T extends Row>(
109
115
  view: AnyResourceView<T>,
110
116
  action: "create" | "update" | "delete",
111
117
  row: T | undefined,
112
118
  screen?: NativeResourceScreenCan<T>,
119
+ viewer?: Viewer,
113
120
  ): Allowed | false {
114
121
  const own = screen?.(action, row);
115
122
  if (own === false) return false;
116
123
  if (typeof own === "string") return own;
117
- const guard = action === "create" ? view.can("create") : row ? view.can(action, row as T & DataRow) : true;
124
+ const guard = action === "create" ? view.can("create", viewer) : row ? view.can(action, row as T & DataRow, viewer) : true;
118
125
  return guard;
119
126
  }
120
127
 
@@ -125,6 +132,8 @@ export interface SwipeActionOptions<T> {
125
132
  /** The view has fields a writer may change when editing. */
126
133
  editable: boolean;
127
134
  screen?: NativeResourceScreenCan<T>;
135
+ /** Who is looking (`useViewer()`), for the view's guards. */
136
+ viewer?: Viewer;
128
137
  onEdit: (row: T) => void;
129
138
  onDelete: (row: T) => void;
130
139
  /** A refused action was pressed: say why. */
@@ -140,7 +149,7 @@ export function swipeActionsFor<T extends Row>(
140
149
  row: T,
141
150
  options: SwipeActionOptions<T>,
142
151
  ): NativeResourceSwipeAction[] {
143
- const { messages, softDelete, editable, screen, onEdit, onDelete, onRefused } = options;
152
+ const { messages, softDelete, editable, screen, viewer, onEdit, onDelete, onRefused } = options;
144
153
  const actions: NativeResourceSwipeAction[] = [];
145
154
  const add = (id: string, label: string, icon: string, right: Allowed | false, run: () => void, destructive = false) => {
146
155
  if (right === false) return;
@@ -154,12 +163,12 @@ export function swipeActionsFor<T extends Row>(
154
163
  onPress: reason ? () => onRefused(label, reason) : run,
155
164
  });
156
165
  };
157
- if (editable) add("edit", messages.common.edit, "edit", allowed(view, "update", row, screen), () => onEdit(row));
166
+ if (editable) add("edit", messages.common.edit, "edit", allowed(view, "update", row, screen, viewer), () => onEdit(row));
158
167
  add(
159
168
  "delete",
160
169
  softDelete ? messages.bin.action : messages.delete.action,
161
170
  "trash",
162
- allowed(view, "delete", row, screen),
171
+ allowed(view, "delete", row, screen, viewer),
163
172
  () => onDelete(row),
164
173
  true,
165
174
  );
@@ -237,7 +246,7 @@ export function formFieldsFor<T extends Row>(view: AnyResourceView<T>, mode: "cr
237
246
  .filter((f) => f.display !== "json" && !f.field.array)
238
247
  .filter((f) => mode === "edit" || writable.has(f.field.name))
239
248
  .map((f) => {
240
- const options = f.field.enumValues?.map((value) => ({ value, label: displayText("badge", value, EMPTY_WORDS) }));
249
+ const options = f.options?.map((o) => ({ value: o.value, label: o.label }));
241
250
  const readOnly = !writable.has(f.field.name);
242
251
  return {
243
252
  key: f.field.name,
@@ -255,9 +264,6 @@ export function formFieldsFor<T extends Row>(view: AnyResourceView<T>, mode: "cr
255
264
  });
256
265
  }
257
266
 
258
- // Only `badge` is formatted here, which reads no messages.
259
- const EMPTY_WORDS = { common: { empty: "", yes: "", no: "" } } as NativeResourceViewMessages;
260
-
261
267
  /** Fields shown for these values: a field whose `visible` says no is hidden, and isn't saved. */
262
268
  export function shownFields(fields: readonly NativeFormField[], values: Readonly<Record<string, unknown>>): NativeFormField[] {
263
269
  return fields.filter((f) => !f.visible || f.visible(values));