@marktiderman/genesis-ui-native 2.5.0 → 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 (39) hide show
  1. package/dist/{chunk-IDHW2NOP.js → chunk-3S5XVER4.js} +231 -6
  2. package/dist/chunk-3S5XVER4.js.map +1 -0
  3. package/dist/chunk-56QLEHHV.js +1231 -0
  4. package/dist/chunk-56QLEHHV.js.map +1 -0
  5. package/dist/chunk-6JBNSW4D.js +479 -0
  6. package/dist/chunk-6JBNSW4D.js.map +1 -0
  7. package/dist/{chunk-YJV5MMZX.js → chunk-KZEIF4YI.js} +7 -741
  8. package/dist/chunk-KZEIF4YI.js.map +1 -0
  9. package/dist/{chunk-YI7XVY2D.js → chunk-VMSIKSU2.js} +13 -479
  10. package/dist/chunk-VMSIKSU2.js.map +1 -0
  11. package/dist/components/index.d.ts +3 -1
  12. package/dist/components/index.js +3 -4
  13. package/dist/data/index.d.ts +382 -4
  14. package/dist/data/index.js +1067 -19
  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/image.tsx +5 -0
  23. package/src/data/NativeDetailPanel.tsx +8 -1
  24. package/src/data/index.ts +1 -0
  25. package/src/data/resource-view/NativeResourceFormSheet.tsx +305 -0
  26. package/src/data/resource-view/NativeResourceView.tsx +528 -0
  27. package/src/data/resource-view/__tests__/native-resource-view.test.tsx +870 -0
  28. package/src/data/resource-view/display.tsx +256 -0
  29. package/src/data/resource-view/index.ts +50 -0
  30. package/src/data/resource-view/mapping.ts +326 -0
  31. package/src/data/resource-view/messages.ts +121 -0
  32. package/src/data/resource-view/use-native-resource-view.ts +307 -0
  33. package/dist/chunk-EFXCJ5AN.js +0 -234
  34. package/dist/chunk-EFXCJ5AN.js.map +0 -1
  35. package/dist/chunk-FIITITXO.js +0 -492
  36. package/dist/chunk-FIITITXO.js.map +0 -1
  37. package/dist/chunk-IDHW2NOP.js.map +0 -1
  38. package/dist/chunk-YI7XVY2D.js.map +0 -1
  39. package/dist/chunk-YJV5MMZX.js.map +0 -1
@@ -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
+ }