@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,864 @@
1
+ import * as React from "react";
2
+
3
+ void React;
4
+
5
+ import { AutoForm } from "@alepha/ui/components/auto-form/auto-form";
6
+ import type { ControlProps } from "@alepha/ui/components/control/control";
7
+ import { Badge } from "@alepha/ui/components/ui/badge";
8
+ import { Button } from "@alepha/ui/components/ui/button";
9
+ import {
10
+ Empty,
11
+ EmptyDescription,
12
+ EmptyHeader,
13
+ EmptyMedia,
14
+ EmptyTitle,
15
+ } from "@alepha/ui/components/ui/empty";
16
+ import { Skeleton } from "@alepha/ui/components/ui/skeleton";
17
+ import { useDialog } from "@alepha/ui/components/use-dialog/use-dialog";
18
+ import { useToast } from "@alepha/ui/components/use-toast/use-toast";
19
+ import { cn } from "@alepha/ui/lib/utils";
20
+ import { jsonSchemaToZod, type ZObject, z } from "alepha";
21
+ import type { AdminParameterController } from "alepha/api/parameters";
22
+ import { useAction, useClient, useQuery } from "alepha/react";
23
+ import { useForm } from "alepha/react/form";
24
+ import { useI18n } from "alepha/react/i18n";
25
+ import { useQueryParams } from "alepha/react/router";
26
+ import {
27
+ ChevronRight,
28
+ Download,
29
+ FileCog,
30
+ History as HistoryIcon,
31
+ Settings2,
32
+ Upload,
33
+ } from "lucide-react";
34
+ import { useMemo, useRef, useState } from "react";
35
+ import { ParameterDiffDialog } from "./parameter-diff-dialog.tsx";
36
+ import { ParameterHistoryItem } from "./parameter-history-item.tsx";
37
+ import { ParameterSaveDialog } from "./parameter-save-dialog.tsx";
38
+
39
+ /**
40
+ * Three-pane admin parameters editor:
41
+ *
42
+ * [ tree ][ AutoForm on current version ][ history ]
43
+ *
44
+ * - Left: collapsible tree of every registered parameter name. Dot-notation
45
+ * (`lore.campaign.limits`) becomes a folder hierarchy. Leaves are
46
+ * clickable; clicking sets the active parameter.
47
+ * - Center: AutoForm bound to the parameter's runtime schema and pre-filled
48
+ * with the current effective value. "Save new version" opens a dialog
49
+ * to attach tags, then creates an immediate version via
50
+ * `createVersion`.
51
+ * - Right: reverse-chronological history. Each version is a collapsible card
52
+ * (see `ParameterHistoryItem`) with a `…` menu to view its JSON, diff
53
+ * it against the previous version, or roll back to it.
54
+ */
55
+ const parameterQuerySchema = z.object({ param: z.string().optional() });
56
+
57
+ export interface AdminParametersProps {
58
+ /**
59
+ * Per-parameter field overrides, keyed by parameter name, forwarded to the
60
+ * generated form (same shape as `AutoForm`'s `fields`). This is how an app
61
+ * attaches a domain widget to a field the generic form cannot render well —
62
+ * a fare zone matrix, a colour picker, a code editor — without forking this
63
+ * panel. Reach nested fields through `objectProps.controlProps`.
64
+ *
65
+ * @example
66
+ * ```tsx
67
+ * <AdminParameters
68
+ * fields={{
69
+ * "ticketing.fares.catalog": {
70
+ * payg: { objectProps: { controlProps: { zoneFareCents: { custom: ZoneMatrix } } } },
71
+ * },
72
+ * }}
73
+ * />
74
+ * ```
75
+ */
76
+ fields?: Record<string, Record<string, Partial<Omit<ControlProps, "input">>>>;
77
+ }
78
+
79
+ export function AdminParameters(props: AdminParametersProps = {}) {
80
+ const client = useClient<AdminParameterController>();
81
+ const { tr } = useI18n();
82
+ const toast = useToast();
83
+ const dialog = useDialog();
84
+ // Selected parameter is bound to the URL (`?param=<name>`) via useQueryParams
85
+ // in querystring mode (replaceState — picking a parameter does not add a
86
+ // browser-history entry), mirroring the admin user-detail tab pattern.
87
+ const [query, setQuery] = useQueryParams(parameterQuerySchema, {
88
+ format: "querystring",
89
+ });
90
+ const selected = query.param || undefined;
91
+ const setSelected = (name: string) => setQuery({ param: name });
92
+ const [reloadKey, setReloadKey] = useState(0);
93
+
94
+ const { data: treeNodes } = useQuery(
95
+ { handler: () => client.getParameterTree() as Promise<ParamNode[]> },
96
+ [client, reloadKey],
97
+ );
98
+
99
+ const leafNames = useMemo(
100
+ () => collectLeafNames(treeNodes ?? []),
101
+ [treeNodes],
102
+ );
103
+
104
+ const exportAll = useAction(
105
+ {
106
+ handler: async () => {
107
+ if (leafNames.length === 0) return;
108
+ const payload: Array<{ name: string; content: unknown }> = [];
109
+ for (const name of leafNames) {
110
+ const res = await client.getCurrent({ params: { name } });
111
+ payload.push({
112
+ name,
113
+ content:
114
+ res.current?.content ?? res.currentValue ?? res.defaultValue,
115
+ });
116
+ }
117
+ downloadJson(payload, "parameters.json");
118
+ },
119
+ },
120
+ [client, leafNames],
121
+ );
122
+
123
+ const importParams = useAction<[File], void>(
124
+ {
125
+ handler: async (file) => {
126
+ let parsed: unknown;
127
+ try {
128
+ parsed = JSON.parse(await file.text());
129
+ } catch {
130
+ toast.error(
131
+ tr("admin.parameters.importInvalidJson", {
132
+ default: "Invalid JSON file",
133
+ }),
134
+ );
135
+ return;
136
+ }
137
+ const items = Array.isArray(parsed) ? parsed : [parsed];
138
+ const valid = items.filter(
139
+ (it): it is { name: string; content: unknown } =>
140
+ !!it &&
141
+ typeof (it as any).name === "string" &&
142
+ "content" in (it as any),
143
+ );
144
+ if (valid.length === 0) {
145
+ toast.error(
146
+ tr("admin.parameters.importNoItems", {
147
+ default: "No parameters found in file",
148
+ }),
149
+ );
150
+ return;
151
+ }
152
+ const known = new Set(leafNames);
153
+ const recognized = valid.filter((it) => known.has(it.name));
154
+ const skipped = valid.length - recognized.length;
155
+ if (recognized.length === 0) {
156
+ toast.error(
157
+ tr("admin.parameters.importNoneMatch", {
158
+ default: "No registered parameters match the imported names",
159
+ }),
160
+ );
161
+ return;
162
+ }
163
+ const ok = await dialog.confirm({
164
+ title: tr("admin.parameters.importTitle", {
165
+ default: "Import parameters",
166
+ }),
167
+ description: tr("admin.parameters.importConfirm", {
168
+ default: `Import ${recognized.length} parameter(s)? ${skipped > 0 ? `${skipped} unknown entrie(s) will be skipped.` : ""}`,
169
+ args: [String(recognized.length), String(skipped)],
170
+ }),
171
+ });
172
+ if (!ok) return;
173
+ for (const it of recognized) {
174
+ await client.createVersion({
175
+ params: { name: it.name },
176
+ body: {
177
+ content: it.content as Record<string, any>,
178
+ changeDescription: "Imported",
179
+ },
180
+ });
181
+ }
182
+ toast.success(
183
+ tr("admin.parameters.imported", {
184
+ default: `Imported ${recognized.length} parameter(s)`,
185
+ args: [String(recognized.length)],
186
+ }),
187
+ );
188
+ setReloadKey((k) => k + 1);
189
+ },
190
+ },
191
+ [client, leafNames, dialog, toast, tr],
192
+ );
193
+
194
+ const rollback = useAction<[number], void>(
195
+ {
196
+ handler: async (version) => {
197
+ if (!selected) return;
198
+ const ok = await dialog.confirm({
199
+ title: tr("admin.parameters.rollbackTitle", {
200
+ default: "Roll back parameter",
201
+ }),
202
+ description: tr("admin.parameters.rollbackConfirm", {
203
+ default: `Roll back to version ${version}? This creates a new version copying that content.`,
204
+ args: [String(version)],
205
+ }),
206
+ });
207
+ if (!ok) return;
208
+ await client.rollback({
209
+ params: { name: selected },
210
+ body: { targetVersion: version },
211
+ });
212
+ toast.success(
213
+ tr("admin.parameters.rolledBack", {
214
+ default: "Parameter rolled back",
215
+ }),
216
+ );
217
+ setReloadKey((k) => k + 1);
218
+ },
219
+ },
220
+ [client, selected, dialog, toast, tr],
221
+ );
222
+
223
+ return (
224
+ <div
225
+ className={cn(
226
+ "grid min-h-0 flex-1 p-6",
227
+ // Desktop-first 3-pane (tree | editor | history). Columns narrow on
228
+ // laptops (lg) and reach full width at xl; below lg the panes stack
229
+ // into a single scrollable column. The history pane only appears once
230
+ // a parameter is selected, so the grid drops a column until then.
231
+ selected
232
+ ? "grid-cols-1 lg:grid-cols-[220px_minmax(0,1fr)_260px] xl:grid-cols-[280px_minmax(0,1fr)_300px]"
233
+ : "grid-cols-1 lg:grid-cols-[220px_minmax(0,1fr)] xl:grid-cols-[280px_minmax(0,1fr)]",
234
+ )}
235
+ >
236
+ <ParameterTreePane
237
+ nodes={treeNodes}
238
+ selected={selected}
239
+ onSelect={setSelected}
240
+ onExportAll={exportAll.run}
241
+ onImport={importParams.run}
242
+ exporting={exportAll.loading}
243
+ importing={importParams.loading}
244
+ />
245
+ <ParameterEditorPane
246
+ key={selected ?? "none"}
247
+ name={selected}
248
+ fields={selected ? props.fields?.[selected] : undefined}
249
+ reloadKey={reloadKey}
250
+ onSaved={() => {
251
+ setReloadKey((k) => k + 1);
252
+ toast.success(
253
+ tr("admin.parameters.saved", {
254
+ default: "Parameter saved",
255
+ }),
256
+ );
257
+ }}
258
+ />
259
+ {selected && (
260
+ <ParameterHistoryPane
261
+ key={`history-${selected}`}
262
+ name={selected}
263
+ reloadKey={reloadKey}
264
+ onRollback={rollback.run}
265
+ />
266
+ )}
267
+ </div>
268
+ );
269
+ }
270
+
271
+ // ── Pane A: tree ─────────────────────────────────────────────────────
272
+
273
+ interface ParameterTreePaneProps {
274
+ nodes: ParamNode[] | undefined;
275
+ selected: string | undefined;
276
+ onSelect: (name: string) => void;
277
+ onExportAll: () => void | Promise<void>;
278
+ onImport: (file: File) => void | Promise<void>;
279
+ exporting?: boolean;
280
+ importing?: boolean;
281
+ }
282
+
283
+ interface ParamNode {
284
+ name: string;
285
+ path: string;
286
+ isLeaf: boolean;
287
+ children: ParamNode[];
288
+ }
289
+
290
+ const ParameterTreePane = (props: ParameterTreePaneProps) => {
291
+ const { tr } = useI18n();
292
+ return (
293
+ <div className="bg-card flex min-h-0 flex-col gap-2 rounded-l-lg border p-2">
294
+ <div className="text-muted-foreground flex items-center gap-1.5 px-2 py-1 text-xs font-medium uppercase tracking-wide">
295
+ <Settings2 className="size-3.5" />
296
+ {tr("admin.parameters.treeTitle", { default: "Parameters" })}
297
+ </div>
298
+ <div className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto pr-2">
299
+ {!props.nodes ? (
300
+ // Loading — distinct from an empty (loaded) tree.
301
+ ["t1", "t2", "t3", "t4", "t5"].map((k, i) => (
302
+ <div key={k} className="flex items-center gap-1.5 px-2 py-1.5">
303
+ <Skeleton className="size-3.5 shrink-0 rounded" />
304
+ <Skeleton
305
+ className="h-3.5"
306
+ style={{ width: `${[70, 55, 80, 50, 65][i]}%` }}
307
+ />
308
+ </div>
309
+ ))
310
+ ) : props.nodes.length ? (
311
+ props.nodes.map((node) => (
312
+ <TreeNodeView
313
+ key={node.path}
314
+ node={node}
315
+ depth={0}
316
+ selected={props.selected}
317
+ onSelect={props.onSelect}
318
+ />
319
+ ))
320
+ ) : (
321
+ <span className="text-muted-foreground px-2 py-1 text-xs">
322
+ {tr("admin.parameters.treeEmpty", {
323
+ default: "No parameters registered.",
324
+ })}
325
+ </span>
326
+ )}
327
+ </div>
328
+ <TreeFooterActions
329
+ onExportAll={props.onExportAll}
330
+ onImport={props.onImport}
331
+ exporting={props.exporting}
332
+ importing={props.importing}
333
+ disabled={!props.nodes?.length}
334
+ />
335
+ </div>
336
+ );
337
+ };
338
+
339
+ interface TreeFooterActionsProps {
340
+ onExportAll: () => void | Promise<void>;
341
+ onImport: (file: File) => void | Promise<void>;
342
+ disabled?: boolean;
343
+ exporting?: boolean;
344
+ importing?: boolean;
345
+ }
346
+
347
+ const TreeFooterActions = (props: TreeFooterActionsProps) => {
348
+ const { tr } = useI18n();
349
+ const fileInput = useRef<HTMLInputElement>(null);
350
+ return (
351
+ <div className="flex items-center justify-center gap-2 border-t pt-2">
352
+ <input
353
+ ref={fileInput}
354
+ type="file"
355
+ accept="application/json,.json"
356
+ className="hidden"
357
+ onChange={async (e) => {
358
+ const file = e.target.files?.[0];
359
+ // Reset so the same file can be re-selected on a subsequent click.
360
+ e.target.value = "";
361
+ if (file) await props.onImport(file);
362
+ }}
363
+ />
364
+ <Button
365
+ type="button"
366
+ variant="ghost"
367
+ size="sm"
368
+ disabled={props.disabled || props.exporting}
369
+ onClick={() => props.onExportAll()}
370
+ >
371
+ <Download className="size-3.5" />
372
+ {tr("admin.parameters.export", { default: "Export" })}
373
+ </Button>
374
+ <span aria-hidden className="bg-border h-4 w-px rotate-12" />
375
+ <Button
376
+ type="button"
377
+ variant="ghost"
378
+ size="sm"
379
+ disabled={props.importing}
380
+ onClick={() => fileInput.current?.click()}
381
+ >
382
+ <Upload className="size-3.5" />
383
+ {tr("admin.parameters.import", { default: "Import" })}
384
+ </Button>
385
+ </div>
386
+ );
387
+ };
388
+
389
+ interface TreeNodeViewProps {
390
+ node: ParamNode;
391
+ depth: number;
392
+ selected: string | undefined;
393
+ onSelect: (name: string) => void;
394
+ }
395
+
396
+ const TreeNodeView = (props: TreeNodeViewProps) => {
397
+ const { node } = props;
398
+ const { tr } = useI18n();
399
+ const [open, setOpen] = useState(true);
400
+ const isActive = node.isLeaf && props.selected === node.path;
401
+ // Translatable label keyed by the full dotted path
402
+ // (`parameters.courts.pricing`, `parameters.courts`), falling back to the
403
+ // English title-case of the last segment when the app has no dictionary
404
+ // entry — so a parameters tree always renders, localized or not.
405
+ const label = tr(`parameters.${node.path}`, { default: labelOf(node.name) });
406
+ const indent = props.depth * 12;
407
+
408
+ if (node.isLeaf) {
409
+ return (
410
+ <button
411
+ type="button"
412
+ onClick={() => props.onSelect(node.path)}
413
+ style={{ paddingLeft: 8 + indent }}
414
+ className={cn(
415
+ "hover:bg-accent flex items-center gap-1.5 rounded-md py-1.5 pr-2 text-left text-sm transition-colors",
416
+ isActive && "bg-accent text-accent-foreground font-medium",
417
+ )}
418
+ >
419
+ <FileCog className="size-3.5 shrink-0 opacity-60" />
420
+ <span className="truncate">{label}</span>
421
+ </button>
422
+ );
423
+ }
424
+ return (
425
+ <>
426
+ <button
427
+ type="button"
428
+ onClick={() => setOpen((v) => !v)}
429
+ style={{ paddingLeft: 4 + indent }}
430
+ className="hover:bg-accent text-muted-foreground flex items-center gap-1 rounded-md py-1.5 pr-2 text-left text-xs font-medium transition-colors"
431
+ >
432
+ <ChevronRight
433
+ className={cn("size-3.5 transition-transform", open && "rotate-90")}
434
+ />
435
+ <span className="truncate">{label}</span>
436
+ </button>
437
+ {open &&
438
+ node.children.map((child) => (
439
+ <TreeNodeView
440
+ key={child.path}
441
+ node={child}
442
+ depth={props.depth + 1}
443
+ selected={props.selected}
444
+ onSelect={props.onSelect}
445
+ />
446
+ ))}
447
+ </>
448
+ );
449
+ };
450
+
451
+ // ── Pane B: editor ───────────────────────────────────────────────────
452
+
453
+ interface ParameterEditorPaneProps {
454
+ /** Per-field overrides for this parameter's generated form. */
455
+ fields?: Record<string, Partial<Omit<ControlProps, "input">>>;
456
+ name: string | undefined;
457
+ reloadKey: number;
458
+ onSaved: () => void;
459
+ }
460
+
461
+ const ParameterEditorPane = (props: ParameterEditorPaneProps) => {
462
+ const client = useClient<AdminParameterController>();
463
+ const { tr } = useI18n();
464
+ const toast = useToast();
465
+
466
+ const { data: current } = useQuery(
467
+ {
468
+ handler: () => client.getCurrent({ params: { name: props.name! } }),
469
+ enabled: !!props.name,
470
+ },
471
+ [client, props.name, props.reloadKey],
472
+ );
473
+
474
+ // Factory reset is a write mutation — runs through useAction so the action
475
+ // button can disable while it's in flight. Reads `current` at call time
476
+ // (the hook must sit above the early returns below).
477
+ const factoryReset = useAction(
478
+ {
479
+ handler: async () => {
480
+ if (!props.name || !current) return;
481
+ await client.createVersion({
482
+ params: { name: props.name },
483
+ body: {
484
+ content: (current.defaultValue ?? {}) as Record<string, any>,
485
+ changeDescription: "Factory reset to compiled defaults",
486
+ },
487
+ });
488
+ toast.success(
489
+ tr("admin.parameters.factoryReset", {
490
+ default: "Parameter reset to defaults",
491
+ }),
492
+ );
493
+ props.onSaved();
494
+ },
495
+ },
496
+ [client, props.name, current],
497
+ );
498
+
499
+ // Factory reset is gated behind a confirm dialog that previews the diff
500
+ // between the current effective value and the compiled defaults.
501
+ const [resetOpen, setResetOpen] = useState(false);
502
+
503
+ if (!props.name) {
504
+ // No selection → history pane is hidden, so the editor is the rightmost
505
+ // pane and closes the card on its right edge.
506
+ return (
507
+ <div className="bg-card flex flex-1 items-center justify-center rounded-r-lg border-y border-r p-6">
508
+ <Empty className="border-0">
509
+ <EmptyHeader>
510
+ <EmptyMedia variant="icon">
511
+ <Settings2 className="size-4" />
512
+ </EmptyMedia>
513
+ <EmptyTitle>
514
+ {tr("admin.parameters.emptyTitle", {
515
+ default: "No parameter selected",
516
+ })}
517
+ </EmptyTitle>
518
+ <EmptyDescription>
519
+ {tr("admin.parameters.emptySelection", {
520
+ default: "Pick a parameter on the left to edit it.",
521
+ })}
522
+ </EmptyDescription>
523
+ </EmptyHeader>
524
+ </Empty>
525
+ </div>
526
+ );
527
+ }
528
+ if (!current) {
529
+ return (
530
+ <div className="bg-card flex min-h-0 flex-1 flex-col border-y">
531
+ <div className="flex items-center gap-3 border-b px-4 pb-3 pt-3">
532
+ <Skeleton className="size-10 rounded-full" />
533
+ <div className="flex flex-col gap-1.5">
534
+ <Skeleton className="h-4 w-32" />
535
+ <Skeleton className="h-3 w-24" />
536
+ </div>
537
+ </div>
538
+ <div className="grid grid-cols-1 gap-4 p-4 lg:grid-cols-2 xl:grid-cols-3">
539
+ {["f1", "f2", "f3", "f4"].map((k) => (
540
+ <div key={k} className="flex flex-col gap-2">
541
+ <Skeleton className="h-3 w-28" />
542
+ <Skeleton className="h-9 w-full" />
543
+ </div>
544
+ ))}
545
+ </div>
546
+ </div>
547
+ );
548
+ }
549
+
550
+ const data = current;
551
+ const schema = data.schema
552
+ ? (jsonSchemaToZod(data.schema as any) as ZObject)
553
+ : (jsonSchemaToZod({
554
+ type: "object",
555
+ properties: {},
556
+ }) as ZObject);
557
+ const initial =
558
+ (data.current?.content as Record<string, unknown> | undefined) ??
559
+ (data.currentValue as Record<string, unknown> | undefined) ??
560
+ (data.defaultValue as Record<string, unknown> | undefined) ??
561
+ {};
562
+
563
+ const exportContent =
564
+ data.current?.content ?? data.currentValue ?? data.defaultValue ?? {};
565
+
566
+ return (
567
+ <>
568
+ <ParameterEditorForm
569
+ name={props.name}
570
+ fields={props.fields}
571
+ declaredDescription={data.description}
572
+ schema={schema}
573
+ initial={initial}
574
+ schemaHash={data.current?.schemaHash}
575
+ currentVersion={data.current?.version}
576
+ initialTags={data.current?.tags ?? undefined}
577
+ onSubmit={async (content, meta) => {
578
+ await client.createVersion({
579
+ params: { name: props.name! },
580
+ body: {
581
+ content: content as Record<string, any>,
582
+ tags: meta.tags.length > 0 ? meta.tags : undefined,
583
+ activationDate: meta.activationDate,
584
+ },
585
+ });
586
+ props.onSaved();
587
+ }}
588
+ onFactoryReset={() => setResetOpen(true)}
589
+ factoryResetLoading={factoryReset.loading}
590
+ onExport={() => {
591
+ downloadJson(
592
+ [{ name: props.name!, content: exportContent }],
593
+ `${props.name}.json`,
594
+ );
595
+ }}
596
+ />
597
+ <ParameterDiffDialog
598
+ open={resetOpen}
599
+ onOpenChange={setResetOpen}
600
+ title={tr("admin.parameters.factoryResetTitle", {
601
+ default: "Factory reset",
602
+ })}
603
+ description={tr("admin.parameters.factoryResetConfirm", {
604
+ default:
605
+ "Reset to compiled defaults? The change below will be saved as a new version.",
606
+ })}
607
+ previous={initial}
608
+ current={data.defaultValue ?? {}}
609
+ confirm={{
610
+ label: tr("admin.parameters.factoryReset", {
611
+ default: "Factory reset",
612
+ }),
613
+ destructive: true,
614
+ loading: factoryReset.loading,
615
+ onConfirm: async () => {
616
+ await factoryReset.run();
617
+ setResetOpen(false);
618
+ },
619
+ }}
620
+ />
621
+ </>
622
+ );
623
+ };
624
+
625
+ interface ParameterEditorFormProps {
626
+ /** Per-field overrides forwarded to AutoForm (domain widgets). */
627
+ fields?: Record<string, Partial<Omit<ControlProps, "input">>>;
628
+ /** `$parameter({ description })` as declared in code. */
629
+ declaredDescription?: string;
630
+ name: string;
631
+ schema: ZObject;
632
+ initial: Record<string, unknown>;
633
+ schemaHash?: string;
634
+ currentVersion?: number;
635
+ initialTags?: string[];
636
+ onSubmit: (
637
+ content: unknown,
638
+ meta: { tags: string[]; activationDate?: string },
639
+ ) => Promise<void>;
640
+ onFactoryReset: () => void | Promise<void>;
641
+ factoryResetLoading?: boolean;
642
+ onExport: () => void;
643
+ }
644
+
645
+ const ParameterEditorForm = (props: ParameterEditorFormProps) => {
646
+ // `lang` is in the deps of every memo below on purpose: `tr` is a stable
647
+ // method on the injected provider, so switching language re-renders but
648
+ // would otherwise hand back the previously memoised (wrong-language) copy.
649
+ const { tr, lang } = useI18n();
650
+ // Saving is a two-step flow: the AutoForm submit captures the edited content
651
+ // and opens the save dialog, which collects tags before the version is
652
+ // actually persisted via onSubmit.
653
+ const [pending, setPending] = useState<Record<string, unknown> | null>(null);
654
+ const form = useForm(
655
+ {
656
+ schema: props.schema,
657
+ initialValues: props.initial as Record<string, any>,
658
+ handler: async (values) => {
659
+ setPending(values);
660
+ },
661
+ },
662
+ [props.name, props.schemaHash],
663
+ );
664
+ const title = useMemo(
665
+ () => tr(`parameters.${props.name}`, { default: labelOf(props.name) }),
666
+ [props.name, tr, lang],
667
+ );
668
+ /**
669
+ * What this parameter IS, in order of preference: the dictionary
670
+ * (`parameters.<name>.desc`, so it can be translated and edited without a
671
+ * deploy), then the `description` declared on the `$parameter`, then the
672
+ * tree path as a last resort. A key like "reducedFactor" means nothing to
673
+ * an operator — this line is what turns the panel into documentation.
674
+ */
675
+ const description = useMemo(() => {
676
+ const key = `parameters.${props.name}.desc`;
677
+ const translated = tr(key, { default: "" });
678
+ if (translated && translated !== key) return translated;
679
+ return props.declaredDescription || undefined;
680
+ }, [props.name, props.declaredDescription, tr, lang]);
681
+
682
+ const breadcrumb = useMemo(() => {
683
+ const parts = props.name.split(".");
684
+ parts.pop();
685
+ // Translate each ancestor folder by its cumulative path
686
+ // (`parameters.courts`), falling back to the raw segment.
687
+ return parts
688
+ .map((segment, i) => {
689
+ const path = parts.slice(0, i + 1).join(".");
690
+ return tr(`parameters.${path}`, { default: segment });
691
+ })
692
+ .join(" / ");
693
+ }, [props.name, tr, lang]);
694
+
695
+ return (
696
+ <div className="flex min-h-0 flex-col">
697
+ <AutoForm
698
+ form={form}
699
+ fields={props.fields as never}
700
+ fill
701
+ card="rounded-none ring-0 border-y"
702
+ // Two columns, not three: every field now carries help text under it,
703
+ // and a third of a row turns that help into an unreadable ribbon.
704
+ gridClassName="grid-cols-1 lg:grid-cols-2"
705
+ icon="cog"
706
+ title={title}
707
+ description={description ?? breadcrumb ?? undefined}
708
+ i18nPrefix={`parameters.${props.name}`}
709
+ headerAction={
710
+ props.currentVersion != null ? (
711
+ <Badge variant="secondary">v{props.currentVersion}</Badge>
712
+ ) : undefined
713
+ }
714
+ autoGroup
715
+ disabledIfPristine
716
+ skipReset
717
+ submitLabel={tr("admin.parameters.save", {
718
+ default: "Save new version",
719
+ })}
720
+ actions={[
721
+ {
722
+ label: tr("admin.parameters.factoryReset", {
723
+ default: "Factory reset",
724
+ }),
725
+ icon: "wrench",
726
+ variant: "outline",
727
+ onClick: props.onFactoryReset,
728
+ disabled: props.factoryResetLoading,
729
+ },
730
+ {
731
+ label: tr("admin.parameters.export", { default: "Export" }),
732
+ icon: "download",
733
+ variant: "outline",
734
+ onClick: props.onExport,
735
+ },
736
+ ]}
737
+ />
738
+ <ParameterSaveDialog
739
+ open={pending !== null}
740
+ onOpenChange={(open) => {
741
+ if (!open) setPending(null);
742
+ }}
743
+ initialTags={props.initialTags}
744
+ onConfirm={async (meta) => {
745
+ if (pending) await props.onSubmit(pending, meta);
746
+ setPending(null);
747
+ }}
748
+ />
749
+ </div>
750
+ );
751
+ };
752
+
753
+ // ── Pane C: history ──────────────────────────────────────────────────
754
+
755
+ interface ParameterHistoryPaneProps {
756
+ name: string | undefined;
757
+ reloadKey: number;
758
+ onRollback: (version: number) => Promise<void>;
759
+ }
760
+
761
+ const ParameterHistoryPane = (props: ParameterHistoryPaneProps) => {
762
+ const client = useClient<AdminParameterController>();
763
+ const { tr } = useI18n();
764
+
765
+ const { data: history } = useQuery(
766
+ {
767
+ handler: () =>
768
+ client.getHistory({
769
+ params: { name: props.name! },
770
+ query: { limit: 50 },
771
+ }),
772
+ enabled: !!props.name,
773
+ },
774
+ [client, props.name, props.reloadKey],
775
+ );
776
+
777
+ return (
778
+ <div className="bg-card flex min-h-0 flex-col overflow-hidden rounded-r-lg border">
779
+ <div className="text-muted-foreground flex items-center gap-1.5 px-3 py-2 text-xs font-medium uppercase tracking-wide">
780
+ <HistoryIcon className="size-3.5" />
781
+ {tr("admin.parameters.historyTitle", { default: "History" })}
782
+ </div>
783
+ {!props.name ? (
784
+ <span className="text-muted-foreground px-3 py-2 text-xs">
785
+ {tr("admin.parameters.historyHint", {
786
+ default: "Select a parameter to see its versions.",
787
+ })}
788
+ </span>
789
+ ) : !history ? (
790
+ <div className="flex flex-col border-t">
791
+ {["s1", "s2", "s3"].map((k) => (
792
+ <div
793
+ key={k}
794
+ className="flex items-center gap-3 border-b px-3 py-2.5"
795
+ >
796
+ <Skeleton className="size-4 rounded-full" />
797
+ <div className="flex flex-1 flex-col gap-1.5">
798
+ <Skeleton className="h-3.5 w-20" />
799
+ <Skeleton className="h-3 w-28" />
800
+ </div>
801
+ </div>
802
+ ))}
803
+ </div>
804
+ ) : !history.versions.length ? (
805
+ <span className="text-muted-foreground px-3 py-2 text-xs">
806
+ {tr("admin.parameters.historyEmpty", {
807
+ default: "No saved versions yet",
808
+ })}
809
+ </span>
810
+ ) : (
811
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto border-t">
812
+ {[...history.versions]
813
+ // Most recent activation on top.
814
+ .sort(
815
+ (a, b) =>
816
+ b.activationDate.localeCompare(a.activationDate) ||
817
+ b.version - a.version,
818
+ )
819
+ .map((v) => (
820
+ <ParameterHistoryItem
821
+ key={v.id}
822
+ version={v}
823
+ onRollback={props.onRollback}
824
+ />
825
+ ))}
826
+ </div>
827
+ )}
828
+ </div>
829
+ );
830
+ };
831
+
832
+ // ── helpers ──────────────────────────────────────────────────────────
833
+
834
+ const collectLeafNames = (nodes: ParamNode[]): string[] => {
835
+ const out: string[] = [];
836
+ const walk = (n: ParamNode) => {
837
+ if (n.isLeaf) out.push(n.path);
838
+ for (const c of n.children) walk(c);
839
+ };
840
+ for (const n of nodes) walk(n);
841
+ return out;
842
+ };
843
+
844
+ const downloadJson = (data: unknown, fileName: string) => {
845
+ const blob = new Blob([JSON.stringify(data, null, 2)], {
846
+ type: "application/json",
847
+ });
848
+ const url = URL.createObjectURL(blob);
849
+ const a = document.createElement("a");
850
+ a.href = url;
851
+ a.download = fileName;
852
+ document.body.appendChild(a);
853
+ a.click();
854
+ document.body.removeChild(a);
855
+ // Give the browser a moment to start the download before reclaiming the URL.
856
+ setTimeout(() => URL.revokeObjectURL(url), 1_000);
857
+ };
858
+
859
+ const labelOf = (s: string) => {
860
+ const last = s.split(".").pop() ?? s;
861
+ return last.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
862
+ };
863
+
864
+ export default AdminParameters;