@alepha/ui 0.25.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 (136) hide show
  1. package/README.md +12 -0
  2. package/components.json +20 -0
  3. package/package.json +85 -0
  4. package/src/components/action-error-toaster/action-error-toaster.tsx +70 -0
  5. package/src/components/admin/admin-audits.tsx +247 -0
  6. package/src/components/admin/admin-files.tsx +346 -0
  7. package/src/components/admin/admin-jobs-executions-panel.tsx +235 -0
  8. package/src/components/admin/admin-jobs-status-badge.tsx +33 -0
  9. package/src/components/admin/admin-jobs.tsx +294 -0
  10. package/src/components/admin/admin-keys.tsx +162 -0
  11. package/src/components/admin/admin-notifications.tsx +130 -0
  12. package/src/components/admin/admin-page.tsx +24 -0
  13. package/src/components/admin/admin-parameters.tsx +864 -0
  14. package/src/components/admin/admin-payments.tsx +93 -0
  15. package/src/components/admin/admin-sessions.tsx +174 -0
  16. package/src/components/admin/admin-user-detail-audits-tab.tsx +82 -0
  17. package/src/components/admin/admin-user-detail-identity-aside.tsx +218 -0
  18. package/src/components/admin/admin-user-detail-overview-tab.tsx +87 -0
  19. package/src/components/admin/admin-user-detail-password-dialog.tsx +85 -0
  20. package/src/components/admin/admin-user-detail-password-schema.ts +11 -0
  21. package/src/components/admin/admin-user-detail-profile-schema.ts +19 -0
  22. package/src/components/admin/admin-user-detail-provider-labels.ts +15 -0
  23. package/src/components/admin/admin-user-detail-security-tab.tsx +146 -0
  24. package/src/components/admin/admin-user-detail-sessions-tab.tsx +93 -0
  25. package/src/components/admin/admin-user-detail.tsx +606 -0
  26. package/src/components/admin/admin-users-roles-picker.tsx +126 -0
  27. package/src/components/admin/admin-users-status-filter.tsx +51 -0
  28. package/src/components/admin/admin-users.tsx +518 -0
  29. package/src/components/admin/diff-lines.spec.ts +58 -0
  30. package/src/components/admin/diff-lines.ts +58 -0
  31. package/src/components/admin/parameter-diff-dialog.tsx +119 -0
  32. package/src/components/admin/parameter-history-item.tsx +252 -0
  33. package/src/components/admin/parameter-json-dialog.tsx +93 -0
  34. package/src/components/admin/parameter-save-dialog.tsx +126 -0
  35. package/src/components/admin/use-confirmed-action.tsx +93 -0
  36. package/src/components/alepha-table/__tests__/use-table-selection.browser.spec.tsx +92 -0
  37. package/src/components/alepha-table/alepha-table.tsx +1158 -0
  38. package/src/components/alepha-table/use-table-selection.ts +95 -0
  39. package/src/components/app-shell/app-shell.tsx +568 -0
  40. package/src/components/auth/__tests__/auth-router.spec.ts +52 -0
  41. package/src/components/auth/auth-login.tsx +382 -0
  42. package/src/components/auth/auth-register.tsx +786 -0
  43. package/src/components/auth/auth-reset-password.tsx +349 -0
  44. package/src/components/auth/auth-router.tsx +126 -0
  45. package/src/components/auth/auth-verify-email.tsx +179 -0
  46. package/src/components/auto-form/auto-form.tsx +867 -0
  47. package/src/components/brand-icon/brand-icon.tsx +104 -0
  48. package/src/components/button-dark/button-dark.tsx +78 -0
  49. package/src/components/button-language/button-language.tsx +98 -0
  50. package/src/components/button-theme/button-theme.tsx +148 -0
  51. package/src/components/button-user/button-user.tsx +214 -0
  52. package/src/components/captcha/turnstile-widget.tsx +157 -0
  53. package/src/components/control/control.tsx +735 -0
  54. package/src/components/control-array/control-array.tsx +700 -0
  55. package/src/components/control-base/__tests__/form-field-a11y.browser.spec.tsx +93 -0
  56. package/src/components/control-base/field-i18n.ts +60 -0
  57. package/src/components/control-base/form-field.tsx +275 -0
  58. package/src/components/control-base/grid.tsx +59 -0
  59. package/src/components/control-base/icon-hint.tsx +64 -0
  60. package/src/components/control-date/control-date.tsx +190 -0
  61. package/src/components/control-number/control-number.tsx +136 -0
  62. package/src/components/control-object/control-object.tsx +200 -0
  63. package/src/components/control-select/control-select.tsx +774 -0
  64. package/src/components/control-upload/control-upload.tsx +475 -0
  65. package/src/components/file-image/file-image.tsx +52 -0
  66. package/src/components/language-toggle/language-toggle.tsx +66 -0
  67. package/src/components/markdown-view/markdown-view.css +114 -0
  68. package/src/components/markdown-view/markdown-view.tsx +92 -0
  69. package/src/components/nav-shell/nav-page.tsx +56 -0
  70. package/src/components/nav-shell/nav-shell.tsx +72 -0
  71. package/src/components/nav-shell/nav-tree-util.ts +62 -0
  72. package/src/components/nav-shell/spotlight.tsx +163 -0
  73. package/src/components/nav-shell/use-nav-breadcrumbs.ts +52 -0
  74. package/src/components/nav-shell/use-nav-entries.ts +101 -0
  75. package/src/components/nav-shell/use-nav-tree.ts +61 -0
  76. package/src/components/ui/accordion.tsx +77 -0
  77. package/src/components/ui/alert-dialog.tsx +186 -0
  78. package/src/components/ui/alert.tsx +75 -0
  79. package/src/components/ui/aspect-ratio.tsx +22 -0
  80. package/src/components/ui/avatar.tsx +106 -0
  81. package/src/components/ui/badge.tsx +51 -0
  82. package/src/components/ui/breadcrumb.tsx +121 -0
  83. package/src/components/ui/button-group.tsx +86 -0
  84. package/src/components/ui/button.tsx +83 -0
  85. package/src/components/ui/calendar.tsx +235 -0
  86. package/src/components/ui/card.tsx +102 -0
  87. package/src/components/ui/carousel.tsx +241 -0
  88. package/src/components/ui/chart.tsx +370 -0
  89. package/src/components/ui/checkbox.tsx +27 -0
  90. package/src/components/ui/collapsible.tsx +19 -0
  91. package/src/components/ui/combobox.tsx +298 -0
  92. package/src/components/ui/command.tsx +196 -0
  93. package/src/components/ui/context-menu.tsx +271 -0
  94. package/src/components/ui/dialog.tsx +153 -0
  95. package/src/components/ui/direction.tsx +4 -0
  96. package/src/components/ui/drawer.tsx +130 -0
  97. package/src/components/ui/dropdown-menu.tsx +269 -0
  98. package/src/components/ui/empty.tsx +100 -0
  99. package/src/components/ui/hover-card.tsx +50 -0
  100. package/src/components/ui/input-group.tsx +157 -0
  101. package/src/components/ui/input-otp.tsx +83 -0
  102. package/src/components/ui/input.tsx +19 -0
  103. package/src/components/ui/item.tsx +200 -0
  104. package/src/components/ui/kbd.tsx +26 -0
  105. package/src/components/ui/label.tsx +19 -0
  106. package/src/components/ui/menubar.tsx +283 -0
  107. package/src/components/ui/navigation-menu.tsx +170 -0
  108. package/src/components/ui/pagination.tsx +133 -0
  109. package/src/components/ui/popover.tsx +87 -0
  110. package/src/components/ui/progress.tsx +82 -0
  111. package/src/components/ui/radio-group.tsx +35 -0
  112. package/src/components/ui/resizable.tsx +49 -0
  113. package/src/components/ui/scroll-area.tsx +51 -0
  114. package/src/components/ui/segmented.tsx +232 -0
  115. package/src/components/ui/select.tsx +201 -0
  116. package/src/components/ui/separator.tsx +22 -0
  117. package/src/components/ui/sheet.tsx +133 -0
  118. package/src/components/ui/sidebar.tsx +723 -0
  119. package/src/components/ui/skeleton.tsx +13 -0
  120. package/src/components/ui/slider.tsx +51 -0
  121. package/src/components/ui/sonner.tsx +46 -0
  122. package/src/components/ui/spinner.tsx +15 -0
  123. package/src/components/ui/switch.tsx +29 -0
  124. package/src/components/ui/table.tsx +115 -0
  125. package/src/components/ui/tabs.tsx +79 -0
  126. package/src/components/ui/textarea.tsx +17 -0
  127. package/src/components/ui/toggle-group.tsx +86 -0
  128. package/src/components/ui/toggle.tsx +44 -0
  129. package/src/components/ui/tooltip.tsx +63 -0
  130. package/src/components/use-dialog/use-dialog.tsx +244 -0
  131. package/src/components/use-toast/use-toast.tsx +89 -0
  132. package/src/hooks/use-mobile.ts +21 -0
  133. package/src/lib/__tests__/i18n-fr.spec.ts +72 -0
  134. package/src/lib/i18n-fr.ts +500 -0
  135. package/src/lib/utils.ts +6 -0
  136. package/src/styles.css +129 -0
@@ -0,0 +1,867 @@
1
+ import * as React from "react";
2
+
3
+ void React;
4
+
5
+ import {
6
+ Control,
7
+ type ControlProps,
8
+ } from "@alepha/ui/components/control/control";
9
+ import {
10
+ FormFieldAutoSaveProvider,
11
+ FormFieldLayoutProvider,
12
+ } from "@alepha/ui/components/control-base/form-field";
13
+ import { spanClass, widthFor } from "@alepha/ui/components/control-base/grid";
14
+ import { iconFor } from "@alepha/ui/components/control-base/icon-hint";
15
+ import { Button } from "@alepha/ui/components/ui/button";
16
+ import {
17
+ Card,
18
+ CardContent,
19
+ CardDescription,
20
+ CardFooter,
21
+ CardTitle,
22
+ } from "@alepha/ui/components/ui/card";
23
+ import {
24
+ Popover,
25
+ PopoverContent,
26
+ PopoverTrigger,
27
+ } from "@alepha/ui/components/ui/popover";
28
+ import { cn } from "@alepha/ui/lib/utils";
29
+ import { type ZObject, z } from "alepha";
30
+ import { useAlepha } from "alepha/react";
31
+ import {
32
+ type BaseInputField,
33
+ type FormModel,
34
+ isObjectOrUnionOfObjects,
35
+ useFormState,
36
+ } from "alepha/react/form";
37
+ import { useI18n } from "alepha/react/i18n";
38
+ import { AlertCircle, RotateCcw, X } from "lucide-react";
39
+ import { type ReactNode, useEffect, useMemo, useState } from "react";
40
+
41
+ /**
42
+ * Detect a `z.string()` schema (incl. optional/nullable wrappers) so the
43
+ * auto-save effect can skip keystroke commits on text fields.
44
+ */
45
+ function isStringSchema(schema: unknown): boolean {
46
+ if (!schema || typeof schema !== "object") return false;
47
+ const s = schema as { type?: unknown; anyOf?: unknown[] };
48
+ if (s.type === "string") return true;
49
+ if (Array.isArray(s.anyOf)) return s.anyOf.some(isStringSchema);
50
+ return false;
51
+ }
52
+
53
+ /**
54
+ * Detect an enum schema (incl. optional/nullable wrappers). Enum fields
55
+ * render as a `<Select>`, so they must auto-commit on change like any
56
+ * other select — never get lumped in with free-text string fields.
57
+ */
58
+ function isEnumSchema(schema: unknown): boolean {
59
+ if (!schema || typeof schema !== "object") return false;
60
+ const s = schema as { enum?: unknown[]; anyOf?: unknown[] };
61
+ if (Array.isArray(s.enum)) return true;
62
+ if (Array.isArray(s.anyOf)) return s.anyOf.some(isEnumSchema);
63
+ return false;
64
+ }
65
+
66
+ /**
67
+ * Resolve the effective `<Control>` config for a field, merging the
68
+ * `fields` map with any per-field override carried on a `groups` entry —
69
+ * the same precedence `GroupBlock` applies when rendering.
70
+ */
71
+ function resolveControlConfig(
72
+ name: string,
73
+ fields: Record<string, unknown> | undefined,
74
+ groups: AutoFormGroup[] | undefined,
75
+ ): Record<string, unknown> {
76
+ const fromMap = (fields?.[name] as Record<string, unknown>) ?? {};
77
+ let fromGroup: Record<string, unknown> = {};
78
+ for (const group of groups ?? []) {
79
+ for (const field of group.fields) {
80
+ if (typeof field === "object" && field.name === name) {
81
+ fromGroup = field as Record<string, unknown>;
82
+ }
83
+ }
84
+ }
85
+ return { ...fromMap, ...fromGroup };
86
+ }
87
+
88
+ export interface AutoFormGroup {
89
+ /**
90
+ * Group title shown in the header.
91
+ */
92
+ title?: string;
93
+ /**
94
+ * Icon name (lucide) for the group header.
95
+ */
96
+ icon?: string;
97
+ /**
98
+ * Visibility predicate. Group is omitted when this returns false.
99
+ */
100
+ can?: () => boolean;
101
+ /**
102
+ * Field names from the form schema. Each renders as a `<Control>`.
103
+ * Use the object form `{ name, ...controlProps }` for per-field overrides
104
+ * (width, icon, custom, etc.).
105
+ */
106
+ fields: Array<
107
+ string | (Partial<Omit<ControlProps, "input">> & { name: string })
108
+ >;
109
+ }
110
+
111
+ export interface AutoFormAction {
112
+ label: string;
113
+ icon?: string;
114
+ variant?: "default" | "outline" | "ghost" | "destructive" | "secondary";
115
+ onClick: () => void | Promise<void>;
116
+ disabled?: boolean;
117
+ }
118
+
119
+ export interface AutoFormProps<T extends ZObject> {
120
+ /**
121
+ * Form model returned by `useForm()`. The schema drives every field.
122
+ */
123
+ form: FormModel<T>;
124
+
125
+ /**
126
+ * Header icon (lucide name).
127
+ */
128
+ icon?: string;
129
+ /**
130
+ * Header title.
131
+ */
132
+ title?: string;
133
+ /**
134
+ * Header description / subtitle.
135
+ */
136
+ description?: string;
137
+ /**
138
+ * Extra content rendered on the right of the header (e.g. a status badge).
139
+ * In `card` mode it renders as the `CardAction`; otherwise it is pushed to
140
+ * the right edge of the header box.
141
+ */
142
+ headerAction?: ReactNode;
143
+
144
+ /**
145
+ * Manual layout: list of groups, each with its own fields.
146
+ * If neither `groups` nor `autoGroup` is set, every top-level schema
147
+ * field is rendered in a single ungrouped column.
148
+ */
149
+ groups?: AutoFormGroup[];
150
+
151
+ /**
152
+ * Auto-group: scan the schema, primitive fields land in a "General"
153
+ * group, each object/array-of-objects becomes its own group.
154
+ */
155
+ autoGroup?: boolean | { defaultTitle?: string; defaultIcon?: string };
156
+
157
+ /**
158
+ * Per-field control overrides keyed by field name (also works without groups).
159
+ */
160
+ fields?: Partial<
161
+ Record<keyof T["shape"] & string, Partial<Omit<ControlProps, "input">>>
162
+ >;
163
+
164
+ /**
165
+ * Localize field labels the schema doesn't carry. When set, each field's
166
+ * label is resolved from the app dictionary via
167
+ * `tr(\`${i18nPrefix}.${fieldName}\`)` and its description via
168
+ * `tr(\`${i18nPrefix}.${fieldName}.desc\`)`, falling back to the
169
+ * schema-derived label/description when the key is absent. Lets a generic
170
+ * AutoForm (e.g. the parameters admin, whose schemas rarely set `title`)
171
+ * render translated labels without per-schema annotations. Explicit
172
+ * `fields[name].label` overrides still win.
173
+ */
174
+ i18nPrefix?: string;
175
+
176
+ /**
177
+ * Submit button label.
178
+ */
179
+ submitLabel?: string;
180
+ /**
181
+ * Hide built-in submit button.
182
+ */
183
+ noSubmit?: boolean;
184
+ /**
185
+ * Disable submit when form is pristine (not dirty).
186
+ */
187
+ disabledIfPristine?: boolean;
188
+ /**
189
+ * Disable the entire form (cascades to controls).
190
+ */
191
+ disabled?: boolean;
192
+
193
+ /**
194
+ * Cancel button — hidden when omitted.
195
+ */
196
+ onCancel?: () => void;
197
+ /**
198
+ * Skip the reset button in the bottom bar.
199
+ */
200
+ skipReset?: boolean;
201
+ /**
202
+ * Skip the entire bottom bar.
203
+ */
204
+ skipBottomBar?: boolean;
205
+
206
+ /**
207
+ * Extra action buttons in the bottom bar (left side).
208
+ */
209
+ actions?: AutoFormAction[];
210
+
211
+ /**
212
+ * Extra content rendered above the bottom bar.
213
+ */
214
+ footer?: ReactNode;
215
+
216
+ /**
217
+ * Extra classes applied to the form wrapper.
218
+ */
219
+ className?: string;
220
+
221
+ /**
222
+ * Override the column classes of each field group's grid. By default fields
223
+ * lay out on a fixed 12-column grid and each field's span is derived from
224
+ * width heuristics (`$control.width`, type, …).
225
+ *
226
+ * Pass responsive column classes — e.g.
227
+ * `"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"` — to get N equal columns per
228
+ * breakpoint instead; when set, every field occupies a single cell and the
229
+ * per-field width heuristics are ignored.
230
+ */
231
+ gridClassName?: string;
232
+
233
+ /**
234
+ * Wrap the form in a `<Card>`:
235
+ * - the header (icon + title/description) renders as the `CardHeader`,
236
+ * - the field groups render as the `CardContent`,
237
+ * - the action bar (cancel / reset / actions / submit) renders as the
238
+ * `CardFooter`.
239
+ *
240
+ * When omitted, the form uses its default chrome (a muted header box and a
241
+ * standalone bottom bar). The footer is hidden in `autoSave` mode just like
242
+ * the default bottom bar.
243
+ *
244
+ * Pass a string to override the `<Card>` className (e.g. `"rounded-none"` to
245
+ * make the card sit flush against neighbouring panes).
246
+ */
247
+ card?: boolean | string;
248
+
249
+ /**
250
+ * Fill the available height: the card stretches to `100%` of its container
251
+ * and the body (field groups) scrolls while the header and footer stay
252
+ * pinned. Only meaningful in `card` mode.
253
+ */
254
+ fill?: boolean;
255
+
256
+ /**
257
+ * Visual layout for every nested Control.
258
+ * - `"stack"` (default): label on top, control below — the classic form look.
259
+ * - `"row"`: settings-style — each control sits on its own line with the
260
+ * label/description on the left and the control on the right. Each
261
+ * group renders as a bordered card with horizontal dividers.
262
+ */
263
+ layout?: "stack" | "row";
264
+
265
+ /**
266
+ * Auto-commit edits instead of showing a Save button.
267
+ *
268
+ * When enabled, every field change schedules a debounced `form.submit()`
269
+ * and the bottom bar is hidden by default. Pass an options object to
270
+ * customize the debounce delay (default 600ms).
271
+ *
272
+ * The `handler` you pass to `useForm` is the auto-commit target — it
273
+ * runs once per quiescent edit, and any thrown error stops the loop
274
+ * until the user edits again.
275
+ */
276
+ autoSave?: boolean | { delay?: number };
277
+ }
278
+
279
+ /**
280
+ * Schema-driven form with optional grouping, header chrome, and bottom
281
+ * bar. Every input field is resolved through `<Control>`, so schemas
282
+ * carrying `$control` metadata configure themselves.
283
+ */
284
+ export function AutoForm<T extends ZObject>(props: AutoFormProps<T>) {
285
+ const { tr } = useI18n();
286
+ const { dirty, loading } = useFormState(props.form, ["dirty", "loading"]);
287
+ const inputs = props.form.input as Record<string, never>;
288
+
289
+ // `z.object({})` rather than a hand-made `{ properties: {} }`: the latter
290
+ // only ever worked because a prototype alias made `.properties` readable on
291
+ // a schema, so a fake object with that key passed for one.
292
+ const schema = (props.form.options.schema as ZObject) ?? z.object({});
293
+
294
+ // ── Auto-save ─────────────────────────────────────────────────────
295
+ // Text fields (string) are intentionally excluded: typing should not commit
296
+ // on every keystroke. They commit via Enter (native submit) or the inline
297
+ // tick button. Booleans / selects / uploads / etc. auto-commit on change.
298
+ const autoSave = props.autoSave;
299
+ const autoSaveDelay =
300
+ typeof autoSave === "object" ? (autoSave?.delay ?? 600) : 600;
301
+ const autoSaveEnabled = !!autoSave;
302
+ const alepha = useAlepha();
303
+ useEffect(() => {
304
+ if (!autoSaveEnabled) return;
305
+ let handle: ReturnType<typeof setTimeout> | undefined;
306
+ const off = alepha.events.on("form:change", (ev) => {
307
+ if (ev.id !== props.form.id) return;
308
+ if (ev.initial) return;
309
+ // FormModel paths look like "/title" or "/contacts/0/email". The
310
+ // top-level key is the first segment after the leading slash.
311
+ const top = ev.path.replace(/^\//, "").split("/")[0];
312
+ const fieldSchema = z.schema.shape(schema)[top];
313
+ const fieldConfig = resolveControlConfig(
314
+ top,
315
+ props.fields as Record<string, unknown> | undefined,
316
+ props.groups,
317
+ );
318
+ // Text fields (incl. optional/nullable wrappers) should NOT auto-commit
319
+ // on keystroke; they commit via Enter or the inline tick button.
320
+ // Uploads commit a uuid string when the upload finishes, and selects /
321
+ // comboboxes / segmented controls commit a discrete value on change —
322
+ // all of those MUST auto-save even though the field schema is a string.
323
+ const rendersAsSelect =
324
+ !!fieldConfig.select ||
325
+ !!fieldConfig.combobox ||
326
+ !!fieldConfig.segmented ||
327
+ fieldConfig.items != null ||
328
+ isEnumSchema(fieldSchema);
329
+ if (
330
+ !fieldConfig.upload &&
331
+ !rendersAsSelect &&
332
+ isStringSchema(fieldSchema)
333
+ )
334
+ return;
335
+ if (handle) clearTimeout(handle);
336
+ handle = setTimeout(() => props.form.submit(), autoSaveDelay);
337
+ });
338
+ return () => {
339
+ off();
340
+ if (handle) clearTimeout(handle);
341
+ };
342
+ }, [
343
+ alepha,
344
+ autoSaveEnabled,
345
+ autoSaveDelay,
346
+ props.form,
347
+ props.fields,
348
+ props.groups,
349
+ schema,
350
+ ]);
351
+ const skipBottomBar = props.skipBottomBar ?? autoSaveEnabled;
352
+
353
+ const resolvedGroups: AutoFormGroup[] = useMemo(() => {
354
+ if (props.groups) return props.groups.filter((g) => g.can?.() !== false);
355
+ if (props.autoGroup) {
356
+ const opts = typeof props.autoGroup === "object" ? props.autoGroup : {};
357
+ return autoGroupSchema(schema, { tr, ...opts });
358
+ }
359
+ return [
360
+ {
361
+ fields: Object.keys(z.schema.shape(schema)),
362
+ },
363
+ ];
364
+ }, [props.groups, props.autoGroup, schema]);
365
+
366
+ const HeaderIcon = props.icon ? iconFor(props.icon) : undefined;
367
+ const hasHeader = !!(
368
+ props.title ||
369
+ props.description ||
370
+ HeaderIcon ||
371
+ props.headerAction
372
+ );
373
+
374
+ const fieldGroups = (
375
+ <FormFieldLayoutProvider value={props.layout ?? "stack"}>
376
+ <FormFieldAutoSaveProvider value={autoSaveEnabled}>
377
+ {resolvedGroups.map((group, gi) => (
378
+ <GroupBlock
379
+ key={gi}
380
+ group={group}
381
+ inputs={inputs}
382
+ disabled={props.disabled}
383
+ fields={props.fields}
384
+ i18nPrefix={props.i18nPrefix}
385
+ multiGroup={resolvedGroups.length > 1}
386
+ layout={props.layout ?? "stack"}
387
+ gridClassName={props.gridClassName}
388
+ />
389
+ ))}
390
+ </FormFieldAutoSaveProvider>
391
+ </FormFieldLayoutProvider>
392
+ );
393
+
394
+ const bottomBarProps = {
395
+ form: props.form,
396
+ dirty,
397
+ loading,
398
+ disabled: props.disabled,
399
+ disabledIfPristine: props.disabledIfPristine,
400
+ submitLabel: props.submitLabel,
401
+ noSubmit: props.noSubmit,
402
+ onCancel: props.onCancel,
403
+ skipReset: props.skipReset,
404
+ actions: props.actions,
405
+ };
406
+
407
+ if (props.card) {
408
+ const cardClassName =
409
+ typeof props.card === "string" ? props.card : undefined;
410
+ return (
411
+ <form
412
+ {...props.form.props}
413
+ className={cn(
414
+ props.fill && "flex h-full min-h-0 flex-col",
415
+ props.className,
416
+ )}
417
+ >
418
+ <Card
419
+ className={cn(
420
+ props.fill && "min-h-0 flex-1",
421
+ // Header owns its bottom padding (pb-3); trim the card's top
422
+ // padding to match so header top/bottom are an even 12px.
423
+ hasHeader && "pt-3",
424
+ cardClassName,
425
+ )}
426
+ >
427
+ {hasHeader && (
428
+ // Explicit flex header (not shadcn CardHeader): CardHeader's grid
429
+ // adds a phantom second row + row-gap below the title whenever a
430
+ // CardDescription is nested, making the bottom padding larger than
431
+ // the top. A plain flex row keeps top/bottom padding symmetric.
432
+ <div
433
+ data-slot="card-header"
434
+ className="flex items-start justify-between gap-3 border-b px-4 pb-3"
435
+ >
436
+ <div className="flex items-center gap-3">
437
+ {HeaderIcon && (
438
+ <div className="bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-full">
439
+ <HeaderIcon className="size-5" />
440
+ </div>
441
+ )}
442
+ <div className="flex flex-col gap-0">
443
+ {props.title && <CardTitle>{props.title}</CardTitle>}
444
+ {props.description && (
445
+ <CardDescription>{props.description}</CardDescription>
446
+ )}
447
+ </div>
448
+ </div>
449
+ {props.headerAction && (
450
+ <div className="shrink-0">{props.headerAction}</div>
451
+ )}
452
+ </div>
453
+ )}
454
+ <CardContent
455
+ className={cn(
456
+ "flex flex-col gap-4",
457
+ props.fill && "min-h-0 flex-1 overflow-y-auto",
458
+ )}
459
+ >
460
+ {fieldGroups}
461
+ {props.footer}
462
+ </CardContent>
463
+ {!skipBottomBar && (
464
+ <CardFooter>
465
+ <BottomBar {...bottomBarProps} bare />
466
+ </CardFooter>
467
+ )}
468
+ </Card>
469
+ </form>
470
+ );
471
+ }
472
+
473
+ return (
474
+ <form {...props.form.props} className={props.className}>
475
+ <div className="flex flex-col gap-4">
476
+ {hasHeader && (
477
+ <div className="bg-muted/40 border rounded-md p-4 flex items-start gap-3">
478
+ {HeaderIcon && (
479
+ <div className="bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-full">
480
+ <HeaderIcon className="size-5" />
481
+ </div>
482
+ )}
483
+ <div className="flex flex-col gap-1">
484
+ {props.title && (
485
+ <h2 className="text-base font-semibold">{props.title}</h2>
486
+ )}
487
+ {props.description && (
488
+ <p className="text-muted-foreground text-sm">
489
+ {props.description}
490
+ </p>
491
+ )}
492
+ </div>
493
+ {props.headerAction && (
494
+ <div className="ml-auto">{props.headerAction}</div>
495
+ )}
496
+ </div>
497
+ )}
498
+
499
+ {fieldGroups}
500
+
501
+ {props.footer}
502
+
503
+ {!skipBottomBar && <BottomBar {...bottomBarProps} />}
504
+ </div>
505
+ </form>
506
+ );
507
+ }
508
+
509
+ // ──────────────────────────────────────────────────────────────────────
510
+
511
+ interface GroupBlockProps {
512
+ group: AutoFormGroup;
513
+ inputs: Record<string, never>;
514
+ fields?: Partial<Record<string, Partial<Omit<ControlProps, "input">>>>;
515
+ i18nPrefix?: string;
516
+ disabled?: boolean;
517
+ multiGroup?: boolean;
518
+ layout: "stack" | "row";
519
+ gridClassName?: string;
520
+ }
521
+
522
+ function GroupBlock(props: GroupBlockProps) {
523
+ const { group } = props;
524
+ const { tr } = useI18n();
525
+ const Icon = group.icon ? iconFor(group.icon) : undefined;
526
+
527
+ const items = group.fields
528
+ .map((entry) => {
529
+ const name = typeof entry === "string" ? entry : entry.name;
530
+ const override =
531
+ typeof entry === "object" ? (entry as Partial<ControlProps>) : {};
532
+ const input = props.inputs[name];
533
+ if (!input) return null;
534
+ const fromMap = props.fields?.[name] ?? {};
535
+ const merged: Partial<ControlProps> = {
536
+ ...fromMap,
537
+ ...override,
538
+ };
539
+ // i18nPrefix: fill label/description from the dictionary when neither
540
+ // the override nor the schema already provides one. A missing key
541
+ // makes `tr` echo the key back (an empty `default` is falsy, so the
542
+ // provider can't substitute it) — guard with `!== key` so an absent
543
+ // entry leaves the Control to fall back to `schema.title ??
544
+ // prettyName(field)`, preserving current behaviour.
545
+ if (props.i18nPrefix && merged.label === undefined) {
546
+ const key = `${props.i18nPrefix}.${name}`;
547
+ const label = tr(key, { default: "" });
548
+ if (label && label !== key) merged.label = label;
549
+ }
550
+ if (props.i18nPrefix && merged.description === undefined) {
551
+ const key = `${props.i18nPrefix}.${name}.desc`;
552
+ const desc = tr(key, { default: "" });
553
+ if (desc && desc !== key) merged.description = desc;
554
+ }
555
+ // Hand the extended prefix down so an object's children and an array's
556
+ // item fields resolve their own labels/help
557
+ // (`parameters.x.payg.dailyCapCents.desc`).
558
+ if (props.i18nPrefix && merged.i18nPrefix === undefined) {
559
+ merged.i18nPrefix = `${props.i18nPrefix}.${name}`;
560
+ }
561
+ return { name, input, props: merged };
562
+ })
563
+ .filter(Boolean) as Array<{
564
+ name: string;
565
+ input: BaseInputField;
566
+ props: Partial<ControlProps>;
567
+ }>;
568
+
569
+ if (!items.length && !props.multiGroup) return null;
570
+
571
+ // Naked group: no title, no icon → no card chrome (lets solo complex
572
+ // fields render with just their own header).
573
+ const isNaked = !group.title && !Icon;
574
+
575
+ // Row layout: each group becomes a divider-stacked card, every Control
576
+ // takes a full row through its own FormField row layout (via context).
577
+ if (props.layout === "row") {
578
+ return (
579
+ <div>
580
+ {group.title && (
581
+ <div className="mb-2 flex items-center gap-2 px-1">
582
+ {Icon && <Icon className="text-muted-foreground size-4" />}
583
+ <span className="text-sm font-medium">{group.title}</span>
584
+ </div>
585
+ )}
586
+ <div className="bg-card divide-y rounded-lg border shadow-sm">
587
+ {items.map((it) => (
588
+ <Control
589
+ key={it.name}
590
+ input={it.input}
591
+ {...it.props}
592
+ disabled={props.disabled || it.props.disabled}
593
+ />
594
+ ))}
595
+ </div>
596
+ </div>
597
+ );
598
+ }
599
+
600
+ const wrapperCls =
601
+ props.multiGroup && !isNaked ? "border rounded-md overflow-hidden" : "";
602
+
603
+ return (
604
+ <div className={wrapperCls}>
605
+ {props.multiGroup && !isNaked && (
606
+ <div className="bg-muted/40 flex items-center gap-2 border-b px-3 py-2">
607
+ {Icon && <Icon className="text-muted-foreground size-4" />}
608
+ {group.title && (
609
+ <span className="text-sm font-medium">{group.title}</span>
610
+ )}
611
+ </div>
612
+ )}
613
+ <div
614
+ className={cn(
615
+ "grid gap-3",
616
+ props.gridClassName ?? "grid-cols-12",
617
+ !isNaked && "p-3",
618
+ )}
619
+ >
620
+ {items.map((it) => (
621
+ <div
622
+ key={it.name}
623
+ className={
624
+ // Responsive grid: each field is one cell. Default: 12-col span
625
+ // from width heuristics. A caller-supplied grid keeps its own
626
+ // column count for scalars, but COMPLEX fields (an object card,
627
+ // a list of object editors) still claim the whole row —
628
+ // squeezing one into a third of a row is unreadable, and the
629
+ // heuristic already knows which those are (width 100).
630
+ props.gridClassName
631
+ ? widthFor(it.input, it.props.width as number | undefined) >=
632
+ 100
633
+ ? "col-span-full"
634
+ : undefined
635
+ : spanClass(
636
+ widthFor(it.input, it.props.width as number | undefined),
637
+ )
638
+ }
639
+ >
640
+ <Control
641
+ input={it.input}
642
+ {...it.props}
643
+ disabled={props.disabled || it.props.disabled}
644
+ />
645
+ </div>
646
+ ))}
647
+ </div>
648
+ </div>
649
+ );
650
+ }
651
+
652
+ // ──────────────────────────────────────────────────────────────────────
653
+
654
+ interface BottomBarProps {
655
+ form: FormModel<ZObject>;
656
+ dirty?: boolean;
657
+ loading?: boolean;
658
+ disabled?: boolean;
659
+ disabledIfPristine?: boolean;
660
+ submitLabel?: string;
661
+ noSubmit?: boolean;
662
+ onCancel?: () => void;
663
+ skipReset?: boolean;
664
+ actions?: AutoFormAction[];
665
+ /**
666
+ * Drop the standalone chrome (border / rounded / background / padding) so
667
+ * the bar slots into a `CardFooter`, which provides that chrome itself.
668
+ */
669
+ bare?: boolean;
670
+ }
671
+
672
+ function BottomBar(props: BottomBarProps) {
673
+ const { tr } = useI18n();
674
+ return (
675
+ <div
676
+ className={
677
+ props.bare
678
+ ? "flex w-full items-center gap-2"
679
+ : "bg-card flex items-center gap-2 border rounded-md p-2"
680
+ }
681
+ >
682
+ {props.onCancel && (
683
+ <Button
684
+ type="button"
685
+ variant="ghost"
686
+ onClick={props.onCancel}
687
+ disabled={props.disabled}
688
+ >
689
+ <X className="size-4 mr-1" />
690
+ {tr("autoForm.cancel", { default: "Cancel" })}
691
+ </Button>
692
+ )}
693
+ {!props.skipReset && (
694
+ <Button
695
+ type="button"
696
+ variant="ghost"
697
+ onClick={() => props.form.reset()}
698
+ disabled={props.disabled || !props.dirty}
699
+ >
700
+ <RotateCcw className="size-4 mr-1" />
701
+ {tr("autoForm.reset", { default: "Reset" })}
702
+ </Button>
703
+ )}
704
+ {props.actions?.map((action, i) => {
705
+ const Icon = action.icon ? iconFor(action.icon) : undefined;
706
+ return (
707
+ <Button
708
+ key={i}
709
+ type="button"
710
+ variant={action.variant ?? "ghost"}
711
+ onClick={() => action.onClick()}
712
+ disabled={props.disabled || action.disabled}
713
+ >
714
+ {Icon && <Icon className="size-4 mr-1" />}
715
+ {action.label}
716
+ </Button>
717
+ );
718
+ })}
719
+
720
+ <div className="ml-auto flex items-center gap-2">
721
+ <FormErrorPopover form={props.form} />
722
+ {!props.noSubmit && (
723
+ <Button
724
+ type="submit"
725
+ loading={props.loading}
726
+ disabled={
727
+ props.disabled || (props.disabledIfPristine && !props.dirty)
728
+ }
729
+ >
730
+ {props.submitLabel ?? tr("autoForm.save", { default: "Save" })}
731
+ </Button>
732
+ )}
733
+ </div>
734
+ </div>
735
+ );
736
+ }
737
+
738
+ // ──────────────────────────────────────────────────────────────────────
739
+
740
+ interface FormErrorPopoverProps {
741
+ form: FormModel<ZObject>;
742
+ }
743
+
744
+ function FormErrorPopover(props: FormErrorPopoverProps) {
745
+ const { error } = useFormState(props.form, ["error"]);
746
+ const { tr } = useI18n();
747
+ const [open, setOpen] = useState(false);
748
+ // close popover when error clears
749
+ useEffect(() => {
750
+ if (!error && open) setOpen(false);
751
+ }, [error, open]);
752
+
753
+ if (!error) return null;
754
+
755
+ const items = collectErrors(error);
756
+
757
+ return (
758
+ <Popover open={open} onOpenChange={setOpen}>
759
+ <PopoverTrigger
760
+ render={
761
+ <Button
762
+ type="button"
763
+ variant="ghost"
764
+ size="icon"
765
+ aria-label={tr("autoForm.errors", { default: "Form errors" })}
766
+ className="text-destructive"
767
+ />
768
+ }
769
+ >
770
+ <AlertCircle className="size-4" />
771
+ </PopoverTrigger>
772
+ <PopoverContent align="end" className="w-80 p-2">
773
+ <p className="text-destructive text-sm font-medium px-2 py-1">
774
+ {items.length === 1
775
+ ? tr("autoForm.error", { default: "Error" })
776
+ : tr("autoForm.errors", { default: "Errors" })}
777
+ </p>
778
+ <ul className="flex flex-col gap-1">
779
+ {items.map((it, i) => (
780
+ <li key={i}>
781
+ <button
782
+ type="button"
783
+ onClick={() => focusError(it.path, props.form.id)}
784
+ className="hover:bg-accent w-full rounded text-left text-xs px-2 py-1"
785
+ >
786
+ <span className="font-medium">
787
+ {it.path || tr("autoForm.formLabel", { default: "Form" })}
788
+ </span>
789
+ <span className="text-muted-foreground"> — {it.message}</span>
790
+ </button>
791
+ </li>
792
+ ))}
793
+ </ul>
794
+ </PopoverContent>
795
+ </Popover>
796
+ );
797
+ }
798
+
799
+ interface ErrorItem {
800
+ path: string;
801
+ message: string;
802
+ }
803
+
804
+ const collectErrors = (error: Error): ErrorItem[] => {
805
+ const anyErr = error as Error & {
806
+ value?: { message?: string; path?: string };
807
+ };
808
+ const path = anyErr.value?.path ?? "";
809
+ const message = anyErr.value?.message ?? error.message ?? "Invalid";
810
+ return [{ path, message }];
811
+ };
812
+
813
+ const focusError = (path: string, formId: string) => {
814
+ const fieldName = path.replace(/^\//, "").replace(/\//g, ".");
815
+ if (!fieldName) return;
816
+ const el =
817
+ document.getElementById(`${formId}-${fieldName}`) ??
818
+ document.querySelector<HTMLElement>(`[name="${fieldName}"]`);
819
+ el?.focus();
820
+ };
821
+
822
+ // ──────────────────────────────────────────────────────────────────────
823
+
824
+ const autoGroupSchema = (
825
+ schema: ZObject,
826
+ opts: {
827
+ defaultTitle?: string;
828
+ defaultIcon?: string;
829
+ /** Translator for the fallback group title (the helper is hook-free). */
830
+ tr?: (key: string, options?: { default?: string }) => string;
831
+ },
832
+ ): AutoFormGroup[] => {
833
+ const general: AutoFormGroup = {
834
+ title:
835
+ opts.defaultTitle ??
836
+ opts.tr?.("autoForm.general", { default: "General" }) ??
837
+ "General",
838
+ icon: opts.defaultIcon ?? "cog",
839
+ fields: [],
840
+ };
841
+ const groups: AutoFormGroup[] = [];
842
+
843
+ for (const [key, prop] of Object.entries(z.schema.shape(schema))) {
844
+ const p = prop as {
845
+ type?: string;
846
+ items?: unknown;
847
+ element?: unknown;
848
+ };
849
+ const isObject = p.type === "object";
850
+ // An array of a UNION of objects is a complex field too — without this it
851
+ // lands in the "General" grid and gets a third of a row to render a list
852
+ // of object editors in.
853
+ const isArrayOfObjects =
854
+ p.type === "array" && isObjectOrUnionOfObjects(p.element);
855
+ if (isObject || isArrayOfObjects) {
856
+ // Solo complex fields render their own header (label + description +
857
+ // chevron + add/init), so we skip the group bar to avoid a
858
+ // duplicate title row.
859
+ groups.push({ fields: [key] });
860
+ } else {
861
+ general.fields.push(key);
862
+ }
863
+ }
864
+
865
+ if (general.fields.length === 0) return groups;
866
+ return [general, ...groups];
867
+ };