@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,333 @@
1
+ // A view mapped onto native list pieces, with no React: rows for NativeListItem, sections for
2
+ // SectionList, guards as swipe actions, and the form sheet's fields. NativeResourceView and
3
+ // useNativeResourceView draw from these, and the tests check them directly.
4
+
5
+ import type { DataRow } from "@marktiderman/genesis-core";
6
+ import type {
7
+ Allowed,
8
+ DisplayHint,
9
+ ResourceView,
10
+ RowPicture,
11
+ RowSummary,
12
+ Viewer,
13
+ } from "@marktiderman/genesis-core/resource-view";
14
+ import { rowPicture } from "@marktiderman/genesis-core/resource-view";
15
+ import type { InboxSwipeAction } from "../../layouts/inbox-page";
16
+ import { displayText, isEmptyValue } from "./display";
17
+ import { fill, type NativeResourceViewMessages } from "./messages";
18
+
19
+ type Row = Record<string, unknown>;
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract; the row is what matters here
21
+ export type AnyResourceView<T extends Row = Row> = ResourceView<any, T & DataRow>;
22
+
23
+ /** What one row shows in a NativeListItem. */
24
+ export interface NativeResourceRowItem {
25
+ id: string;
26
+ title: string;
27
+ /** `summary(row).subtitle`, the only subtitle: never a raw column. */
28
+ subtitle?: string;
29
+ chips: NonNullable<RowSummary["chips"]>;
30
+ /**
31
+ * `rowPicture(summary)`: an image (passed `isSafeUrl`, with initials to fall back to), initials,
32
+ * or null. On a phone only an http(s) image can load, so any other safe src (a root-relative
33
+ * path) draws its initials instead.
34
+ */
35
+ picture: RowPicture | null;
36
+ }
37
+
38
+ function nativePicture(summary: RowSummary): RowPicture | null {
39
+ const picture = rowPicture(summary);
40
+ if (picture?.kind === "image" && !/^https?:/i.test(picture.src)) {
41
+ return picture.fallback ? { kind: "initials", text: picture.fallback } : null;
42
+ }
43
+ return picture;
44
+ }
45
+
46
+ /**
47
+ * A row as NativeListItem draws it: `view.summary(row)`'s title, subtitle and chips, and nothing
48
+ * else. A view that wants a second line says so in its summary.
49
+ */
50
+ export function rowItem<T extends Row>(view: AnyResourceView<T>, row: T): NativeResourceRowItem {
51
+ const summary = view.summary(row as T & DataRow);
52
+ return {
53
+ id: String(row.id ?? summary.title),
54
+ title: summary.title,
55
+ ...(summary.subtitle ? { subtitle: summary.subtitle } : {}),
56
+ chips: summary.chips ?? [],
57
+ picture: nativePicture(summary),
58
+ };
59
+ }
60
+
61
+ export interface NativeResourceSection<T> {
62
+ key: string;
63
+ /** Empty for the one section of an ungrouped view (no header is drawn). */
64
+ title: string;
65
+ data: T[];
66
+ }
67
+
68
+ /**
69
+ * Rows in sections by `definition.groupBy`, in the order each group first appears (the server's
70
+ * sort, so paging never reorders what's on screen). Without `groupBy`, one untitled section.
71
+ */
72
+ export function sectionsFor<T extends Row>(
73
+ view: AnyResourceView<T>,
74
+ rows: readonly T[],
75
+ messages: NativeResourceViewMessages,
76
+ ): NativeResourceSection<T>[] {
77
+ const field = view.definition.groupBy as string | undefined;
78
+ if (!field) return rows.length ? [{ key: "", title: "", data: [...rows] }] : [];
79
+ const display = view.display(field);
80
+ const groups = new Map<string, NativeResourceSection<T>>();
81
+ for (const row of rows) {
82
+ const value = row[field];
83
+ const key = isEmptyValue(value) ? "\u0000" : String(value);
84
+ let group = groups.get(key);
85
+ if (!group) {
86
+ const title = isEmptyValue(value)
87
+ ? fill(messages.list.noGroup, { label: view.label(field).toLowerCase() })
88
+ : displayText(display, value, messages);
89
+ group = { key, title, data: [] };
90
+ groups.set(key, group);
91
+ }
92
+ group.data.push(row);
93
+ }
94
+ return [...groups.values()];
95
+ }
96
+
97
+ /** A row action: InboxPage's swipe action plus an icon name and, when a guard refuses it, why. */
98
+ export interface NativeResourceSwipeAction extends InboxSwipeAction {
99
+ /** An icon name from Genesis's set (`edit`, `trash`), mapped per platform. */
100
+ icon?: string;
101
+ /** Set when a guard refuses the action: pressing it explains instead of acting. */
102
+ reason?: string;
103
+ }
104
+
105
+ /** A screen's own rule. It only narrows: `false` hides the action, a sentence shows it refused. */
106
+ export type NativeResourceScreenCan<T> = (action: "create" | "update" | "delete", row?: T) => Allowed | boolean;
107
+
108
+ /**
109
+ * The effective right: the screen's rule AND the view's guard (never OR). The guard gets the
110
+ * viewer (`useViewer()`); without one it gets no one, so a guard that needs it refuses.
111
+ */
112
+ export function allowed<T extends Row>(
113
+ view: AnyResourceView<T>,
114
+ action: "create" | "update" | "delete",
115
+ row: T | undefined,
116
+ screen?: NativeResourceScreenCan<T>,
117
+ viewer?: Viewer,
118
+ ): Allowed | false {
119
+ const own = screen?.(action, row);
120
+ if (own === false) return false;
121
+ if (typeof own === "string") return own;
122
+ const guard = action === "create" ? view.can("create", viewer) : row ? view.can(action, row as T & DataRow, viewer) : true;
123
+ return guard;
124
+ }
125
+
126
+ export interface SwipeActionOptions<T> {
127
+ messages: NativeResourceViewMessages;
128
+ /** The provider moves deleted rows to a recycle bin (`capabilities(resource).softDelete`). */
129
+ softDelete: boolean;
130
+ /** The view has fields a writer may change when editing. */
131
+ editable: boolean;
132
+ screen?: NativeResourceScreenCan<T>;
133
+ /** Who is looking (`useViewer()`), for the view's guards. */
134
+ viewer?: Viewer;
135
+ onEdit: (row: T) => void;
136
+ onDelete: (row: T) => void;
137
+ /** A refused action was pressed: say why. */
138
+ onRefused: (label: string, reason: string) => void;
139
+ }
140
+
141
+ /**
142
+ * A row's swipe actions, from the view's guards. A refused action stays in the list with its
143
+ * reason, so the person learns why; one the screen turns off (`false`) is left out.
144
+ */
145
+ export function swipeActionsFor<T extends Row>(
146
+ view: AnyResourceView<T>,
147
+ row: T,
148
+ options: SwipeActionOptions<T>,
149
+ ): NativeResourceSwipeAction[] {
150
+ const { messages, softDelete, editable, screen, viewer, onEdit, onDelete, onRefused } = options;
151
+ const actions: NativeResourceSwipeAction[] = [];
152
+ const add = (id: string, label: string, icon: string, right: Allowed | false, run: () => void, destructive = false) => {
153
+ if (right === false) return;
154
+ const reason = right === true ? undefined : right;
155
+ actions.push({
156
+ id,
157
+ label,
158
+ icon,
159
+ ...(destructive ? { destructive } : {}),
160
+ ...(reason ? { reason } : {}),
161
+ onPress: reason ? () => onRefused(label, reason) : run,
162
+ });
163
+ };
164
+ if (editable) add("edit", messages.common.edit, "edit", allowed(view, "update", row, screen, viewer), () => onEdit(row));
165
+ add(
166
+ "delete",
167
+ softDelete ? messages.bin.action : messages.delete.action,
168
+ "trash",
169
+ allowed(view, "delete", row, screen, viewer),
170
+ () => onDelete(row),
171
+ true,
172
+ );
173
+ return actions;
174
+ }
175
+
176
+ /** How a form field is drawn. */
177
+ export type NativeFormFieldKind =
178
+ | "text"
179
+ | "email"
180
+ | "url"
181
+ | "number"
182
+ | "textarea"
183
+ | "switch"
184
+ | "segmented"
185
+ | "select"
186
+ | "date"
187
+ | "datetime";
188
+
189
+ export interface NativeFormField {
190
+ key: string;
191
+ label: string;
192
+ kind: NativeFormFieldKind;
193
+ display: DisplayHint;
194
+ required: boolean;
195
+ /** Shown as text, never as an input, and never sent. */
196
+ readOnly: boolean;
197
+ max?: number;
198
+ options?: { value: string; label: string }[];
199
+ /** The heading it sits under; null for the form's first, untitled group. */
200
+ section: string | null;
201
+ sectionTitle: string | null;
202
+ visible?: (values: Readonly<Record<string, unknown>>) => boolean;
203
+ }
204
+
205
+ /** Choices that fit a segmented control; more go to a list. */
206
+ const SEGMENTED_MAX = 4;
207
+
208
+ function kindFor(display: DisplayHint, options: unknown[] | undefined): NativeFormFieldKind {
209
+ if (options) return options.length <= SEGMENTED_MAX ? "segmented" : "select";
210
+ switch (display) {
211
+ case "boolean":
212
+ return "switch";
213
+ case "date":
214
+ return "date";
215
+ case "datetime":
216
+ return "datetime";
217
+ case "number":
218
+ case "currency":
219
+ case "percent":
220
+ return "number";
221
+ case "longText":
222
+ return "textarea";
223
+ case "email":
224
+ return "email";
225
+ case "url":
226
+ case "image":
227
+ return "url";
228
+ default:
229
+ return "text";
230
+ }
231
+ }
232
+
233
+ /**
234
+ * The form sheet's fields: `view.form(mode)` (which already leaves out JSON, lists, links, scope,
235
+ * sensitive and unreadable fields and server-filled keys), each marked read-only unless
236
+ * `view.writable(mode)` lists it. Copied, never mutated: core caches and freezes `form()`. A create leaves read-only fields out (there is nothing to show yet); an edit shows
237
+ * them as text.
238
+ */
239
+ export function formFieldsFor<T extends Row>(view: AnyResourceView<T>, mode: "create" | "edit"): NativeFormField[] {
240
+ const writable = new Set(view.writable(mode));
241
+ return view
242
+ .form(mode)
243
+ // JSON and lists need editors of their own; a plain input would send them back as text (as the web).
244
+ .filter((f) => f.display !== "json" && !f.field.array)
245
+ .filter((f) => mode === "edit" || writable.has(f.field.name))
246
+ .map((f) => {
247
+ const options = f.field.enumValues?.map((value) => ({ value, label: displayText("badge", value, EMPTY_WORDS) }));
248
+ const readOnly = !writable.has(f.field.name);
249
+ return {
250
+ key: f.field.name,
251
+ label: f.label,
252
+ kind: kindFor(f.display, options),
253
+ display: f.display,
254
+ required: !readOnly && f.required,
255
+ readOnly,
256
+ ...(f.max !== undefined ? { max: f.max } : {}),
257
+ ...(options ? { options } : {}),
258
+ section: f.section,
259
+ sectionTitle: f.sectionTitle,
260
+ ...(f.visible ? { visible: f.visible } : {}),
261
+ };
262
+ });
263
+ }
264
+
265
+ // Only `badge` is formatted here, which reads no messages.
266
+ const EMPTY_WORDS = { common: { empty: "", yes: "", no: "" } } as NativeResourceViewMessages;
267
+
268
+ /** Fields shown for these values: a field whose `visible` says no is hidden, and isn't saved. */
269
+ export function shownFields(fields: readonly NativeFormField[], values: Readonly<Record<string, unknown>>): NativeFormField[] {
270
+ return fields.filter((f) => !f.visible || f.visible(values));
271
+ }
272
+
273
+ /**
274
+ * What a save sends: only the keys `view.writable(mode)` lists and the form shows. Read-only,
275
+ * generated, key and scope fields, and anything else the values carry (joined columns), never go.
276
+ * An edit passes `dirty`, the fields the person changed, so a save never rewrites the rest. A
277
+ * cleared optional value (an empty text, a cleared number or date) is sent as null.
278
+ */
279
+ export function writableValues<T extends Row>(
280
+ view: AnyResourceView<T>,
281
+ mode: "create" | "edit",
282
+ fields: readonly NativeFormField[],
283
+ values: Readonly<Record<string, unknown>>,
284
+ dirty?: ReadonlySet<string>,
285
+ ): Record<string, unknown> {
286
+ const writable = new Set(view.writable(mode));
287
+ const out: Record<string, unknown> = {};
288
+ for (const field of shownFields(fields, values)) {
289
+ if (field.readOnly || !writable.has(field.key)) continue;
290
+ if (dirty && !dirty.has(field.key)) continue;
291
+ const value = values[field.key];
292
+ out[field.key] = (value === "" || value === undefined) && !field.required ? null : value;
293
+ }
294
+ return out;
295
+ }
296
+
297
+ /** Field errors for a save: required fields with no value, and text over `max`. */
298
+ export function validateValues(
299
+ fields: readonly NativeFormField[],
300
+ values: Readonly<Record<string, unknown>>,
301
+ messages: NativeResourceViewMessages,
302
+ ): Record<string, string> {
303
+ const errors: Record<string, string> = {};
304
+ for (const field of shownFields(fields, values)) {
305
+ if (field.readOnly) continue;
306
+ const value = values[field.key];
307
+ if (field.required && field.kind !== "switch" && (isEmptyValue(value) || (typeof value === "string" && !value.trim()))) {
308
+ errors[field.key] = fill(messages.form.required, { label: field.label });
309
+ } else if (field.max !== undefined && typeof value === "string" && value.length > field.max) {
310
+ errors[field.key] = fill(messages.form.tooLong, { label: field.label, max: field.max });
311
+ }
312
+ }
313
+ return errors;
314
+ }
315
+
316
+ /**
317
+ * A refused write in plain words. A provider's `DataWriteError` (a zero-row update or delete it
318
+ * read back: forbidden, gone, a guard's message) already says it plainly; anything else gets the
319
+ * fallback sentence, never a raw driver message.
320
+ */
321
+ export function refusalMessage(error: unknown, fallback: string): string {
322
+ if (error instanceof Error && error.name === "DataWriteError" && error.message) return error.message;
323
+ return fallback;
324
+ }
325
+
326
+ /** Per-field messages a provider attached to a refused write (`DataWriteError.fields`). */
327
+ export function refusalFields(error: unknown): Record<string, string> {
328
+ if (error instanceof Error && error.name === "DataWriteError") {
329
+ const fields = (error as Error & { fields?: Record<string, string> }).fields;
330
+ if (fields) return { ...fields };
331
+ }
332
+ return {};
333
+ }
@@ -0,0 +1,121 @@
1
+ // The words NativeResourceView shows. `common` matches genesis-ui's `uiMessages.common`, so a
2
+ // renderer written for one platform reads the same keys on the other. `{name}`-style placeholders
3
+ // are filled with `fill`.
4
+
5
+ export interface NativeResourceViewMessages {
6
+ common: {
7
+ /** Shown for an empty value. */
8
+ empty: string;
9
+ yes: string;
10
+ no: string;
11
+ cancel: string;
12
+ save: string;
13
+ edit: string;
14
+ close: string;
15
+ /** "New {noun}". */
16
+ create: string;
17
+ /** "Edit {noun}". */
18
+ editTitle: string;
19
+ /** "Search {nounPlural}". */
20
+ search: string;
21
+ };
22
+ delete: {
23
+ /** The action when a delete removes the row for good. */
24
+ action: string;
25
+ /** `{name}`: the row's title. */
26
+ confirmTitle: string;
27
+ confirmBody: string;
28
+ };
29
+ bin: {
30
+ /** The action when the provider moves deleted rows to a recycle bin (`softDelete`). */
31
+ action: string;
32
+ confirmTitle: string;
33
+ confirmBody: string;
34
+ };
35
+ list: {
36
+ /** `{nounPlural}`. */
37
+ emptyTitle: string;
38
+ emptyBody: string;
39
+ noResultsTitle: string;
40
+ noResultsBody: string;
41
+ loadingMore: string;
42
+ /** `{nounPlural}`. */
43
+ loadFailed: string;
44
+ retry: string;
45
+ /** A section for rows with no value in the group field. `{label}`: the field. */
46
+ noGroup: string;
47
+ };
48
+ form: {
49
+ /** `{label}`. */
50
+ required: string;
51
+ /** `{label}`, `{max}`. */
52
+ tooLong: string;
53
+ /** `{noun}`. A save failed with no message of its own. */
54
+ saveFailed: string;
55
+ /** An empty day field's button. */
56
+ pickDate: string;
57
+ /** An empty date-and-time field's button. */
58
+ pickDateTime: string;
59
+ /** Empties an optional date. `{label}`. */
60
+ clear: string;
61
+ loading: string;
62
+ };
63
+ refusal: {
64
+ /** `{noun}`. A delete failed with no message of its own. */
65
+ deleteFailed: string;
66
+ dismiss: string;
67
+ };
68
+ }
69
+
70
+ export const defaultNativeResourceViewMessages: NativeResourceViewMessages = {
71
+ common: {
72
+ empty: "—",
73
+ yes: "Yes",
74
+ no: "No",
75
+ cancel: "Cancel",
76
+ save: "Save",
77
+ edit: "Edit",
78
+ close: "Close",
79
+ create: "New {noun}",
80
+ editTitle: "Edit {noun}",
81
+ search: "Search {nounPlural}",
82
+ },
83
+ delete: {
84
+ action: "Delete",
85
+ confirmTitle: "Delete “{name}”?",
86
+ confirmBody: "This can't be undone.",
87
+ },
88
+ bin: {
89
+ action: "Move to Bin",
90
+ confirmTitle: "Move “{name}” to the bin?",
91
+ confirmBody: "You can restore it from the bin.",
92
+ },
93
+ list: {
94
+ emptyTitle: "No {nounPlural} yet",
95
+ emptyBody: "When there are some, they show up here.",
96
+ noResultsTitle: "No results",
97
+ noResultsBody: "Try a different search.",
98
+ loadingMore: "Loading more",
99
+ loadFailed: "These {nounPlural} couldn't be loaded.",
100
+ retry: "Try again",
101
+ noGroup: "No {label}",
102
+ },
103
+ form: {
104
+ required: "{label} is required.",
105
+ tooLong: "{label} can be at most {max} characters.",
106
+ saveFailed: "This {noun} couldn't be saved. Try again.",
107
+ pickDate: "Add a date",
108
+ pickDateTime: "Add a date and time",
109
+ clear: "Clear {label}",
110
+ loading: "Loading",
111
+ },
112
+ refusal: {
113
+ deleteFailed: "This {noun} couldn't be deleted. Try again.",
114
+ dismiss: "Dismiss",
115
+ },
116
+ };
117
+
118
+ /** Fill `{name}` placeholders. A placeholder with no value is left as it is. */
119
+ export function fill(template: string, values: Readonly<Record<string, string | number>>): string {
120
+ return template.replace(/\{(\w+)\}/g, (match, key: string) => (key in values ? String(values[key]) : match));
121
+ }