@marktiderman/genesis-ui-native 2.4.1 → 2.6.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 (47) hide show
  1. package/README.md +30 -0
  2. package/dist/{chunk-BPD5DCFP.js → chunk-3S5XVER4.js} +271 -6
  3. package/dist/chunk-3S5XVER4.js.map +1 -0
  4. package/dist/chunk-56QLEHHV.js +1231 -0
  5. package/dist/chunk-56QLEHHV.js.map +1 -0
  6. package/dist/chunk-6JBNSW4D.js +479 -0
  7. package/dist/chunk-6JBNSW4D.js.map +1 -0
  8. package/dist/{chunk-RARJGZA3.js → chunk-KZEIF4YI.js} +7 -741
  9. package/dist/chunk-KZEIF4YI.js.map +1 -0
  10. package/dist/{chunk-6TLBCRS6.js → chunk-VMSIKSU2.js} +13 -477
  11. package/dist/chunk-VMSIKSU2.js.map +1 -0
  12. package/dist/components/index.d.ts +29 -3
  13. package/dist/components/index.js +3 -4
  14. package/dist/data/index.d.ts +382 -4
  15. package/dist/data/index.js +1067 -19
  16. package/dist/data/index.js.map +1 -1
  17. package/dist/inbox-page-DZUR-PJ1.d.ts +199 -0
  18. package/dist/index.d.ts +3 -2
  19. package/dist/index.js +5 -5
  20. package/dist/layouts/index.d.ts +4 -186
  21. package/dist/layouts/index.js +3 -3
  22. package/package.json +2 -2
  23. package/src/components/__tests__/loading-state.test.tsx +41 -0
  24. package/src/components/image.tsx +5 -0
  25. package/src/components/index.ts +3 -0
  26. package/src/components/loading-state.tsx +92 -0
  27. package/src/data/NativeDetailPanel.tsx +8 -1
  28. package/src/data/index.ts +1 -0
  29. package/src/data/resource-view/NativeResourceFormSheet.tsx +305 -0
  30. package/src/data/resource-view/NativeResourceView.tsx +528 -0
  31. package/src/data/resource-view/__tests__/native-resource-view.test.tsx +870 -0
  32. package/src/data/resource-view/display.tsx +256 -0
  33. package/src/data/resource-view/index.ts +50 -0
  34. package/src/data/resource-view/mapping.ts +326 -0
  35. package/src/data/resource-view/messages.ts +121 -0
  36. package/src/data/resource-view/use-native-resource-view.ts +307 -0
  37. package/src/layouts/__tests__/inbox-page.test.tsx +2 -1
  38. package/src/layouts/__tests__/screen-container.test.tsx +27 -0
  39. package/src/layouts/inbox-page.tsx +4 -7
  40. package/src/layouts/screen-container.tsx +18 -1
  41. package/dist/chunk-6TLBCRS6.js.map +0 -1
  42. package/dist/chunk-BPD5DCFP.js.map +0 -1
  43. package/dist/chunk-EFXCJ5AN.js +0 -234
  44. package/dist/chunk-EFXCJ5AN.js.map +0 -1
  45. package/dist/chunk-FIITITXO.js +0 -492
  46. package/dist/chunk-FIITITXO.js.map +0 -1
  47. package/dist/chunk-RARJGZA3.js.map +0 -1
@@ -0,0 +1,92 @@
1
+ /**
2
+ * LoadingState — a centred spinner for a screen (or part of one) that is
3
+ * waiting: a redirect while the session loads, the first fetch of a page.
4
+ *
5
+ * Use it instead of a hand-rolled `<View><ActivityIndicator /></View>`: the
6
+ * spinner takes the theme tint, screen readers hear one "Loading" progress
7
+ * bar (or your `label`), and the full-screen form sits inside the safe area
8
+ * on the screen background. For content-shaped placeholders (a list about to
9
+ * appear) use `NativeSkeleton`; for known progress use `NativeProgress`.
10
+ *
11
+ * if (!session) return <NativeLoadingState />; // whole screen
12
+ * <NativeLoadingState fullScreen={false} label="Loading more" size="small" />
13
+ *
14
+ * `ScreenContainer loading` renders the inline form in place of its body.
15
+ *
16
+ * @stability Beta
17
+ */
18
+ import { ActivityIndicator, View, type ColorValue } from "react-native";
19
+ import { SafeAreaView } from "react-native-safe-area-context";
20
+ import { cn } from "../utils";
21
+ import { useThemeRoles } from "../hooks/use-theme-roles";
22
+ import { NativeText } from "./text";
23
+
24
+ export type NativeLoadingStateEdge = "top" | "bottom" | "left" | "right";
25
+
26
+ export interface NativeLoadingStateProps {
27
+ /** Text shown under the spinner. It is also what screen readers announce. */
28
+ label?: string;
29
+ /** What screen readers announce when no `label` is shown. Default `"Loading"`. */
30
+ accessibilityLabel?: string;
31
+ /** Spinner size. Default `"large"`. */
32
+ size?: "small" | "large";
33
+ /**
34
+ * `true` (default): fill the screen on the theme background, inside the
35
+ * safe area. `false`: a padded, centred block that fills its parent, for a
36
+ * screen body, a section or a list footer.
37
+ */
38
+ fullScreen?: boolean;
39
+ /** Safe-area edges when `fullScreen`. Default all four. */
40
+ safeAreaEdges?: NativeLoadingStateEdge[];
41
+ /** Spinner color. Defaults to the theme tint. */
42
+ color?: ColorValue;
43
+ className?: string;
44
+ /** testID on the root; the spinner is `${testID}-spinner`, the label `${testID}-label`. Default `"loading-state"`. */
45
+ testID?: string;
46
+ }
47
+
48
+ const ALL_EDGES: NativeLoadingStateEdge[] = ["top", "bottom", "left", "right"];
49
+
50
+ export function NativeLoadingState({
51
+ label,
52
+ accessibilityLabel,
53
+ size = "large",
54
+ fullScreen = true,
55
+ safeAreaEdges = ALL_EDGES,
56
+ color,
57
+ className,
58
+ testID = "loading-state",
59
+ }: NativeLoadingStateProps) {
60
+ const roles = useThemeRoles();
61
+ const spoken = label ?? accessibilityLabel ?? "Loading";
62
+
63
+ const content = (
64
+ <View
65
+ testID={fullScreen ? `${testID}-content` : testID}
66
+ className={cn("items-center justify-center gap-3 px-4 py-8", !fullScreen && "flex-grow", !fullScreen && className)}
67
+ accessible
68
+ accessibilityRole="progressbar"
69
+ accessibilityLabel={spoken}
70
+ accessibilityState={{ busy: true }}
71
+ >
72
+ <ActivityIndicator testID={`${testID}-spinner`} size={size} color={(color ?? roles.tint) as string} />
73
+ {label ? (
74
+ <NativeText testID={`${testID}-label`} preset="body-sm" className="text-muted-foreground text-center">
75
+ {label}
76
+ </NativeText>
77
+ ) : null}
78
+ </View>
79
+ );
80
+
81
+ if (!fullScreen) return content;
82
+
83
+ return (
84
+ <SafeAreaView
85
+ testID={testID}
86
+ edges={safeAreaEdges}
87
+ className={cn("flex-1 items-center justify-center bg-background", className)}
88
+ >
89
+ {content}
90
+ </SafeAreaView>
91
+ );
92
+ }
@@ -20,6 +20,10 @@ export interface NativeDetailPanelProps<T = Record<string, unknown>> {
20
20
  fields?: NativeDetailField<T>[];
21
21
  onEdit?: (item: T) => void;
22
22
  onDelete?: (item: T) => void;
23
+ /** The heading. Wins over `titleField` (e.g. a view's `summary(row).title`). */
24
+ title?: string;
25
+ /** Below the fields and actions (e.g. actions with their own wording, or the reason one is refused). */
26
+ footer?: ReactNode;
23
27
  children?: ReactNode;
24
28
  }
25
29
 
@@ -31,9 +35,11 @@ function NativeDetailPanel<T extends Record<string, unknown>>({
31
35
  fields,
32
36
  onEdit,
33
37
  onDelete,
38
+ title: titleProp,
39
+ footer,
34
40
  children,
35
41
  }: NativeDetailPanelProps<T>) {
36
- const title = titleField ? String(item[titleField] ?? "") : undefined;
42
+ const title = titleProp ?? (titleField ? String(item[titleField] ?? "") : undefined);
37
43
  const hasActions = onEdit != null || onDelete != null;
38
44
 
39
45
  // Escape hatch — caller provides full content
@@ -122,6 +128,7 @@ function NativeDetailPanel<T extends Record<string, unknown>>({
122
128
  ) : null}
123
129
  </View>
124
130
  ) : null}
131
+ {footer}
125
132
  </ScrollView>
126
133
  </SafeAreaView>
127
134
  );
package/src/data/index.ts CHANGED
@@ -7,3 +7,4 @@ export { NativeDetailPanel, type NativeDetailPanelProps, type NativeDetailField
7
7
  export { NativeResourceFormFieldRenderer, type NativeResourceFormFieldRendererProps } from "./NativeResourceFormField";
8
8
  export { NativeResourceForm, type NativeResourceFormProps } from "./NativeResourceForm";
9
9
  export { NativeResourcePage, type NativeResourcePageProps, type NativeCardFieldDef } from "./NativeResourcePage";
10
+ export * from "./resource-view";
@@ -0,0 +1,305 @@
1
+ // The form sheet a NativeResourceView opens for New and Edit: Cancel and Save in the bar, the
2
+ // view's sections as grouped sections, native date and time pickers, choices as a segmented
3
+ // control (up to four) or a list. Text, number, switch and list fields are drawn by
4
+ // NativeResourceFormFieldRenderer, the same as NativeResourceForm. Read-only fields are text, never
5
+ // inputs, and a save sends only the view's writable keys.
6
+
7
+ import { useEffect, useMemo, useRef, useState } from "react";
8
+ import { Pressable, Text, View } from "react-native";
9
+ import { Controller, useForm } from "react-hook-form";
10
+ import type { ResourceFormFieldDef } from "@marktiderman/genesis-core";
11
+ import { NativeButton } from "../../components/button";
12
+ import { NativeDatePicker, NativeTimePicker } from "../../components/date-time-picker";
13
+ import { NativeInlineAlert } from "../../components/inline-alert";
14
+ import { NativeLabel } from "../../components/label";
15
+ import { NativeLoadingState } from "../../components/loading-state";
16
+ import { NativeSegmentedControl } from "../../components/segmented-control";
17
+ import { NativeSheet, NativeSheetScrollView } from "../../components/sheet";
18
+ import { NativeText } from "../../components/text";
19
+ import { NavBarSaveButton } from "../../layouts/nav-bar";
20
+ import { NativeResourceFormFieldRenderer } from "../NativeResourceFormField";
21
+ import { dateToDay, dayToDate, displayText, resolveZone, useDisplayTimeZones, useNativeResourceViewMessages } from "./display";
22
+ import { fill } from "./messages";
23
+ import { shownFields, type NativeFormField } from "./mapping";
24
+ import type { SaveResult } from "./use-native-resource-view";
25
+
26
+ type Values = Record<string, unknown>;
27
+
28
+ export interface NativeResourceFormSheetProps {
29
+ open: boolean;
30
+ mode: "create" | "edit";
31
+ title: string;
32
+ fields: readonly NativeFormField[];
33
+ /** The row being edited (fetched by id), or a create's starting values. */
34
+ initial?: Values;
35
+ /** The record is still loading: a spinner instead of fields, and Save is off. */
36
+ loading?: boolean;
37
+ /** Which record the sheet holds; the form starts over when it (or `open`) changes. */
38
+ recordKey?: string;
39
+ onCancel: () => void;
40
+ /** Saves with the fields the person changed; the sheet closes on `{ ok: true }` and shows the refusal otherwise. */
41
+ onSave: (values: Values, dirty: ReadonlySet<string>) => Promise<SaveResult>;
42
+ testID?: string;
43
+ }
44
+
45
+ const FIELD_TYPE: Partial<Record<NativeFormField["kind"], ResourceFormFieldDef["type"]>> = {
46
+ text: "text",
47
+ email: "email",
48
+ url: "url",
49
+ number: "number",
50
+ textarea: "textarea",
51
+ switch: "switch",
52
+ select: "select",
53
+ };
54
+
55
+ /** Equal for the form's purposes: "" and null and undefined are all empty. */
56
+ function sameValue(a: unknown, b: unknown): boolean {
57
+ const empty = (v: unknown) => v === "" || v === null || v === undefined;
58
+ if (empty(a) && empty(b)) return true;
59
+ return a === b || JSON.stringify(a) === JSON.stringify(b);
60
+ }
61
+
62
+ function startValues(fields: readonly NativeFormField[], initial: Values | undefined): Values {
63
+ const values: Values = {};
64
+ for (const field of fields) {
65
+ const value = initial?.[field.key];
66
+ values[field.key] = value ?? (field.kind === "switch" ? false : "");
67
+ }
68
+ return values;
69
+ }
70
+
71
+ export function NativeResourceFormSheet({
72
+ open,
73
+ mode,
74
+ title,
75
+ fields,
76
+ initial,
77
+ loading = false,
78
+ recordKey,
79
+ onCancel,
80
+ onSave,
81
+ testID = "native-resource-form",
82
+ }: NativeResourceFormSheetProps) {
83
+ const messages = useNativeResourceViewMessages();
84
+ const defaults = useMemo(() => startValues(fields, initial), [fields, initial]);
85
+ const form = useForm<Values>({ defaultValues: defaults });
86
+ const [saving, setSaving] = useState(false);
87
+ const [refusal, setRefusal] = useState<string | null>(null);
88
+
89
+ // Opened, another record, or the record arrived: start from its values. Not on every refetch,
90
+ // which would wipe what the person typed.
91
+ const latest = useRef(defaults);
92
+ latest.current = defaults;
93
+ // What the form started from, snapshotted at that reset: a later refetch moves `defaults` (someone
94
+ // else's change), but "changed" means changed by this person since the sheet opened.
95
+ const start = useRef(defaults);
96
+ useEffect(() => {
97
+ if (open && !loading) {
98
+ start.current = latest.current;
99
+ form.reset(start.current);
100
+ setRefusal(null);
101
+ }
102
+ }, [open, loading, recordKey, form]);
103
+
104
+ const values = form.watch();
105
+ const sections = useMemo(() => {
106
+ const out: { key: string; title: string | null; fields: NativeFormField[] }[] = [];
107
+ for (const field of shownFields(fields, values)) {
108
+ const last = out[out.length - 1];
109
+ if (last && last.key === (field.section ?? "")) last.fields.push(field);
110
+ else out.push({ key: field.section ?? "", title: field.sectionTitle, fields: [field] });
111
+ }
112
+ return out;
113
+ }, [fields, values]);
114
+
115
+ const submit = async () => {
116
+ setSaving(true);
117
+ setRefusal(null);
118
+ form.clearErrors();
119
+ try {
120
+ // Changed against what the sheet started from (as react-hook-form's dirty fields, without
121
+ // depending on which parts of formState were read during render).
122
+ const now = form.getValues();
123
+ const from = start.current;
124
+ const dirty = new Set(fields.map((f) => f.key).filter((key) => !sameValue(now[key], from[key])));
125
+ const result = await onSave(now, dirty);
126
+ if (result.ok) return;
127
+ for (const [key, message] of Object.entries(result.fields)) form.setError(key, { type: "server", message });
128
+ if (result.message) setRefusal(result.message);
129
+ } finally {
130
+ setSaving(false);
131
+ }
132
+ };
133
+
134
+ return (
135
+ <NativeSheet open={open} onOpenChange={(next) => (next ? undefined : onCancel())} testID={testID}>
136
+ <View
137
+ testID={`${testID}-bar`}
138
+ style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: 8, paddingVertical: 4 }}
139
+ >
140
+ <Pressable
141
+ testID={`${testID}-cancel`}
142
+ accessibilityRole="button"
143
+ accessibilityLabel={messages.common.cancel}
144
+ onPress={onCancel}
145
+ hitSlop={8}
146
+ className="min-h-[44px] justify-center px-3"
147
+ >
148
+ <Text className="text-base text-primary">{messages.common.cancel}</Text>
149
+ </Pressable>
150
+ <NativeText preset="body" accessibilityRole="header" className="font-semibold" numberOfLines={1}>
151
+ {title}
152
+ </NativeText>
153
+ <NavBarSaveButton
154
+ testID={`${testID}-save`}
155
+ label={messages.common.save}
156
+ loading={saving}
157
+ disabled={loading}
158
+ onPress={() => void submit()}
159
+ />
160
+ </View>
161
+ <NativeSheetScrollView contentContainerStyle={{ padding: 16, gap: 20 }} keyboardShouldPersistTaps="handled">
162
+ {loading ? <NativeLoadingState fullScreen={false} label={messages.form.loading} testID={`${testID}-loading`} /> : null}
163
+ {refusal ? <NativeInlineAlert testID={`${testID}-refusal`} variant="destructive" description={refusal} /> : null}
164
+ {loading ? null : sections.map((section, index) => (
165
+ <View key={section.key || `__first_${index}`} testID={`${testID}-section-${section.key || "main"}`} style={{ gap: 12 }}>
166
+ {section.title ? (
167
+ <NativeText preset="caption" accessibilityRole="header" className="uppercase text-muted-foreground">
168
+ {section.title}
169
+ </NativeText>
170
+ ) : null}
171
+ {section.fields.map((field) => (
172
+ <FormField key={field.key} field={field} form={form} mode={mode} testID={`${testID}-field-${field.key}`} />
173
+ ))}
174
+ </View>
175
+ ))}
176
+ </NativeSheetScrollView>
177
+ </NativeSheet>
178
+ );
179
+ }
180
+
181
+ type Form = ReturnType<typeof useForm<Values>>;
182
+
183
+ function FormField({
184
+ field,
185
+ form: f,
186
+ mode: m,
187
+ testID: id,
188
+ }: {
189
+ field: NativeFormField;
190
+ form: Form;
191
+ mode: "create" | "edit";
192
+ testID: string;
193
+ }) {
194
+ const messages = useNativeResourceViewMessages();
195
+ const zones = useDisplayTimeZones();
196
+ const error = f.formState.errors[field.key]?.message as string | undefined;
197
+ if (field.readOnly) {
198
+ // A link shows its raw id until batched relation labels arrive.
199
+ const shown = displayText(field.display, f.getValues(field.key), messages, resolveZone(undefined, zones));
200
+ return (
201
+ <View testID={id} style={{ gap: 4 }} accessibilityLabel={`${field.label}, ${shown}`}>
202
+ <NativeLabel>{field.label}</NativeLabel>
203
+ <NativeText testID={`${id}-value`} preset="body" className="text-muted-foreground">
204
+ {shown}
205
+ </NativeText>
206
+ </View>
207
+ );
208
+ }
209
+ const type = FIELD_TYPE[field.kind];
210
+ if (type) {
211
+ const def: ResourceFormFieldDef = {
212
+ key: field.key,
213
+ label: field.label,
214
+ type,
215
+ required: field.required,
216
+ ...(field.options ? { options: field.options } : {}),
217
+ ...(field.max !== undefined ? { maxLength: field.max } : {}),
218
+ };
219
+ return (
220
+ <View testID={id}>
221
+ <NativeResourceFormFieldRenderer field={def} control={f.control} action={m} />
222
+ </View>
223
+ );
224
+ }
225
+ return (
226
+ <Controller
227
+ name={field.key}
228
+ control={f.control}
229
+ render={({ field: input }) => (
230
+ <View testID={id} style={{ gap: 6 }}>
231
+ <NativeLabel>{field.label}</NativeLabel>
232
+ {field.kind === "segmented" ? (
233
+ <NativeSegmentedControl
234
+ testID={`${id}-segmented`}
235
+ options={field.options ?? []}
236
+ value={String(input.value ?? "")}
237
+ onChange={input.onChange}
238
+ />
239
+ ) : (
240
+ <DateField
241
+ kind={field.kind as "date" | "datetime"}
242
+ value={input.value}
243
+ onChange={input.onChange}
244
+ clearable={!field.required}
245
+ label={field.label}
246
+ testID={id}
247
+ />
248
+ )}
249
+ {error ? (
250
+ <NativeText preset="caption" className="text-destructive">
251
+ {error}
252
+ </NativeText>
253
+ ) : null}
254
+ </View>
255
+ )}
256
+ />
257
+ );
258
+ }
259
+
260
+ /**
261
+ * A day (`YYYY-MM-DD`, built from the picked date's own parts, never `toISOString`) or an instant
262
+ * (an ISO timestamp). An empty value shows a button that starts it at today.
263
+ */
264
+ function DateField({
265
+ kind,
266
+ value,
267
+ onChange,
268
+ clearable,
269
+ label,
270
+ testID,
271
+ }: {
272
+ kind: "date" | "datetime";
273
+ value: unknown;
274
+ onChange: (value: unknown) => void;
275
+ clearable: boolean;
276
+ label: string;
277
+ testID: string;
278
+ }) {
279
+ const messages = useNativeResourceViewMessages();
280
+ const date = kind === "date" ? dayToDate(value) : typeof value === "string" && value ? new Date(value) : null;
281
+ if (!date || Number.isNaN(date.getTime())) {
282
+ return (
283
+ <NativeButton
284
+ variant="outline"
285
+ size="sm"
286
+ testID={`${testID}-set`}
287
+ onPress={() => onChange(kind === "date" ? dateToDay(new Date()) : new Date().toISOString())}
288
+ >
289
+ {kind === "date" ? messages.form.pickDate : messages.form.pickDateTime}
290
+ </NativeButton>
291
+ );
292
+ }
293
+ const set = (next: Date) => onChange(kind === "date" ? dateToDay(next) : next.toISOString());
294
+ return (
295
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
296
+ <NativeDatePicker testID={`${testID}-date`} value={date} onChange={set} />
297
+ {kind === "datetime" ? <NativeTimePicker testID={`${testID}-time`} value={date} onChange={set} /> : null}
298
+ {clearable ? (
299
+ <NativeButton variant="ghost" size="sm" testID={`${testID}-clear`} onPress={() => onChange(null)}>
300
+ {fill(messages.form.clear, { label: label.toLowerCase() })}
301
+ </NativeButton>
302
+ ) : null}
303
+ </View>
304
+ );
305
+ }