@oaiz/app-kit 0.0.0-stage → 0.1.4130

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +149 -2
  3. package/THIRD_PARTY_NOTICES.md +76 -0
  4. package/package.json +139 -4
  5. package/registry.json +1847 -0
  6. package/src/components/activity-timeline.tsx +227 -0
  7. package/src/components/app-shell.tsx +622 -0
  8. package/src/components/bar-list.tsx +47 -0
  9. package/src/components/board.tsx +700 -0
  10. package/src/components/calendar-view.tsx +1388 -0
  11. package/src/components/card-grid.tsx +462 -0
  12. package/src/components/charts.tsx +701 -0
  13. package/src/components/chat-markdown.tsx +230 -0
  14. package/src/components/chat-panel.tsx +760 -0
  15. package/src/components/code-editor.tsx +276 -0
  16. package/src/components/collection-controls.tsx +226 -0
  17. package/src/components/command-palette.tsx +403 -0
  18. package/src/components/confirm-action.tsx +123 -0
  19. package/src/components/data-table.tsx +821 -0
  20. package/src/components/date-input.tsx +429 -0
  21. package/src/components/empty-state.tsx +31 -0
  22. package/src/components/error-state.tsx +37 -0
  23. package/src/components/file-upload.tsx +595 -0
  24. package/src/components/filter-bar.tsx +415 -0
  25. package/src/components/grouped-picker.tsx +250 -0
  26. package/src/components/line-items.tsx +601 -0
  27. package/src/components/list-view.tsx +491 -0
  28. package/src/components/metrics.tsx +53 -0
  29. package/src/components/page-header.tsx +33 -0
  30. package/src/components/property-picker.tsx +546 -0
  31. package/src/components/record-detail.tsx +416 -0
  32. package/src/components/record-form.tsx +295 -0
  33. package/src/components/record-name.tsx +85 -0
  34. package/src/components/save-bar.tsx +142 -0
  35. package/src/components/sign-in.tsx +179 -0
  36. package/src/components/split-view.tsx +128 -0
  37. package/src/components/status-dot.tsx +56 -0
  38. package/src/components/stepper.tsx +153 -0
  39. package/src/components/text-diff-model.ts +111 -0
  40. package/src/components/text-diff.tsx +98 -0
  41. package/src/components/time-zone-picker.tsx +69 -0
  42. package/src/components/ui/accordion.tsx +138 -0
  43. package/src/components/ui/alert-dialog.tsx +67 -0
  44. package/src/components/ui/alert.tsx +65 -0
  45. package/src/components/ui/avatar-group.tsx +119 -0
  46. package/src/components/ui/avatar.tsx +55 -0
  47. package/src/components/ui/badge.tsx +59 -0
  48. package/src/components/ui/bottom-navigation.tsx +102 -0
  49. package/src/components/ui/breadcrumb.tsx +117 -0
  50. package/src/components/ui/button.tsx +71 -0
  51. package/src/components/ui/card.tsx +95 -0
  52. package/src/components/ui/checkbox.tsx +31 -0
  53. package/src/components/ui/collapsible.tsx +27 -0
  54. package/src/components/ui/context-menu.tsx +270 -0
  55. package/src/components/ui/count-up.tsx +136 -0
  56. package/src/components/ui/detail-disclosure-section.tsx +109 -0
  57. package/src/components/ui/dialog.tsx +157 -0
  58. package/src/components/ui/dropdown-menu.tsx +273 -0
  59. package/src/components/ui/form-field.tsx +155 -0
  60. package/src/components/ui/heading.tsx +126 -0
  61. package/src/components/ui/hover-card.tsx +45 -0
  62. package/src/components/ui/input.tsx +50 -0
  63. package/src/components/ui/label.tsx +30 -0
  64. package/src/components/ui/orb-spinner.tsx +238 -0
  65. package/src/components/ui/popover.tsx +59 -0
  66. package/src/components/ui/progress-ring.tsx +125 -0
  67. package/src/components/ui/progress.tsx +38 -0
  68. package/src/components/ui/radio-group.tsx +124 -0
  69. package/src/components/ui/resizable.tsx +48 -0
  70. package/src/components/ui/scroll-fade.tsx +98 -0
  71. package/src/components/ui/segmented-control.tsx +70 -0
  72. package/src/components/ui/select.tsx +230 -0
  73. package/src/components/ui/separator.tsx +29 -0
  74. package/src/components/ui/sheet.tsx +170 -0
  75. package/src/components/ui/shimmer-text.tsx +87 -0
  76. package/src/components/ui/shortcut.tsx +39 -0
  77. package/src/components/ui/skeleton.tsx +15 -0
  78. package/src/components/ui/slider.tsx +48 -0
  79. package/src/components/ui/switch.tsx +44 -0
  80. package/src/components/ui/table.tsx +119 -0
  81. package/src/components/ui/tabs.tsx +80 -0
  82. package/src/components/ui/text.tsx +93 -0
  83. package/src/components/ui/textarea.tsx +51 -0
  84. package/src/components/ui/toast.tsx +141 -0
  85. package/src/components/ui/toaster.tsx +40 -0
  86. package/src/components/ui/tooltip.tsx +38 -0
  87. package/src/components/ui/top-banner.tsx +108 -0
  88. package/src/components/ui/tree-view.tsx +215 -0
  89. package/src/components/ui/use-toast.tsx +184 -0
  90. package/src/components/ui/voice-orb.tsx +252 -0
  91. package/src/hooks/oaiz-chat.tsx +530 -0
  92. package/src/hooks/oaiz-data.tsx +617 -0
  93. package/src/hooks/oaiz-session.tsx +63 -0
  94. package/src/hooks/use-arrivals.ts +19 -0
  95. package/src/hooks/use-breakpoint.ts +100 -0
  96. package/src/hooks/use-media-query.ts +36 -0
  97. package/src/hooks/use-theme.ts +67 -0
  98. package/src/hooks/use-url-state.ts +77 -0
  99. package/src/lib/breakpoints.ts +81 -0
  100. package/src/lib/csp-nonce.ts +15 -0
  101. package/src/lib/format.ts +291 -0
  102. package/src/lib/speech-level.ts +118 -0
  103. package/src/lib/utils.ts +109 -0
  104. package/src/styles/oaiz/app.css +21 -0
  105. package/src/styles/oaiz/scrollbars.css +20 -0
  106. package/src/styles/oaiz/tokens.css +952 -0
  107. package/src/styles/oaiz/voice-orb.css +39 -0
@@ -0,0 +1,416 @@
1
+ import { Label } from './ui/label';
2
+ import { Button } from './ui/button';
3
+ import {
4
+ useId,
5
+ useLayoutEffect,
6
+ useRef,
7
+ useState,
8
+ type KeyboardEvent,
9
+ type ReactNode,
10
+ } from 'react';
11
+
12
+ import { cn } from '../lib/utils';
13
+ import { Alert, AlertDescription } from './ui/alert';
14
+ import {
15
+ Dialog,
16
+ DialogContent,
17
+ DialogDescription,
18
+ DialogHeader,
19
+ DialogTitle,
20
+ } from './ui/dialog';
21
+ import { Heading } from './ui/heading';
22
+ import { Input } from './ui/input';
23
+ import {
24
+ Select,
25
+ SelectContent,
26
+ SelectItem,
27
+ SelectTrigger,
28
+ SelectValue,
29
+ } from './ui/select';
30
+ import { Skeleton } from './ui/skeleton';
31
+ import { Text } from './ui/text';
32
+ import { Textarea } from './ui/textarea';
33
+
34
+ export type RecordDetailField<Row> = {
35
+ /** The column the field shows and saves. */
36
+ key: string;
37
+ label: string;
38
+ /** Shown before the label, such as an icon for the field's type. */
39
+ icon?: ReactNode;
40
+ type: 'text' | 'number' | 'email' | 'textarea' | 'select';
41
+ options?: { value: string; label: ReactNode }[];
42
+ /** How the value reads when it is not being edited; the raw value when omitted. */
43
+ display?: (row: Row) => ReactNode;
44
+ readOnly?: boolean;
45
+ };
46
+
47
+ export type RecordDetailProps<Row> = {
48
+ title: ReactNode;
49
+ subtitle?: ReactNode;
50
+ fields: RecordDetailField<Row>[];
51
+ row: Row | undefined;
52
+ loading?: boolean;
53
+ /** Shown instead of the fields. */
54
+ error?: { message: string } | null;
55
+ /** Saves one field; the field shows the rejection's message and keeps the entered value. */
56
+ onSave?: (column: string, value: string | number | null) => Promise<unknown>;
57
+ /** Buttons beside the title. */
58
+ actions?: ReactNode;
59
+ /** Related records below the fields, such as a customer's orders. */
60
+ children?: ReactNode;
61
+ labels?: Partial<RecordDetailLabels>;
62
+ };
63
+
64
+ export type RecordDetailLabels = {
65
+ empty: string;
66
+ details: string;
67
+ description: string;
68
+ saveError: string;
69
+ numberError: string;
70
+ close: string;
71
+ };
72
+ const defaultLabels: RecordDetailLabels = {
73
+ empty: 'Empty',
74
+ details: 'Details',
75
+ description: 'Record details',
76
+ saveError: 'The change was not saved.',
77
+ numberError: 'Enter a number.',
78
+ close: 'Close',
79
+ };
80
+
81
+ function valueOf<Row>(row: Row, key: string): unknown {
82
+ return (row as Record<string, unknown>)[key];
83
+ }
84
+
85
+ function asText(value: unknown): string {
86
+ return value === null || value === undefined ? '' : String(value);
87
+ }
88
+
89
+ function Field<Row>({
90
+ field,
91
+ row,
92
+ onSave,
93
+ labels,
94
+ }: {
95
+ field: RecordDetailField<Row>;
96
+ row: Row;
97
+ onSave?: RecordDetailProps<Row>['onSave'];
98
+ labels: RecordDetailLabels;
99
+ }) {
100
+ const id = useId();
101
+ const current = valueOf(row, field.key);
102
+ const [editing, setEditing] = useState(false);
103
+ const [draft, setDraft] = useState('');
104
+ const [saving, setSaving] = useState(false);
105
+ const [error, setError] = useState<string | null>(null);
106
+ // Enter saves and the blur that follows must not save again.
107
+ const inFlight = useRef(false);
108
+ const trigger = useRef<HTMLButtonElement>(null);
109
+ const restoreFocus = useRef(false);
110
+ const cancelled = useRef(false);
111
+ useLayoutEffect(() => {
112
+ if (!editing && restoreFocus.current) {
113
+ restoreFocus.current = false;
114
+ trigger.current?.focus();
115
+ }
116
+ }, [editing]);
117
+ const editable = onSave !== undefined && !field.readOnly;
118
+
119
+ async function save(text: string, restore = false, badInput = false) {
120
+ if (inFlight.current || cancelled.current) return;
121
+ if (badInput) {
122
+ setError(labels.numberError);
123
+ return;
124
+ }
125
+ restoreFocus.current = restore;
126
+ const value =
127
+ text.trim() === '' ? null : field.type === 'number' ? Number(text) : text;
128
+ if (value === current || (value === null && current == null)) {
129
+ setEditing(false);
130
+ return;
131
+ }
132
+ inFlight.current = true;
133
+ setSaving(true);
134
+ setError(null);
135
+ try {
136
+ await onSave!(field.key, value);
137
+ setEditing(false);
138
+ } catch (failure) {
139
+ setError(failure instanceof Error ? failure.message : labels.saveError);
140
+ } finally {
141
+ inFlight.current = false;
142
+ setSaving(false);
143
+ }
144
+ }
145
+
146
+ function onKeyDown(
147
+ event: KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>,
148
+ ) {
149
+ if (event.nativeEvent.isComposing) return;
150
+ if (event.key === 'Escape') {
151
+ event.preventDefault();
152
+ cancelled.current = true;
153
+ restoreFocus.current = true;
154
+ setEditing(false);
155
+ setError(null);
156
+ } else if (
157
+ event.key === 'Enter' &&
158
+ (field.type !== 'textarea' || event.metaKey || event.ctrlKey)
159
+ ) {
160
+ event.preventDefault();
161
+ void save(draft, true, event.currentTarget.validity.badInput);
162
+ }
163
+ }
164
+
165
+ const shown = field.display ? field.display(row) : asText(current);
166
+ const empty = current === null || current === undefined || current === '';
167
+
168
+ let control: ReactNode;
169
+ if (field.type === 'select' && editable) {
170
+ control = (
171
+ <Select
172
+ value={asText(current) || undefined}
173
+ disabled={saving}
174
+ onValueChange={(chosen) => void save(chosen)}
175
+ >
176
+ <SelectTrigger id={id} size="sm" className="w-full">
177
+ <SelectValue placeholder={labels.empty} />
178
+ </SelectTrigger>
179
+ <SelectContent aria-labelledby={`${id}-label`}>
180
+ {field.options?.map((option) => (
181
+ <SelectItem key={option.value} value={option.value}>
182
+ {option.label}
183
+ </SelectItem>
184
+ ))}
185
+ </SelectContent>
186
+ </Select>
187
+ );
188
+ } else if (editing) {
189
+ const shared = {
190
+ id,
191
+ autoFocus: true,
192
+ value: draft,
193
+ disabled: saving,
194
+ 'aria-invalid': error !== null,
195
+ 'aria-describedby': error ? `${id}-error` : undefined,
196
+ onChange: (event: { target: { value: string } }) => {
197
+ setDraft(event.target.value);
198
+ setError(null);
199
+ },
200
+ onKeyDown,
201
+ onBlur: (event: { currentTarget: { validity: ValidityState } }) =>
202
+ void save(draft, false, event.currentTarget.validity.badInput),
203
+ };
204
+ control =
205
+ field.type === 'textarea' ? (
206
+ <Textarea {...shared} rows={3} />
207
+ ) : (
208
+ <Input
209
+ {...shared}
210
+ type={field.type === 'select' ? 'text' : field.type}
211
+ />
212
+ );
213
+ } else if (editable) {
214
+ control = (
215
+ <Button variant="plain" size={null}
216
+ ref={trigger}
217
+ id={id}
218
+ type="button"
219
+ aria-labelledby={`${id}-label ${id}-value`}
220
+ className={cn(
221
+ 'flex min-h-8 w-full items-center rounded-md px-inline text-left text-sm hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
222
+ empty && 'text-muted-foreground',
223
+ )}
224
+ onClick={() => {
225
+ cancelled.current = false;
226
+ setDraft(asText(current));
227
+ setEditing(true);
228
+ }}
229
+ >
230
+ <span id={`${id}-value`}>{empty ? labels.empty : shown}</span>
231
+ </Button>
232
+ );
233
+ } else {
234
+ control = (
235
+ <Text
236
+ as="div"
237
+ id={id}
238
+ size="sm"
239
+ className={cn('px-inline py-1.5', empty && 'text-muted-foreground')}
240
+ >
241
+ {empty ? labels.empty : shown}
242
+ </Text>
243
+ );
244
+ }
245
+
246
+ return (
247
+ <div className="grid grid-cols-[9rem_1fr] items-start gap-inline">
248
+ <Label
249
+ id={`${id}-label`}
250
+ htmlFor={id}
251
+ className="flex min-h-8 items-center gap-1.5 text-sm text-muted-foreground [&_svg]:size-3.5 [&_svg]:shrink-0"
252
+ >
253
+ {field.icon && (
254
+ <span aria-hidden="true" className="flex">
255
+ {field.icon}
256
+ </span>
257
+ )}
258
+ <span className="truncate">{field.label}</span>
259
+ </Label>
260
+ <div className="flex min-w-0 flex-col gap-1">
261
+ {control}
262
+ {error && (
263
+ <Text id={`${id}-error`} size="sm" variant="destructive" role="alert">
264
+ {error}
265
+ </Text>
266
+ )}
267
+ </div>
268
+ </div>
269
+ );
270
+ }
271
+
272
+ function RecordFields<Row>({
273
+ fields,
274
+ row,
275
+ loading,
276
+ onSave,
277
+ labels,
278
+ }: Pick<RecordDetailProps<Row>, 'fields' | 'row' | 'onSave'> & {
279
+ loading: boolean;
280
+ labels: RecordDetailLabels;
281
+ }) {
282
+ return (
283
+ <section aria-label={labels.details} className="flex flex-col gap-1">
284
+ {loading || row === undefined
285
+ ? fields.map((field) => (
286
+ <div
287
+ key={field.key}
288
+ className="grid grid-cols-[9rem_1fr] gap-inline py-2"
289
+ >
290
+ <Skeleton className="h-4 w-20" />
291
+ <Skeleton className="h-4 w-full" />
292
+ </div>
293
+ ))
294
+ : fields.map((field) => (
295
+ <Field
296
+ key={field.key}
297
+ field={field}
298
+ row={row}
299
+ onSave={onSave}
300
+ labels={labels}
301
+ />
302
+ ))}
303
+ </section>
304
+ );
305
+ }
306
+
307
+ /**
308
+ * One record: a title, its fields with inline editing, and related records below. A text field
309
+ * opens on click and saves on Enter or when it loses focus; Escape cancels. A select saves when
310
+ * an option is chosen.
311
+ */
312
+ export function RecordDetail<Row>({
313
+ title,
314
+ subtitle,
315
+ fields,
316
+ row,
317
+ loading = false,
318
+ error,
319
+ onSave,
320
+ actions,
321
+ children,
322
+ labels: suppliedLabels,
323
+ }: RecordDetailProps<Row>) {
324
+ const labels = { ...defaultLabels, ...suppliedLabels };
325
+ if (error) {
326
+ return (
327
+ <Alert variant="destructive">
328
+ <AlertDescription>{error.message}</AlertDescription>
329
+ </Alert>
330
+ );
331
+ }
332
+
333
+ return (
334
+ <article aria-busy={loading} className="flex flex-col gap-section">
335
+ <header className="flex items-start justify-between gap-stack">
336
+ <div className="flex min-w-0 flex-col gap-1">
337
+ {loading || row === undefined ? (
338
+ <Skeleton className="h-7 w-48" />
339
+ ) : (
340
+ <Heading level={2} size="2xl" className="truncate">
341
+ {title}
342
+ </Heading>
343
+ )}
344
+ {subtitle && !loading && <Text variant="muted">{subtitle}</Text>}
345
+ </div>
346
+ {actions && <div className="flex shrink-0 gap-inline">{actions}</div>}
347
+ </header>
348
+ <RecordFields
349
+ fields={fields}
350
+ row={row}
351
+ loading={loading}
352
+ onSave={onSave}
353
+ labels={labels}
354
+ />
355
+ {children}
356
+ </article>
357
+ );
358
+ }
359
+
360
+ export type RecordDetailDialogProps<Row> = RecordDetailProps<Row> & {
361
+ open: boolean;
362
+ onOpenChange: (open: boolean) => void;
363
+ };
364
+
365
+ /** `RecordDetail` in a dialog, whose title is the record's: nothing repeats it. */
366
+ export function RecordDetailDialog<Row>({
367
+ open,
368
+ onOpenChange,
369
+ title,
370
+ subtitle,
371
+ fields,
372
+ row,
373
+ loading = false,
374
+ error,
375
+ onSave,
376
+ actions,
377
+ children,
378
+ labels: suppliedLabels,
379
+ }: RecordDetailDialogProps<Row>) {
380
+ const labels = { ...defaultLabels, ...suppliedLabels };
381
+ return (
382
+ <Dialog open={open} onOpenChange={onOpenChange}>
383
+ <DialogContent closeLabel={labels.close}>
384
+ <DialogHeader>
385
+ <DialogTitle className="truncate pr-section">{title}</DialogTitle>
386
+ {subtitle ? (
387
+ <DialogDescription>{subtitle}</DialogDescription>
388
+ ) : (
389
+ <DialogDescription className="sr-only">
390
+ {labels.description}
391
+ </DialogDescription>
392
+ )}
393
+ </DialogHeader>
394
+ {error ? (
395
+ <Alert variant="destructive">
396
+ <AlertDescription>{error.message}</AlertDescription>
397
+ </Alert>
398
+ ) : (
399
+ <div aria-busy={loading} className="flex flex-col gap-section">
400
+ <RecordFields
401
+ fields={fields}
402
+ row={row}
403
+ loading={loading}
404
+ onSave={onSave}
405
+ labels={labels}
406
+ />
407
+ {children}
408
+ {actions && (
409
+ <div className="flex justify-end gap-inline">{actions}</div>
410
+ )}
411
+ </div>
412
+ )}
413
+ </DialogContent>
414
+ </Dialog>
415
+ );
416
+ }
@@ -0,0 +1,295 @@
1
+ import {
2
+ useId,
3
+ useLayoutEffect,
4
+ useRef,
5
+ useState,
6
+ type FormEvent,
7
+ type ReactNode,
8
+ } from 'react';
9
+ import { Alert, AlertDescription } from './ui/alert';
10
+ import { Button } from './ui/button';
11
+ import { ErrorSummary, FieldGroup, FormField } from './ui/form-field';
12
+ import { Input } from './ui/input';
13
+ import {
14
+ Select,
15
+ SelectContent,
16
+ SelectItem,
17
+ SelectTrigger,
18
+ SelectValue,
19
+ } from './ui/select';
20
+ import { Textarea } from './ui/textarea';
21
+
22
+ export type RecordField = {
23
+ name: string;
24
+ label: ReactNode;
25
+ type: 'text' | 'number' | 'email' | 'date' | 'textarea' | 'select';
26
+ required?: boolean;
27
+ decimals?: number;
28
+ options?: { value: string; label: string }[];
29
+ placeholder?: string;
30
+ hint?: ReactNode;
31
+ autoComplete?: string;
32
+ };
33
+ export type RecordValues = Record<string, string | number>;
34
+ export type RecordFormLabels = {
35
+ required: string;
36
+ choose: string;
37
+ saving: string;
38
+ summary: string;
39
+ requiredError: string;
40
+ emailError: string;
41
+ numberError: string;
42
+ dateError: string;
43
+ decimalsError: (places: number) => string;
44
+ saveError: string;
45
+ };
46
+ const defaults: RecordFormLabels = {
47
+ required: 'required',
48
+ choose: 'Choose',
49
+ saving: 'Saving…',
50
+ summary: 'Check the following fields',
51
+ requiredError: 'This field is required.',
52
+ emailError: 'Enter a valid email address.',
53
+ numberError: 'Enter a number.',
54
+ dateError: 'Enter a valid calendar date.',
55
+ decimalsError: (places) => `Use no more than ${places} decimal places.`,
56
+ saveError: 'The changes were not saved. Try again.',
57
+ };
58
+ export type RecordFormProps = {
59
+ fields: RecordField[];
60
+ submitLabel: ReactNode;
61
+ onSubmit: (values: RecordValues) => unknown;
62
+ validate?: (values: RecordValues) => Record<string, string> | undefined;
63
+ pending?: boolean;
64
+ error?: { message: string } | null;
65
+ /** Initial values are read on mount; key the form by record ID when changing records. */
66
+ initialValues?: RecordValues;
67
+ /** Edit forms preserve their values after saving; create forms reset by default. */
68
+ mode?: 'create' | 'edit';
69
+ resetOnSuccess?: boolean;
70
+ legend?: ReactNode;
71
+ labels?: Partial<RecordFormLabels>;
72
+ };
73
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
74
+ function builtInError(
75
+ field: RecordField,
76
+ value: string,
77
+ labels: RecordFormLabels,
78
+ badInput = false,
79
+ ): string | undefined {
80
+ if (badInput)
81
+ return field.type === 'date' ? labels.dateError : labels.numberError;
82
+ if (value === '') return field.required ? labels.requiredError : undefined;
83
+ if (field.type === 'email' && !EMAIL.test(value)) return labels.emailError;
84
+ if (field.type === 'number' && !Number.isFinite(Number(value)))
85
+ return labels.numberError;
86
+ if (
87
+ field.type === 'number' &&
88
+ field.decimals !== undefined &&
89
+ (value.split('.')[1] ?? '').length > field.decimals
90
+ )
91
+ return labels.decimalsError(field.decimals);
92
+ return undefined;
93
+ }
94
+
95
+ /** Empty create fields are omitted so database defaults apply; empty edit fields are explicit. */
96
+ export function RecordForm({
97
+ fields,
98
+ submitLabel,
99
+ onSubmit,
100
+ validate,
101
+ pending = false,
102
+ error,
103
+ initialValues = {},
104
+ mode = 'create',
105
+ resetOnSuccess = mode === 'create',
106
+ legend,
107
+ labels: suppliedLabels,
108
+ }: RecordFormProps) {
109
+ const labels = { ...defaults, ...suppliedLabels };
110
+ const id = useId();
111
+ const [values, setValues] = useState<Record<string, string>>(() =>
112
+ Object.fromEntries(
113
+ Object.entries(initialValues).map(([key, value]) => [key, String(value)]),
114
+ ),
115
+ );
116
+ const initial = useRef(values);
117
+ const [errors, setErrors] = useState<Record<string, string>>({});
118
+ const [failure, setFailure] = useState<string | null>(null);
119
+ const [saving, setSaving] = useState(false);
120
+ const inFlight = useRef(false);
121
+ const inputRefs = useRef(new Map<string, HTMLInputElement>());
122
+ const summary = useRef<HTMLDivElement>(null);
123
+ const [attempt, setAttempt] = useState(0);
124
+ const busy = pending || saving;
125
+ useLayoutEffect(() => {
126
+ if (attempt > 0) summary.current?.focus();
127
+ }, [attempt]);
128
+
129
+ function change(field: RecordField, value: string, badInput = false) {
130
+ if (busy || inFlight.current) return;
131
+ setValues((current) => ({ ...current, [field.name]: value }));
132
+ setErrors((current) => {
133
+ if (!current[field.name]) return current;
134
+ const next = { ...current };
135
+ const problem = builtInError(field, value.trim(), labels, badInput);
136
+ if (problem) next[field.name] = problem;
137
+ else delete next[field.name];
138
+ return next;
139
+ });
140
+ }
141
+ async function handleSubmit(event: FormEvent<HTMLFormElement>) {
142
+ event.preventDefault();
143
+ if (busy || inFlight.current) return;
144
+ const submitted: RecordValues = {};
145
+ const found: Record<string, string> = {};
146
+ for (const field of fields) {
147
+ const value = (values[field.name] ?? '').trim();
148
+ const control = inputRefs.current.get(field.name);
149
+ const problem = builtInError(
150
+ field,
151
+ value,
152
+ labels,
153
+ control?.validity.badInput,
154
+ );
155
+ if (problem) found[field.name] = problem;
156
+ else if (value !== '')
157
+ submitted[field.name] = field.type === 'number' ? Number(value) : value;
158
+ else if (mode === 'edit') submitted[field.name] = '';
159
+ }
160
+ const all =
161
+ Object.keys(found).length > 0 ? found : (validate?.(submitted) ?? {});
162
+ setErrors(all);
163
+ if (Object.keys(all).length > 0) {
164
+ setAttempt((value) => value + 1);
165
+ return;
166
+ }
167
+ inFlight.current = true;
168
+ setSaving(true);
169
+ setFailure(null);
170
+ try {
171
+ await onSubmit(submitted);
172
+ if (resetOnSuccess) setValues(initial.current);
173
+ } catch (cause) {
174
+ setFailure(cause instanceof Error ? cause.message : labels.saveError);
175
+ } finally {
176
+ inFlight.current = false;
177
+ setSaving(false);
178
+ }
179
+ }
180
+ const controls = fields.map((field) => (
181
+ <FormField
182
+ key={field.name}
183
+ id={`${id}-${field.name}`}
184
+ label={field.label}
185
+ hint={field.hint}
186
+ error={errors[field.name]}
187
+ required={field.required}
188
+ requiredLabel={labels.required}
189
+ >
190
+ {(control) =>
191
+ field.type === 'select' ? (
192
+ <Select
193
+ value={values[field.name] ?? ''}
194
+ onValueChange={(value) => change(field, value)}
195
+ required={field.required}
196
+ disabled={busy}
197
+ >
198
+ <SelectTrigger
199
+ {...control}
200
+ data-testid={`record-form-${field.name}`}
201
+ >
202
+ <SelectValue placeholder={field.placeholder ?? labels.choose} />
203
+ </SelectTrigger>
204
+ <SelectContent aria-labelledby={`${control.id}-label`}>
205
+ {field.options?.map((option) => (
206
+ <SelectItem key={option.value} value={option.value}>
207
+ {option.label}
208
+ </SelectItem>
209
+ ))}
210
+ </SelectContent>
211
+ </Select>
212
+ ) : field.type === 'textarea' ? (
213
+ <Textarea
214
+ {...control}
215
+ name={field.name}
216
+ value={values[field.name] ?? ''}
217
+ autoComplete={field.autoComplete}
218
+ disabled={busy}
219
+ placeholder={field.placeholder}
220
+ onChange={(event) => change(field, event.target.value)}
221
+ data-testid={`record-form-${field.name}`}
222
+ />
223
+ ) : (
224
+ <Input
225
+ {...control}
226
+ ref={(input) => {
227
+ if (input) inputRefs.current.set(field.name, input);
228
+ else inputRefs.current.delete(field.name);
229
+ }}
230
+ name={field.name}
231
+ value={values[field.name] ?? ''}
232
+ type={field.type}
233
+ step={field.type === 'number' ? 'any' : undefined}
234
+ autoComplete={field.autoComplete}
235
+ disabled={busy}
236
+ placeholder={field.placeholder}
237
+ onInput={(event) =>
238
+ change(
239
+ field,
240
+ event.currentTarget.value,
241
+ event.currentTarget.validity.badInput,
242
+ )
243
+ }
244
+ onChange={(event) =>
245
+ change(field, event.target.value, event.target.validity.badInput)
246
+ }
247
+ data-testid={`record-form-${field.name}`}
248
+ />
249
+ )
250
+ }
251
+ </FormField>
252
+ ));
253
+ return (
254
+ <form
255
+ noValidate
256
+ aria-busy={busy}
257
+ className="flex flex-col gap-stack"
258
+ onSubmit={(event) => void handleSubmit(event)}
259
+ >
260
+ <ErrorSummary
261
+ ref={summary}
262
+ title={labels.summary}
263
+ errors={fields
264
+ .filter((field) => errors[field.name])
265
+ .map((field) => ({
266
+ id: `${id}-${field.name}`,
267
+ label: field.label,
268
+ message: errors[field.name],
269
+ }))}
270
+ />
271
+ {legend ? (
272
+ <FieldGroup legend={legend} disabled={busy}>
273
+ {controls}
274
+ </FieldGroup>
275
+ ) : (
276
+ <fieldset disabled={busy} className="flex min-w-0 flex-col gap-stack">
277
+ {controls}
278
+ </fieldset>
279
+ )}
280
+ {(error || failure) && (
281
+ <Alert variant="destructive">
282
+ <AlertDescription>{error?.message ?? failure}</AlertDescription>
283
+ </Alert>
284
+ )}
285
+ <Button
286
+ type="submit"
287
+ disabled={busy}
288
+ className="self-start"
289
+ data-testid="record-form-submit"
290
+ >
291
+ {busy ? labels.saving : submitLabel}
292
+ </Button>
293
+ </form>
294
+ );
295
+ }