@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,700 @@
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 { Button } from "@alepha/ui/components/ui/button";
10
+ import {
11
+ Dialog,
12
+ DialogContent,
13
+ DialogDescription,
14
+ DialogFooter,
15
+ DialogHeader,
16
+ DialogTitle,
17
+ } from "@alepha/ui/components/ui/dialog";
18
+ import { type ZObject, type ZType, z } from "alepha";
19
+ import { useAlepha } from "alepha/react";
20
+ import {
21
+ type BaseInputField,
22
+ parseField,
23
+ unionVariants,
24
+ useFormState,
25
+ } from "alepha/react/form";
26
+ import { useI18n } from "alepha/react/i18n";
27
+ import {
28
+ ArrowDown,
29
+ ArrowUp,
30
+ ChevronDown,
31
+ ChevronRight,
32
+ Plus,
33
+ Trash2,
34
+ } from "lucide-react";
35
+ import { useCallback, useEffect, useRef, useState } from "react";
36
+ import {
37
+ childI18nPrefix,
38
+ resolveFieldI18n,
39
+ } from "../control-base/field-i18n.ts";
40
+
41
+ interface ArrayItem {
42
+ key: number;
43
+ value: unknown;
44
+ }
45
+
46
+ export interface ControlArrayProps {
47
+ /**
48
+ * Bound array `InputField` from `useForm`.
49
+ */
50
+ input: BaseInputField;
51
+ /**
52
+ * Dictionary prefix for the item fields: each reads `<prefix>.<field>` and
53
+ * `<prefix>.<field>.desc` (the index is not part of the key — every row of
54
+ * the list shares one label).
55
+ */
56
+ i18nPrefix?: string;
57
+ /**
58
+ * Field label. Falls back to schema `title`.
59
+ */
60
+ label?: string;
61
+ /**
62
+ * Helper text shown below the array.
63
+ */
64
+ description?: string;
65
+ /**
66
+ * Minimum number of items (Add button disables when reached).
67
+ */
68
+ min?: number;
69
+ /**
70
+ * Maximum number of items (Add button disables when reached).
71
+ */
72
+ max?: number;
73
+ /**
74
+ * Override the "Add item" button label.
75
+ */
76
+ addLabel?: string;
77
+ /**
78
+ * Number of grid columns for each item's inner fields.
79
+ */
80
+ columns?: 1 | 2 | 3 | 4;
81
+ /**
82
+ * "fieldset" wraps in a bordered container with legend; "plain" renders items only.
83
+ */
84
+ variant?: "fieldset" | "plain";
85
+ /**
86
+ * Per-field `<Control>` overrides for items, keyed by inner field name.
87
+ */
88
+ controlProps?: Record<string, Partial<Omit<ControlProps, "input">>>;
89
+ /**
90
+ * Override props applied to every item (when items are primitive, not objects).
91
+ */
92
+ itemControlProps?: Partial<Omit<ControlProps, "input">>;
93
+ /**
94
+ * Disable add/remove and all inner controls.
95
+ */
96
+ disabled?: boolean;
97
+
98
+ /**
99
+ * Default expanded state. @default true
100
+ */
101
+ defaultExpanded?: boolean;
102
+
103
+ /**
104
+ * Confirm before deleting an item. Pass `true` for default copy or an
105
+ * object to override title/message.
106
+ */
107
+ confirmDelete?: boolean | { title?: string; message?: string };
108
+
109
+ /**
110
+ * Compute the visible label for each item header (and tab name in tabs mode).
111
+ */
112
+ renderTabName?: (i: number, value: unknown) => string;
113
+
114
+ /**
115
+ * Force tabs mode even for short arrays. Default heuristic: items > 4 OR nested object/array fields.
116
+ */
117
+ forceTabs?: boolean;
118
+ }
119
+
120
+ const colsClass: Record<number, string> = {
121
+ 1: "grid-cols-1",
122
+ 2: "grid-cols-2",
123
+ 3: "grid-cols-3",
124
+ 4: "grid-cols-4",
125
+ };
126
+
127
+ const useArrayItems = (input: BaseInputField | undefined) => {
128
+ const alepha = useAlepha();
129
+ const counter = useRef(0);
130
+ const [items, setItemsState] = useState<ArrayItem[]>(() => {
131
+ const initial = input?.initialValue;
132
+ return Array.isArray(initial)
133
+ ? initial.map((value) => ({ key: counter.current++, value }))
134
+ : [];
135
+ });
136
+
137
+ const sync = useCallback((next: unknown[] | undefined) => {
138
+ if (!Array.isArray(next)) {
139
+ setItemsState([]);
140
+ return;
141
+ }
142
+ setItemsState((prev) => {
143
+ if (
144
+ prev.length === next.length &&
145
+ prev.every((it, i) => it.value === next[i])
146
+ ) {
147
+ return prev;
148
+ }
149
+ counter.current = 0;
150
+ return next.map((value) => ({ key: counter.current++, value }));
151
+ });
152
+ }, []);
153
+
154
+ useEffect(() => {
155
+ if (!input?.form) return;
156
+ const formId = input.form.id;
157
+ const path = input.path;
158
+ return alepha.events.on("form:change", (e) => {
159
+ if (e.id === formId && e.path === path) sync(e.value as unknown[]);
160
+ });
161
+ }, [alepha, input, sync]);
162
+
163
+ const setItems = useCallback(
164
+ (next: ArrayItem[]) => {
165
+ setItemsState(next);
166
+ input?.set(next.map((it) => it.value));
167
+ },
168
+ [input],
169
+ );
170
+
171
+ return { items, setItems, nextKey: () => counter.current++ };
172
+ };
173
+
174
+ /**
175
+ * Discriminated-union support for item schemas.
176
+ *
177
+ * `z.array(z.union([...objects]))` is how a heterogeneous list is spelled. The
178
+ * variants almost always differ by one literal property (`kind`, `type`, …),
179
+ * which is enough to (a) tell which variant an existing item is and (b) label
180
+ * the choice offered when adding one. Everything below degrades quietly: no
181
+ * union, or no discriminant, and the array behaves exactly as before.
182
+ */
183
+ const objectVariants = (itemSchema: ZType): ZObject[] | null => {
184
+ const variants = unionVariants(itemSchema);
185
+ if (!variants?.length) return null;
186
+ const objects = variants
187
+ .map((variant) => z.schema.unwrap(variant))
188
+ .filter((variant) => z.schema.isObject(variant)) as ZObject[];
189
+ return objects.length === variants.length ? objects : null;
190
+ };
191
+
192
+ /** The property whose value identifies the variant (a literal in every variant). */
193
+ const discriminantOf = (variants: ZObject[]): string | null => {
194
+ const [first] = variants;
195
+ if (!first) return null;
196
+ for (const name of Object.keys(z.schema.shape(first))) {
197
+ const values = variants.map((variant) =>
198
+ literalValueOf(z.schema.shape(variant)[name]),
199
+ );
200
+ if (values.every((value) => typeof value === "string")) {
201
+ const unique = new Set(values as string[]);
202
+ if (unique.size === variants.length) return name;
203
+ }
204
+ }
205
+ return null;
206
+ };
207
+
208
+ /** The single allowed value of a literal/const schema, if it is one. */
209
+ const literalValueOf = (schema: unknown): unknown => {
210
+ if (!schema) return undefined;
211
+ const inner = z.schema.unwrap(schema as ZType) as {
212
+ const?: unknown;
213
+ values?: unknown[] | Set<unknown>;
214
+ _zod?: { def?: { values?: unknown[] } };
215
+ };
216
+ if (inner?.const !== undefined) return inner.const;
217
+ // zod spells a literal's allowed values as `_zod.def.values` (an array);
218
+ // the public `.values` is a Set, so normalise both.
219
+ const raw = inner?._zod?.def?.values ?? inner?.values;
220
+ const values =
221
+ raw instanceof Set ? [...raw] : Array.isArray(raw) ? raw : undefined;
222
+ return values?.length === 1 ? values[0] : undefined;
223
+ };
224
+
225
+ /** Label for a variant: its discriminant value, else its index. */
226
+ const variantLabel = (
227
+ variant: ZObject,
228
+ discriminant: string | null,
229
+ index: number,
230
+ ): string => {
231
+ const value = discriminant
232
+ ? literalValueOf(z.schema.shape(variant)[discriminant])
233
+ : undefined;
234
+ return typeof value === "string" ? value : `#${index + 1}`;
235
+ };
236
+
237
+ const buildItemInput = (
238
+ parent: BaseInputField,
239
+ schema: ZType,
240
+ index: number,
241
+ value: unknown,
242
+ onChange: (v: unknown) => void,
243
+ ): BaseInputField => ({
244
+ schema,
245
+ path: `${parent.path}/${index}`,
246
+ required: false,
247
+ form: parent.form,
248
+ initialValue: value,
249
+ props: {
250
+ id: `${parent.props.id}-${index}`,
251
+ name: `${parent.props.name}[${index}]`,
252
+ },
253
+ set: onChange,
254
+ });
255
+
256
+ const buildFieldInput = (
257
+ parent: BaseInputField,
258
+ itemSchema: ZObject,
259
+ fieldName: string,
260
+ index: number,
261
+ itemValue: Record<string, unknown> | undefined,
262
+ onFieldChange: (field: string, value: unknown) => void,
263
+ ): BaseInputField => ({
264
+ schema: z.schema.shape(itemSchema)[fieldName],
265
+ path: `${parent.path}/${index}/${fieldName}`,
266
+ required: z.schema.requiredKeys(itemSchema).includes(fieldName),
267
+ form: parent.form,
268
+ initialValue: itemValue?.[fieldName],
269
+ props: {
270
+ id: `${parent.props.id}-${index}-${fieldName}`,
271
+ name: `${parent.props.name}[${index}].${fieldName}`,
272
+ },
273
+ set: (v: unknown) => onFieldChange(fieldName, v),
274
+ });
275
+
276
+ export function ControlArray(props: ControlArrayProps) {
277
+ const form = useFormState(props.input, ["error"]);
278
+ const { tr } = useI18n();
279
+ const { items, setItems, nextKey } = useArrayItems(props.input);
280
+ const [expanded, setExpanded] = useState(props.defaultExpanded ?? true);
281
+ const [activeTab, setActiveTab] = useState(0);
282
+ const [pendingDelete, setPendingDelete] = useState<number | null>(null);
283
+
284
+ if (!props.input?.props) return null;
285
+
286
+ const meta = parseField(props.input, {
287
+ label: props.label,
288
+ description: props.description,
289
+ error: form.error,
290
+ });
291
+
292
+ const schema = props.input.schema;
293
+ // `isArray`, not `"items" in schema`: that spelling tested for a prototype
294
+ // alias rather than for an array schema, so it answered false once the alias
295
+ // went away — and the whole control rendered nothing, Add button included.
296
+ if (!z.schema.isArray(schema)) return null;
297
+
298
+ // `z.schema.element`, not `.items`: the latter only ever resolved through a
299
+ // prototype alias on ZodArray, so it silently became `undefined` — and with
300
+ // no item schema the control renders neither fields nor tabs.
301
+ const itemSchema = z.schema.element(schema) as ZType;
302
+ const variants = objectVariants(itemSchema);
303
+ const discriminant = variants ? discriminantOf(variants) : null;
304
+
305
+ /**
306
+ * The object schema to edit an item with. For a union that is the variant the
307
+ * item's discriminant points at (first variant as a fallback, e.g. a freshly
308
+ * added item), so each row renders exactly its own fields.
309
+ */
310
+ const schemaForValue = (value: unknown): ZObject | null => {
311
+ if (!variants) {
312
+ // `isObject`, not `"properties" in itemSchema`: the latter tested for a
313
+ // prototype alias, so it answered false as soon as the alias went away.
314
+ return z.schema.isObject(itemSchema) ? (itemSchema as ZObject) : null;
315
+ }
316
+ if (discriminant && value && typeof value === "object") {
317
+ const tag = (value as Record<string, unknown>)[discriminant];
318
+ const match = variants.find(
319
+ (variant) =>
320
+ literalValueOf(z.schema.shape(variant)[discriminant]) === tag,
321
+ );
322
+ if (match) return match;
323
+ }
324
+ return variants[0] ?? null;
325
+ };
326
+
327
+ const objectItemSchema = schemaForValue(items[0]?.value);
328
+ const fieldNames = objectItemSchema
329
+ ? Object.keys(z.schema.shape(objectItemSchema))
330
+ : [];
331
+
332
+ // Schema-driven max/min if present
333
+ const schemaMax = (schema as { maxItems?: number }).maxItems;
334
+ const schemaMin = (schema as { minItems?: number }).minItems;
335
+ const min = props.min ?? schemaMin ?? 0;
336
+ const max = props.max ?? schemaMax ?? Number.POSITIVE_INFINITY;
337
+ const columns = props.columns ?? 1;
338
+
339
+ // Tabs heuristic: forced or nested complex item or many items
340
+ const hasComplexFields = objectItemSchema
341
+ ? fieldNames.some((n) => {
342
+ const p = z.schema.shape(objectItemSchema)[n] as { type?: string };
343
+ return p?.type === "object" || p?.type === "array";
344
+ })
345
+ : false;
346
+ const useTabs =
347
+ props.forceTabs ||
348
+ (objectItemSchema && (items.length > 4 || hasComplexFields));
349
+
350
+ const handleAdd = (variantIndex = 0) => {
351
+ if (items.length >= max) return;
352
+ const shape = variants ? variants[variantIndex] : objectItemSchema;
353
+ let value: unknown;
354
+ if (shape) {
355
+ value = {};
356
+ for (const [k, p] of Object.entries(z.schema.shape(shape))) {
357
+ const def = z.schema.getDefault(p);
358
+ if (def !== undefined) (value as Record<string, unknown>)[k] = def;
359
+ // Stamp the discriminant so the new item resolves to its variant.
360
+ const literal = literalValueOf(p);
361
+ if (literal !== undefined)
362
+ (value as Record<string, unknown>)[k] = literal;
363
+ }
364
+ } else {
365
+ value = "";
366
+ }
367
+ setItems([...items, { key: nextKey(), value }]);
368
+ if (useTabs) setActiveTab(items.length);
369
+ };
370
+
371
+ const handleRemove = (index: number) => {
372
+ if (items.length <= min) return;
373
+ if (props.confirmDelete) {
374
+ setPendingDelete(index);
375
+ return;
376
+ }
377
+ doRemove(index);
378
+ };
379
+
380
+ const doRemove = (index: number) => {
381
+ setItems(items.filter((_, i) => i !== index));
382
+ if (useTabs)
383
+ setActiveTab(Math.max(0, Math.min(activeTab, items.length - 2)));
384
+ };
385
+
386
+ const handleMove = (index: number, direction: -1 | 1) => {
387
+ const target = index + direction;
388
+ if (target < 0 || target >= items.length) return;
389
+ const next = [...items];
390
+ [next[index], next[target]] = [next[target], next[index]];
391
+ setItems(next);
392
+ if (useTabs) setActiveTab(target);
393
+ };
394
+
395
+ const updateItem = (index: number, value: unknown) => {
396
+ const next = [...items];
397
+ next[index] = { ...next[index], value };
398
+ setItems(next);
399
+ };
400
+
401
+ const updateField = (index: number, field: string, value: unknown) => {
402
+ const next = [...items];
403
+ const current = (next[index].value as Record<string, unknown>) ?? {};
404
+ next[index] = { ...next[index], value: { ...current, [field]: value } };
405
+ setItems(next);
406
+ };
407
+
408
+ const tabName = (i: number): string => {
409
+ if (props.renderTabName) {
410
+ try {
411
+ return props.renderTabName(i, items[i]?.value);
412
+ } catch {
413
+ // fall through
414
+ }
415
+ }
416
+ const value = items[i]?.value as Record<string, unknown> | undefined;
417
+ const tag = discriminant ? value?.[discriminant] : undefined;
418
+ if (typeof tag === "string") return `${tag} #${i + 1}`;
419
+ return `${meta.label} #${i + 1}`;
420
+ };
421
+
422
+ const renderItemBody = (item: ArrayItem, index: number) => {
423
+ // Resolved per item: in a union each row may be a different variant.
424
+ const itemObjectSchema = schemaForValue(item.value);
425
+ const itemFieldNames = itemObjectSchema
426
+ ? Object.keys(z.schema.shape(itemObjectSchema))
427
+ : [];
428
+ return itemObjectSchema ? (
429
+ <div className={`grid gap-3 ${colsClass[columns]}`}>
430
+ {itemFieldNames.map((name) => {
431
+ const fieldProps = {
432
+ ...(props.controlProps?.[name] ?? {}),
433
+ ...resolveFieldI18n(
434
+ tr as never,
435
+ props.i18nPrefix,
436
+ name,
437
+ props.controlProps?.[name] ?? {},
438
+ ),
439
+ i18nPrefix: childI18nPrefix(props.i18nPrefix, name),
440
+ };
441
+ // The discriminant decides the item's SHAPE — editing it would
442
+ // invalidate every sibling field, so it is shown read-only.
443
+ const isDiscriminant = !!variants && name === discriminant;
444
+ const fieldInput = buildFieldInput(
445
+ props.input,
446
+ itemObjectSchema,
447
+ name,
448
+ index,
449
+ item.value as Record<string, unknown>,
450
+ (f, v) => updateField(index, f, v),
451
+ );
452
+ return (
453
+ <Control
454
+ key={name}
455
+ input={fieldInput}
456
+ disabled={props.disabled || isDiscriminant}
457
+ {...fieldProps}
458
+ />
459
+ );
460
+ })}
461
+ </div>
462
+ ) : (
463
+ <Control
464
+ input={buildItemInput(props.input, itemSchema, index, item.value, (v) =>
465
+ updateItem(index, v),
466
+ )}
467
+ disabled={props.disabled}
468
+ {...props.itemControlProps}
469
+ />
470
+ );
471
+ };
472
+
473
+ const itemActions = (index: number) => (
474
+ <div className="flex shrink-0 flex-col gap-1">
475
+ <Button
476
+ type="button"
477
+ variant="ghost"
478
+ size="icon"
479
+ className="size-7"
480
+ disabled={props.disabled || index === 0 || items.length < 2}
481
+ onClick={() => handleMove(index, -1)}
482
+ aria-label={tr("controlArray.moveUp", { default: "Move up" })}
483
+ >
484
+ <ArrowUp className="size-3.5" />
485
+ </Button>
486
+ <Button
487
+ type="button"
488
+ variant="ghost"
489
+ size="icon"
490
+ className="size-7"
491
+ disabled={props.disabled || items.length <= min}
492
+ onClick={() => handleRemove(index)}
493
+ aria-label={tr("controlArray.remove", { default: "Remove" })}
494
+ >
495
+ <Trash2 className="size-3.5" />
496
+ </Button>
497
+ <Button
498
+ type="button"
499
+ variant="ghost"
500
+ size="icon"
501
+ className="size-7"
502
+ disabled={
503
+ props.disabled || index === items.length - 1 || items.length < 2
504
+ }
505
+ onClick={() => handleMove(index, 1)}
506
+ aria-label={tr("controlArray.moveDown", { default: "Move down" })}
507
+ >
508
+ <ArrowDown className="size-3.5" />
509
+ </Button>
510
+ </div>
511
+ );
512
+
513
+ const flatList = (
514
+ <div className="flex flex-col gap-2">
515
+ {items.map((item, index) => (
516
+ <div
517
+ key={item.key}
518
+ className="bg-muted/30 flex items-start gap-2 rounded-md border p-3"
519
+ >
520
+ <div className="flex-1 min-w-0">{renderItemBody(item, index)}</div>
521
+ {itemActions(index)}
522
+ </div>
523
+ ))}
524
+ </div>
525
+ );
526
+
527
+ const tabs = useTabs && items.length > 0 && (
528
+ <div className="flex flex-col gap-2">
529
+ <div className="flex flex-wrap gap-1 border-b pb-1">
530
+ {items.map((item, i) => (
531
+ <Button
532
+ key={item.key}
533
+ type="button"
534
+ variant={i === activeTab ? "default" : "ghost"}
535
+ size="sm"
536
+ onClick={() => setActiveTab(i)}
537
+ >
538
+ {tabName(i)}
539
+ </Button>
540
+ ))}
541
+ </div>
542
+ {items[activeTab] && (
543
+ <div className="bg-muted/30 flex items-start gap-2 rounded-md border p-3">
544
+ <div className="flex-1 min-w-0">
545
+ {renderItemBody(items[activeTab], activeTab)}
546
+ </div>
547
+ {itemActions(activeTab)}
548
+ </div>
549
+ )}
550
+ </div>
551
+ );
552
+
553
+ const list = (
554
+ <div className="flex flex-col gap-2">{useTabs ? tabs : flatList}</div>
555
+ );
556
+
557
+ const headerControls = (
558
+ <div className="flex items-start gap-3">
559
+ {variants && variants.length > 1 ? (
560
+ // A union offers a choice of shapes: one Add button per variant,
561
+ // labelled by its discriminant ("single", "period_pass", …).
562
+ <div className="flex shrink-0 flex-wrap gap-1">
563
+ {variants.map((variant, index) => (
564
+ <Button
565
+ key={variantLabel(variant, discriminant, index)}
566
+ type="button"
567
+ variant="outline"
568
+ size="sm"
569
+ className="h-8"
570
+ disabled={props.disabled || items.length >= max}
571
+ onClick={() => handleAdd(index)}
572
+ >
573
+ <Plus className="size-3.5" />
574
+ {variantLabel(variant, discriminant, index)}
575
+ </Button>
576
+ ))}
577
+ </div>
578
+ ) : (
579
+ <Button
580
+ type="button"
581
+ variant="outline"
582
+ size="icon"
583
+ className="size-8 shrink-0"
584
+ disabled={props.disabled || items.length >= max}
585
+ onClick={() => handleAdd()}
586
+ aria-label={
587
+ props.addLabel ?? tr("controlArray.add", { default: "Add" })
588
+ }
589
+ >
590
+ <Plus className="size-4" />
591
+ </Button>
592
+ )}
593
+ <div className="flex flex-col min-w-0 flex-1">
594
+ <div className="text-sm font-medium leading-tight">
595
+ {meta.label}
596
+ {meta.required && <span className="text-destructive ml-0.5">*</span>}
597
+ <span className="text-muted-foreground ml-2 text-xs">
598
+ ({items.length})
599
+ </span>
600
+ </div>
601
+ {meta.description && (
602
+ <p className="text-muted-foreground text-xs leading-tight">
603
+ {meta.description}
604
+ </p>
605
+ )}
606
+ {meta.error && (
607
+ <p className="text-destructive text-xs leading-tight">{meta.error}</p>
608
+ )}
609
+ </div>
610
+ {items.length > 0 && (
611
+ <Button
612
+ type="button"
613
+ variant="ghost"
614
+ size="icon"
615
+ className="size-8 shrink-0"
616
+ aria-label={
617
+ expanded
618
+ ? tr("controlArray.collapse", { default: "Collapse" })
619
+ : tr("controlArray.expand", { default: "Expand" })
620
+ }
621
+ onClick={() => setExpanded((e) => !e)}
622
+ >
623
+ {expanded ? (
624
+ <ChevronDown className="size-4" />
625
+ ) : (
626
+ <ChevronRight className="size-4" />
627
+ )}
628
+ </Button>
629
+ )}
630
+ </div>
631
+ );
632
+
633
+ const confirmContent = (() => {
634
+ if (pendingDelete == null) return null;
635
+ const cd = props.confirmDelete;
636
+ const title =
637
+ typeof cd === "object"
638
+ ? (cd.title ??
639
+ tr("controlArray.deleteTitle", { default: "Delete item" }))
640
+ : tr("controlArray.deleteTitle", { default: "Delete item" });
641
+ const message =
642
+ typeof cd === "object"
643
+ ? (cd.message ??
644
+ tr("controlArray.deleteConfirm", {
645
+ default: "Are you sure you want to delete this item?",
646
+ }))
647
+ : tr("controlArray.deleteConfirm", {
648
+ default: "Are you sure you want to delete this item?",
649
+ });
650
+ return (
651
+ <Dialog
652
+ open={pendingDelete != null}
653
+ onOpenChange={(v) => !v && setPendingDelete(null)}
654
+ >
655
+ <DialogContent>
656
+ <DialogHeader>
657
+ <DialogTitle>{title}</DialogTitle>
658
+ <DialogDescription>{message}</DialogDescription>
659
+ </DialogHeader>
660
+ <DialogFooter>
661
+ <Button variant="ghost" onClick={() => setPendingDelete(null)}>
662
+ {tr("controlArray.cancel", { default: "Cancel" })}
663
+ </Button>
664
+ <Button
665
+ variant="destructive"
666
+ onClick={() => {
667
+ doRemove(pendingDelete);
668
+ setPendingDelete(null);
669
+ }}
670
+ >
671
+ {tr("controlArray.delete", { default: "Delete" })}
672
+ </Button>
673
+ </DialogFooter>
674
+ </DialogContent>
675
+ </Dialog>
676
+ );
677
+ })();
678
+
679
+ if (props.variant === "plain") {
680
+ return (
681
+ <div className="flex flex-col gap-2">
682
+ {headerControls}
683
+ {expanded && items.length > 0 && list}
684
+ {confirmContent}
685
+ </div>
686
+ );
687
+ }
688
+
689
+ return (
690
+ <fieldset
691
+ className={`rounded-md border p-3 ${
692
+ meta.error ? "border-destructive" : "border-border"
693
+ }`}
694
+ >
695
+ {headerControls}
696
+ {expanded && items.length > 0 && <div className="mt-3">{list}</div>}
697
+ {confirmContent}
698
+ </fieldset>
699
+ );
700
+ }