@vitavision/forms 0.6.4 → 0.7.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.
package/dist/index.js CHANGED
@@ -1,19 +1,51 @@
1
- import { Disclosure, Field, Input, NumberInput, SegmentedControl, Select, Switch, Textarea } from "@vitavision/ui";
2
- import { jsx, jsxs } from "react/jsx-runtime";
3
- //#region src/api/schemaForm.ts
4
- const DEFS_PREFIX = "#/$defs/";
1
+ import { Button, Checkbox, Disclosure, Field, InfoHint, Input, NumberInput, Section, SegmentedControl, Select, Switch, Textarea, TooltipProvider, byDensity, cn, parseNumber, useDensity } from "@vitavision/ui";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { createContext, use, useMemo, useState } from "react";
4
+ //#region src/api/schemaNode.ts
5
+ /** Enough hops for any real schema; a `$ref` cycle ends here instead of looping. */
6
+ const MAX_HOPS = 16;
7
+ function isObject(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ /**
11
+ * Follow a JSON Pointer `$ref` (`#`, `#/$defs/Name`, `#/definitions/Name`) from the root.
12
+ *
13
+ * @param ref - The `$ref` string. Only same-document references (`#…`) resolve.
14
+ * @param root - The document the pointer starts from.
15
+ * @returns The schema it points at, or `undefined` for an external reference, a path that
16
+ * does not exist, or a target that is not a schema object.
17
+ */
18
+ function resolveRef(ref, root) {
19
+ if (ref === "#") return root;
20
+ if (!ref.startsWith("#/")) return void 0;
21
+ let current = root;
22
+ for (const raw of ref.slice(2).split("/")) {
23
+ let segment = raw;
24
+ try {
25
+ segment = decodeURIComponent(raw);
26
+ } catch {}
27
+ segment = segment.replaceAll("~1", "/").replaceAll("~0", "~");
28
+ if (!isObject(current) || !Object.hasOwn(current, segment)) return void 0;
29
+ current = current[segment];
30
+ }
31
+ return isObject(current) ? current : void 0;
32
+ }
5
33
  /**
6
- * Follow a `$ref` into `$defs`.
34
+ * Follow one `$ref`, keeping what the field says about itself.
35
+ *
36
+ * The merge order matters and is the opposite of the obvious one. schemars and pydantic
37
+ * write the field's `default` and `description` *beside* the `$ref`, while the target
38
+ * carries the type's own `title` and docstring. The field's statement about itself wins;
39
+ * the type's is the fallback.
7
40
  *
8
- * The merge order matters and is the opposite of the obvious one. Pydantic writes the
9
- * field's `default` and `description` *beside* the `$ref`, while the target carries the
10
- * enum's own `title` and sometimes its own docstring as a `description`. The field's
11
- * statement about itself wins; the type's is the fallback.
41
+ * @param node - A node that may carry a `$ref`.
42
+ * @param root - The document holding `$defs`.
43
+ * @returns The node merged over its target, or `node` itself when there is nothing to
44
+ * follow (no `$ref`, or one that points at nothing).
12
45
  */
13
- function deref(node, defs) {
46
+ function derefNode(node, root) {
14
47
  if (node.$ref === void 0) return node;
15
- if (!node.$ref.startsWith(DEFS_PREFIX)) return node;
16
- const target = defs?.[node.$ref.slice(8)];
48
+ const target = resolveRef(node.$ref, root);
17
49
  if (target === void 0) return node;
18
50
  const rest = { ...node };
19
51
  delete rest.$ref;
@@ -22,35 +54,172 @@ function deref(node, defs) {
22
54
  ...rest
23
55
  };
24
56
  }
57
+ function isNullSchema(branch) {
58
+ return branch.type === "null" || Object.hasOwn(branch, "const") && branch.const === null;
59
+ }
25
60
  /**
26
- * Look through pydantic's `str | None` encoding to the type that carries the meaning.
61
+ * Look through the "or null" encodings: `type: ["T", "null"]`, an `enum` that lists `null`,
62
+ * and an `anyOf` / `oneOf` with a `{ type: "null" }` branch.
63
+ *
64
+ * An optional string arrives as `anyOf: [{type: "string"}, {type: "null"}]`; treating that
65
+ * as an unrecognised node would give every nullable option a JSON textarea. When exactly
66
+ * one branch is left it is merged into the node (the node's own siblings win); when several
67
+ * are, they stay as the node's `anyOf` / `oneOf`.
27
68
  *
28
- * An optional string arrives as `anyOf: [{type: "string"}, {type: "null"}]`, and treating
29
- * that as an unrecognised node would give every nullable option a JSON textarea.
69
+ * @param node - The node to look through.
70
+ * @returns The node without its null alternative, and whether it had one.
30
71
  */
31
- function unwrap(node) {
32
- if (!node.anyOf) return node;
33
- const meaningful = node.anyOf.filter((branch) => branch.type !== "null");
34
- return meaningful.length === 1 ? {
35
- ...node,
36
- ...meaningful[0]
37
- } : node;
72
+ function stripNullable(node) {
73
+ let out = node;
74
+ let nullable = false;
75
+ if (Array.isArray(out.type) && out.type.includes("null")) {
76
+ const rest = out.type.filter((type) => type !== "null");
77
+ const [only] = rest;
78
+ if (only !== void 0) {
79
+ out = {
80
+ ...out,
81
+ type: rest.length === 1 ? only : rest
82
+ };
83
+ nullable = true;
84
+ }
85
+ }
86
+ if (out.enum?.includes(null) === true) {
87
+ out = {
88
+ ...out,
89
+ enum: out.enum.filter((entry) => entry !== null)
90
+ };
91
+ nullable = true;
92
+ }
93
+ for (const key of ["anyOf", "oneOf"]) {
94
+ const branches = out[key];
95
+ if (branches === void 0 || !branches.some(isNullSchema)) continue;
96
+ const remaining = branches.filter((branch) => !isNullSchema(branch));
97
+ const [only] = remaining;
98
+ if (only === void 0) continue;
99
+ nullable = true;
100
+ if (remaining.length === 1) {
101
+ const rest = { ...out };
102
+ delete rest[key];
103
+ out = {
104
+ ...only,
105
+ ...rest
106
+ };
107
+ } else out = {
108
+ ...out,
109
+ [key]: remaining
110
+ };
111
+ }
112
+ return {
113
+ schema: nullable ? out : node,
114
+ nullable
115
+ };
116
+ }
117
+ /** `allOf: [X]` is how older schemars wrapped a `$ref` that needed siblings. */
118
+ function unwrapAllOf(node) {
119
+ const [only] = node.allOf ?? [];
120
+ if (only === void 0 || node.allOf?.length !== 1) return node;
121
+ const rest = { ...node };
122
+ delete rest.allOf;
123
+ return {
124
+ ...only,
125
+ ...rest
126
+ };
38
127
  }
39
128
  /**
40
- * The node that says what this field *is*.
129
+ * The node that says what a field *is*: `$ref` followed, `allOf: [X]` unwrapped and the
130
+ * "or null" encoding looked through, repeatedly, because each can hide the next (a `$ref`
131
+ * to an enum inside `anyOf: [{$ref}, null]`).
41
132
  *
42
- * Dereferenced on both sides of the unwrap because either can hold the `$ref`: a plain
43
- * `ColorMode` is a bare `$ref`, while an `Optional[ColorMode]` hides one inside `anyOf`.
133
+ * @param node - A property or item schema as written.
134
+ * @param root - The document holding `$defs` (defaults to `node`, for a root schema).
135
+ * @returns The resolved node and whether `null` was among its accepted values. The field's
136
+ * own `default` and `description`, written beside a `$ref`, are kept.
44
137
  */
45
- function resolve(node, defs) {
46
- return deref(unwrap(deref(node, defs)), defs);
138
+ function resolveSchema(node, root = node) {
139
+ let current = node;
140
+ let nullable = false;
141
+ for (let hop = 0; hop < MAX_HOPS; hop++) {
142
+ const stripped = stripNullable(unwrapAllOf(derefNode(current, root)));
143
+ nullable ||= stripped.nullable;
144
+ const done = stripped.schema === current;
145
+ current = stripped.schema;
146
+ if (done) break;
147
+ }
148
+ return {
149
+ schema: current,
150
+ nullable
151
+ };
47
152
  }
48
- function kindOf(resolved) {
153
+ /**
154
+ * Humanise `normal_dirs` into `Normal dirs`, and use a title only when a human chose it.
155
+ *
156
+ * pydantic emits a `title` for every field whether or not anyone wrote one, and its
157
+ * generated form is Title Case — `Csv Path`, `Defect Type From Dir` — which reads like a
158
+ * spreadsheet header rather than a form label. So a title is used only when it is *not*
159
+ * the one pydantic would have generated, which is exactly when a human chose it.
160
+ *
161
+ * Read from the *unresolved* node on purpose. Dereferencing pulls in the type's own title,
162
+ * so a resolved `color` field would be labelled "ColorMode".
163
+ *
164
+ * @param name - The property key.
165
+ * @param node - The property's schema as written (not resolved).
166
+ * @returns The label.
167
+ */
168
+ function labelFor(name, node) {
169
+ const words = name.split("_");
170
+ const generated = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
171
+ if (node.title && node.title !== generated) return node.title;
172
+ const spaced = words.join(" ");
173
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
174
+ }
175
+ //#endregion
176
+ //#region src/api/schemaForm.ts
177
+ /**
178
+ * Turning a JSON Schema into a form, and a form back into options.
179
+ *
180
+ * An options model — a plugin's config, an algorithm's parameters — is meant to *drive*
181
+ * the UI form rather than have the form hardcoded and the schema's defaults merely hoped
182
+ * to agree with it. That stops being survivable the moment an option is *required* and
183
+ * nobody can type it.
184
+ *
185
+ * The logic lives here rather than in the component because it is where the decisions
186
+ * are: what control a schema node deserves, what an empty box means, and when a value is
187
+ * worth sending at all. Rendering is the easy half.
188
+ *
189
+ * Only the shapes pydantic (or an equivalent JSON Schema generator) actually emits are
190
+ * handled. A node this does not recognise becomes a JSON textarea rather than
191
+ * disappearing — a caller can always express what the model accepts, even where the form
192
+ * has nothing prettier to offer.
193
+ *
194
+ * ## Two things worth reading before touching `kindOf`
195
+ *
196
+ * `enum` has to be tested *before* `type`: `Literal["small", "medium"]` emits `enum`
197
+ * *alongside* `type: "string"`, and testing type first turns a closed set into a free text
198
+ * box whose placeholder is the only hint of what is accepted. A `StrEnum` is worse —
199
+ * pydantic emits it as `{"$ref": "#/$defs/ColorMode"}` with the default and description as
200
+ * siblings, and `$ref` is not in the type at all, so it falls through every branch to a
201
+ * JSON textarea unless `$defs` is resolved first.
202
+ *
203
+ * Numeric bounds are the same story: a field can carry `minimum`/`maximum` in the schema,
204
+ * and a control that ignores them turns an out-of-range value into a backend rejection
205
+ * reported nowhere near the field that caused it.
206
+ */
207
+ /**
208
+ * The node that says what this field *is*, looked through `$ref` and "or null" encodings
209
+ * by the same resolver `SchemaValueForm` reads schemas with (see `schemaNode.ts`).
210
+ *
211
+ * Both sides of the null-unwrap can hold the `$ref`: a plain `ColorMode` is a bare
212
+ * `$ref`, while an `Optional[ColorMode]` hides one inside `anyOf`.
213
+ */
214
+ function resolve(node, root) {
215
+ return resolveSchema(node, root).schema;
216
+ }
217
+ function kindOf(resolved, root) {
49
218
  if (Array.isArray(resolved.enum) && resolved.enum.length > 0) return resolved.enum.length <= 3 ? "choice-inline" : "choice";
50
219
  if (resolved.type === "boolean") return "boolean";
51
220
  if (resolved.type === "integer" || resolved.type === "number") return "number";
52
221
  if (resolved.type === "string") return "text";
53
- if (resolved.type === "array" && unwrap(resolved.items ?? {}).type === "string") return "string-list";
222
+ if (resolved.type === "array" && resolve(resolved.items ?? {}, root).type === "string") return "string-list";
54
223
  return "json";
55
224
  }
56
225
  /**
@@ -84,24 +253,6 @@ function isPrimary(node, resolved) {
84
253
  return !isAdvanced(resolved);
85
254
  }
86
255
  /**
87
- * Humanise `normal_dirs` into `Normal dirs`.
88
- *
89
- * Pydantic emits a `title` for every field whether or not anyone wrote one, and its
90
- * generated form is Title Case — `Csv Path`, `Defect Type From Dir` — which reads like a
91
- * spreadsheet header rather than a form label. So a title is used only when it is *not*
92
- * the one pydantic would have generated, which is exactly when a human chose it.
93
- *
94
- * Read from the *unresolved* node on purpose. Dereferencing pulls in the enum class's own
95
- * title, so a resolved `color` field would be labelled "ColorMode".
96
- */
97
- function labelFor(name, node) {
98
- const words = name.split("_");
99
- const generated = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
100
- if (node.title && node.title !== generated) return node.title;
101
- const spaced = words.join(" ");
102
- return spaced.charAt(0).toUpperCase() + spaced.slice(1);
103
- }
104
- /**
105
256
  * A value as a person reads it: scalars as themselves, anything structured as JSON rather
106
257
  * than `[object Object]`.
107
258
  */
@@ -154,10 +305,9 @@ function stepOf(resolved) {
154
305
  */
155
306
  function describeFields(schema) {
156
307
  const required = new Set(schema.required ?? []);
157
- const defs = schema.$defs;
158
308
  return Object.entries(schema.properties ?? {}).map(([name, node]) => {
159
- const resolved = resolve(node, defs);
160
- const kind = kindOf(resolved);
309
+ const resolved = resolve(node, schema);
310
+ const kind = kindOf(resolved, schema);
161
311
  const numeric = (kind === "choice" || kind === "choice-inline") && (resolved.type === "integer" || resolved.type === "number");
162
312
  return {
163
313
  name,
@@ -342,17 +492,17 @@ function SchemaForm({ fields, values, onChange }) {
342
492
  }, field.name);
343
493
  const primary = fields.filter((field) => !field.advanced);
344
494
  const advanced = fields.filter((field) => field.advanced);
345
- if (primary.length === 0) return /* @__PURE__ */ jsx(Grid, { children: advanced.map(render) });
495
+ if (primary.length === 0) return /* @__PURE__ */ jsx(Grid$1, { children: advanced.map(render) });
346
496
  return /* @__PURE__ */ jsxs("div", {
347
497
  className: "flex flex-col gap-4",
348
- children: [/* @__PURE__ */ jsx(Grid, { children: primary.map(render) }), advanced.length > 0 && /* @__PURE__ */ jsx(Disclosure, {
498
+ children: [/* @__PURE__ */ jsx(Grid$1, { children: primary.map(render) }), advanced.length > 0 && /* @__PURE__ */ jsx(Disclosure, {
349
499
  summary: "Advanced",
350
500
  count: advanced.length,
351
- children: /* @__PURE__ */ jsx(Grid, { children: advanced.map(render) })
501
+ children: /* @__PURE__ */ jsx(Grid$1, { children: advanced.map(render) })
352
502
  })]
353
503
  });
354
504
  }
355
- function Grid({ children }) {
505
+ function Grid$1({ children }) {
356
506
  return /* @__PURE__ */ jsx("div", {
357
507
  className: "grid grid-cols-1 gap-x-5 gap-y-4 sm:grid-cols-2",
358
508
  children
@@ -430,6 +580,1475 @@ function SchemaField({ field, value, onChange }) {
430
580
  });
431
581
  }
432
582
  //#endregion
433
- export { SchemaForm, describeFields, initialValues, jsonErrors, missingRequired, outOfRange, overrideCount, toOptions };
583
+ //#region src/api/valuePath.ts
584
+ /**
585
+ * Reading and writing a JSON value by dot path, without mutating it.
586
+ *
587
+ * A form edits one leaf of a value it does not own: the caller holds the value, the form
588
+ * reports the next one. So an edit must produce a new root that shares every untouched
589
+ * subtree with the old one (cheap to compare, safe to hold in state) and must leave the old
590
+ * root exactly as it was.
591
+ *
592
+ * A path is dot-separated keys, with array indices as numbers: `solver.max_iters`,
593
+ * `cameras.0.id`. A key that itself contains a dot cannot be addressed; the Rust and
594
+ * Python configs these forms are for do not have them.
595
+ */
596
+ const INDEX = /^(0|[1-9]\d*)$/;
597
+ function isRecord$1(value) {
598
+ return typeof value === "object" && value !== null && !Array.isArray(value);
599
+ }
600
+ /**
601
+ * Split a dot path into its segments.
602
+ *
603
+ * @param path - `a.b.0`, or `""` for the root.
604
+ * @returns `["a", "b", "0"]`, or `[]` for the root.
605
+ */
606
+ function splitPath(path) {
607
+ return path === "" ? [] : path.split(".");
608
+ }
609
+ /**
610
+ * Join a parent path and a key.
611
+ *
612
+ * @param parent - A dot path; `""` is the root.
613
+ * @param key - A property key or an array index.
614
+ * @returns The child's path.
615
+ */
616
+ function joinPath(parent, key) {
617
+ return parent === "" ? key : `${parent}.${key}`;
618
+ }
619
+ /**
620
+ * Read the value at a path.
621
+ *
622
+ * @param value - The root value.
623
+ * @param path - Dot path; `""` is the root itself.
624
+ * @returns What is there, or `undefined` where any step of the path is missing.
625
+ */
626
+ function getAtPath(value, path) {
627
+ let current = value;
628
+ for (const segment of splitPath(path)) if (Array.isArray(current)) current = INDEX.test(segment) ? current[Number(segment)] : void 0;
629
+ else if (isRecord$1(current) && Object.hasOwn(current, segment)) current = current[segment];
630
+ else return;
631
+ return current;
632
+ }
633
+ function setIn(value, segments, depth, next) {
634
+ const segment = segments[depth];
635
+ if (segment === void 0) return next;
636
+ const isIndex = INDEX.test(segment);
637
+ if (Array.isArray(value) || !isRecord$1(value) && isIndex) {
638
+ if (!isIndex) return value;
639
+ const list = Array.isArray(value) ? value : [];
640
+ const index = Number(segment);
641
+ const updated = setIn(list[index], segments, depth + 1, next);
642
+ if (updated === void 0) return index < list.length ? list.filter((_, i) => i !== index) : value;
643
+ if (Object.is(updated, list[index])) return value;
644
+ const copy = list.slice();
645
+ copy[index] = updated;
646
+ return copy;
647
+ }
648
+ const record = isRecord$1(value) ? value : {};
649
+ const has = Object.hasOwn(record, segment);
650
+ const updated = setIn(has ? record[segment] : void 0, segments, depth + 1, next);
651
+ if (updated === void 0) {
652
+ if (!has) return value;
653
+ const copy = { ...record };
654
+ delete copy[segment];
655
+ return copy;
656
+ }
657
+ if (has && Object.is(updated, record[segment])) return value;
658
+ return {
659
+ ...record,
660
+ [segment]: updated
661
+ };
662
+ }
663
+ /**
664
+ * Write a value at a path, immutably.
665
+ *
666
+ * Every subtree off the path is shared with the input, the input is never touched, and
667
+ * setting what is already there returns the input itself. Containers that do not exist are
668
+ * created (an array before an index, an object before a key). Keys the path does not
669
+ * mention — including ones a schema does not know about — are kept.
670
+ *
671
+ * @param value - The root value.
672
+ * @param path - Dot path; `""` replaces the root.
673
+ * @param next - The new value. `undefined` removes the key (or array element) instead.
674
+ * @returns The new root.
675
+ */
676
+ function setAtPath(value, path, next) {
677
+ return setIn(value, splitPath(path), 0, next);
678
+ }
679
+ //#endregion
680
+ //#region src/api/schemaValue.ts
681
+ /**
682
+ * Reading a schema as the shape of a *value*: what a node is, which fields it has, and
683
+ * what a fresh one looks like.
684
+ *
685
+ * `SchemaForm` asks "which control does this option deserve?". `SchemaValueForm` asks the
686
+ * deeper question — "what can this value be, all the way down?" — and the answer has to
687
+ * cover what Rust's serde does to enums:
688
+ *
689
+ * - a **plain enum** is `oneOf` of `{ const }`, or `enum`;
690
+ * - an **externally tagged** enum is `"None"` for a unit variant and `{ "Huber": { … } }`
691
+ * (or `{ "Fixed": 2 }`, a newtype) for a variant that carries data;
692
+ * - an **internally tagged** enum is an object whose `kind` (or any property that is a
693
+ * `const` in every variant) names the variant.
694
+ *
695
+ * Everything here is pure: the component only renders what these functions decide.
696
+ */
697
+ /** The longest fixed-length array shown as a row of cells rather than as JSON. */
698
+ const MAX_TUPLE = 32;
699
+ /** Discriminator names tried first; any other shared `const` property works too. */
700
+ const PREFERRED_DISCRIMINATORS = [
701
+ "kind",
702
+ "type",
703
+ "tag",
704
+ "variant"
705
+ ];
706
+ /** Recursion limit for seeding a value from a self-referential schema. */
707
+ const MAX_DEPTH = 8;
708
+ function isPrimitive(value) {
709
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
710
+ }
711
+ function isRecord(value) {
712
+ return typeof value === "object" && value !== null && !Array.isArray(value);
713
+ }
714
+ function fieldsOf(schema, omit) {
715
+ const required = new Set(schema.required ?? []);
716
+ return Object.entries(schema.properties ?? {}).filter(([key]) => key !== omit).map(([key, property]) => ({
717
+ key,
718
+ schema: property,
719
+ required: required.has(key)
720
+ }));
721
+ }
722
+ /** The primitives a `const` / `enum` variant fixes, or `undefined` if it is not one. */
723
+ function constValues(variant) {
724
+ if (variant.properties !== void 0) return void 0;
725
+ if (Object.hasOwn(variant, "const")) return isPrimitive(variant.const) ? [variant.const] : void 0;
726
+ if (Array.isArray(variant.enum) && variant.enum.length > 0 && variant.enum.every(isPrimitive)) return variant.enum;
727
+ }
728
+ function constString(property, root) {
729
+ if (property === void 0) return void 0;
730
+ const [value] = constValues(resolveSchema(property, root).schema) ?? [];
731
+ return typeof value === "string" ? value : void 0;
732
+ }
733
+ function classifyTagged(variants, root) {
734
+ if (!variants.every((variant) => variant.properties !== void 0)) return void 0;
735
+ const [first] = variants;
736
+ const keys = Object.keys(first?.properties ?? {});
737
+ const candidates = [...PREFERRED_DISCRIMINATORS.filter((key) => keys.includes(key)), ...keys.filter((key) => !PREFERRED_DISCRIMINATORS.includes(key))];
738
+ for (const discriminator of candidates) {
739
+ const tags = variants.map((variant) => constString(variant.properties?.[discriminator], root));
740
+ if (!tags.every((tag) => tag !== void 0)) continue;
741
+ if (new Set(tags).size !== tags.length) continue;
742
+ return {
743
+ kind: "tagged",
744
+ discriminator,
745
+ variants: variants.map((variant, index) => ({
746
+ tag: tags[index] ?? "",
747
+ label: variant.title ?? tags[index] ?? "",
748
+ description: variant.description,
749
+ schema: variant,
750
+ fields: fieldsOf(variant, discriminator)
751
+ }))
752
+ };
753
+ }
754
+ }
755
+ function classifyExternal(variants) {
756
+ const out = [];
757
+ for (const variant of variants) {
758
+ const units = constValues(variant);
759
+ if (units !== void 0) {
760
+ if (!units.every((unit) => typeof unit === "string")) return void 0;
761
+ for (const unit of units) out.push({
762
+ tag: String(unit),
763
+ label: variant.title ?? String(unit),
764
+ description: variant.description,
765
+ payload: void 0
766
+ });
767
+ continue;
768
+ }
769
+ const keys = Object.keys(variant.properties ?? {});
770
+ const [tag] = keys;
771
+ const payload = tag === void 0 ? void 0 : variant.properties?.[tag];
772
+ if (keys.length !== 1 || tag === void 0 || payload === void 0 || variant.additionalProperties === true) return;
773
+ out.push({
774
+ tag,
775
+ label: variant.title ?? tag,
776
+ description: variant.description,
777
+ payload
778
+ });
779
+ }
780
+ return new Set(out.map((variant) => variant.tag)).size === out.length ? {
781
+ kind: "external",
782
+ variants: out
783
+ } : void 0;
784
+ }
785
+ function classifyUnion(branches, root) {
786
+ const variants = branches.map((branch) => resolveSchema(branch, root).schema);
787
+ const options = [];
788
+ for (const variant of variants) for (const value of constValues(variant) ?? []) options.push({
789
+ value,
790
+ label: variant.title ?? String(value),
791
+ description: variant.description
792
+ });
793
+ if (variants.every((variant) => constValues(variant) !== void 0)) return {
794
+ kind: "enum",
795
+ options
796
+ };
797
+ return classifyTagged(variants, root) ?? classifyExternal(variants) ?? { kind: "json" };
798
+ }
799
+ function classifyArray(schema, root) {
800
+ if (schema.prefixItems !== void 0 && schema.prefixItems.length > 0) return {
801
+ kind: "tuple",
802
+ items: schema.prefixItems
803
+ };
804
+ const items = typeof schema.items === "object" ? schema.items : void 0;
805
+ if (items === void 0) return { kind: "json" };
806
+ const item = resolveSchema(items, root).schema;
807
+ const itemShape = classify(item, root);
808
+ if (itemShape.kind === "string") return {
809
+ kind: "string-list",
810
+ item: items
811
+ };
812
+ const count = schema.minItems;
813
+ if (count !== void 0 && count === schema.maxItems && count >= 1 && count <= MAX_TUPLE && (itemShape.kind === "number" || itemShape.kind === "integer" || itemShape.kind === "object")) return {
814
+ kind: "tuple",
815
+ items: Array.from({ length: count }, () => items)
816
+ };
817
+ return { kind: "json" };
818
+ }
819
+ function classify(schema, root) {
820
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum.every(isPrimitive) ? {
821
+ kind: "enum",
822
+ options: schema.enum.map((value) => ({
823
+ value,
824
+ label: String(value)
825
+ }))
826
+ } : { kind: "json" };
827
+ if (Object.hasOwn(schema, "const")) return isPrimitive(schema.const) ? {
828
+ kind: "enum",
829
+ options: [{
830
+ value: schema.const,
831
+ label: String(schema.const)
832
+ }]
833
+ } : { kind: "json" };
834
+ const branches = schema.oneOf ?? schema.anyOf;
835
+ if (branches !== void 0 && branches.length > 0) return classifyUnion(branches, root);
836
+ if (schema.properties !== void 0) {
837
+ const fields = fieldsOf(schema);
838
+ return fields.length > 0 || schema.additionalProperties === false ? {
839
+ kind: "object",
840
+ fields
841
+ } : { kind: "json" };
842
+ }
843
+ switch (schema.type) {
844
+ case "string": return { kind: "string" };
845
+ case "integer": return { kind: "integer" };
846
+ case "number": return { kind: "number" };
847
+ case "boolean": return { kind: "boolean" };
848
+ case "array": return classifyArray(schema, root);
849
+ default: return { kind: "json" };
850
+ }
851
+ }
852
+ /**
853
+ * What a schema node is.
854
+ *
855
+ * Looks through `$ref` and the "or null" encodings first (see `resolveSchema`), then
856
+ * decides among the shapes of `SchemaShape`. A node it does not recognise is `json`, never
857
+ * an error: a caller can always express what the model accepts.
858
+ *
859
+ * @param node - A schema node as written.
860
+ * @param root - The document holding `$defs` (defaults to `node`).
861
+ * @returns The shape.
862
+ */
863
+ function shapeOf(node, root = node) {
864
+ return classify(resolveSchema(node, root).schema, root);
865
+ }
866
+ /**
867
+ * The variant an internally tagged value is on.
868
+ *
869
+ * @param shape - A `tagged` shape.
870
+ * @param value - The current value.
871
+ * @returns The variant whose tag is in the value's discriminator, or `undefined` for a
872
+ * value that names none (absent, not an object, an unknown tag).
873
+ */
874
+ function activeTagged(shape, value) {
875
+ const tag = isRecord(value) ? value[shape.discriminator] : void 0;
876
+ return typeof tag === "string" ? shape.variants.find((variant) => variant.tag === tag) : void 0;
877
+ }
878
+ /**
879
+ * The variant an externally tagged value is on.
880
+ *
881
+ * @param shape - An `external` shape.
882
+ * @param value - The current value: the string of a unit variant, or an object with the
883
+ * variant's name as its key.
884
+ * @returns The variant, or `undefined` for a value that names none.
885
+ */
886
+ function activeExternal(shape, value) {
887
+ if (typeof value === "string") return shape.variants.find((variant) => variant.payload === void 0 && variant.tag === value);
888
+ if (!isRecord(value)) return void 0;
889
+ return shape.variants.find((variant) => variant.payload !== void 0 && Object.hasOwn(value, variant.tag));
890
+ }
891
+ function seedOf(schema, root, depth, notNull) {
892
+ const { schema: s, nullable } = resolveSchema(schema, root);
893
+ if (s.default !== void 0 && !(notNull && s.default === null)) return s.default;
894
+ if (nullable && !notNull) return null;
895
+ if (depth > MAX_DEPTH) return null;
896
+ const shape = classify(s, root);
897
+ switch (shape.kind) {
898
+ case "enum": return shape.options[0]?.value ?? null;
899
+ case "string": return "";
900
+ case "boolean": return false;
901
+ case "integer":
902
+ case "number": return seedNumber(s, shape.kind === "integer");
903
+ case "object": {
904
+ const out = {};
905
+ for (const field of shape.fields) {
906
+ const hasDefault = resolveSchema(field.schema, root).schema.default !== void 0;
907
+ if (field.required || hasDefault) out[field.key] = seedOf(field.schema, root, depth + 1, false);
908
+ }
909
+ return out;
910
+ }
911
+ case "tagged": {
912
+ const [variant] = shape.variants;
913
+ return variant === void 0 ? null : seedTagged(shape, variant, root, depth);
914
+ }
915
+ case "external": {
916
+ const [variant] = shape.variants;
917
+ return variant === void 0 ? null : seedExternal(variant, root, depth);
918
+ }
919
+ case "tuple": return shape.items.map((item) => seedOf(item, root, depth + 1, false));
920
+ case "string-list": return [];
921
+ case "json": {
922
+ const [first] = s.oneOf ?? s.anyOf ?? [];
923
+ if (first !== void 0) return seedOf(first, root, depth + 1, false);
924
+ if (s.type === "array") return [];
925
+ return s.type === "object" ? {} : null;
926
+ }
927
+ }
928
+ }
929
+ function seedNumber(schema, integer) {
930
+ const lower = schema.minimum ?? (schema.format?.startsWith("uint") === true ? 0 : void 0);
931
+ const exclusiveLower = schema.exclusiveMinimum;
932
+ const upper = schema.maximum ?? schema.exclusiveMaximum;
933
+ let value = 0;
934
+ if (lower !== void 0 && value < lower) value = lower;
935
+ if (exclusiveLower !== void 0 && value <= exclusiveLower) value = integer ? exclusiveLower + 1 : upper !== void 0 ? (exclusiveLower + upper) / 2 : exclusiveLower + 1;
936
+ if (upper !== void 0 && value > upper) value = lower ?? upper;
937
+ return integer ? Math.ceil(value) : value;
938
+ }
939
+ function seedTagged(shape, variant, root, depth) {
940
+ const body = seedOf(variant.schema, root, depth + 1, false);
941
+ return {
942
+ ...isRecord(body) ? body : {},
943
+ [shape.discriminator]: variant.tag
944
+ };
945
+ }
946
+ function seedExternal(variant, root, depth) {
947
+ return variant.payload === void 0 ? variant.tag : { [variant.tag]: seedOf(variant.payload, root, depth + 1, false) };
948
+ }
949
+ /**
950
+ * A fresh value for a schema.
951
+ *
952
+ * Takes the `default` when there is one (a `default` written beside a `$ref` wins over the
953
+ * target's), `null` for a nullable node, and otherwise builds the value from the shape:
954
+ * an object gets its required fields and the fields that have a default, an enum its first
955
+ * value, a union its first variant, a number the nearest legal value to 0, a string `""`.
956
+ * The result is JSON, and for a schema this package can read, valid against it.
957
+ *
958
+ * @param schema - A schema node.
959
+ * @param root - The document holding `$defs` (defaults to `schema`).
960
+ * @returns The seed value.
961
+ */
962
+ function defaultValueForSchema(schema, root = schema) {
963
+ return seedOf(schema, root, 0, false);
964
+ }
965
+ /**
966
+ * The seed for a node that is switched on from `null`: its default, unless that default is
967
+ * itself `null`, in which case the value the shape implies.
968
+ *
969
+ * @param schema - A schema node.
970
+ * @param root - The document holding `$defs`.
971
+ * @returns A value that is not `null` (for a node that can hold anything else).
972
+ */
973
+ function seedNotNull(schema, root) {
974
+ return seedOf(schema, root, 0, true);
975
+ }
976
+ /**
977
+ * The value for a union after the user picks a variant: the variant's own seed, with its
978
+ * tag in place.
979
+ *
980
+ * @param shape - A `tagged` or `external` shape.
981
+ * @param tag - The chosen variant's tag.
982
+ * @param root - The document holding `$defs`.
983
+ * @returns The new value, or `undefined` if the shape has no such variant.
984
+ */
985
+ function seedVariant(shape, tag, root) {
986
+ if (shape.kind === "tagged") {
987
+ const variant = shape.variants.find((candidate) => candidate.tag === tag);
988
+ return variant === void 0 ? void 0 : seedTagged(shape, variant, root, 0);
989
+ }
990
+ const variant = shape.variants.find((candidate) => candidate.tag === tag);
991
+ return variant === void 0 ? void 0 : seedExternal(variant, root, 0);
992
+ }
993
+ /** The fields of the shape for the value as it stands (the active variant, for a union). */
994
+ function childrenOf(shape, value) {
995
+ switch (shape.kind) {
996
+ case "object": return shape.fields;
997
+ case "tagged": return (activeTagged(shape, value) ?? shape.variants[0])?.fields ?? [];
998
+ case "external": {
999
+ const variant = activeExternal(shape, value);
1000
+ return variant?.payload === void 0 ? [] : [{
1001
+ key: variant.tag,
1002
+ schema: variant.payload,
1003
+ required: true
1004
+ }];
1005
+ }
1006
+ case "tuple": return shape.items.map((schema, index) => ({
1007
+ key: String(index),
1008
+ schema,
1009
+ required: true
1010
+ }));
1011
+ case "string-list": return Array.isArray(value) ? value.map((_, index) => ({
1012
+ key: String(index),
1013
+ schema: shape.item,
1014
+ required: true
1015
+ })) : [];
1016
+ default: return [];
1017
+ }
1018
+ }
1019
+ /** The child called `segment`, wherever it is — the active variant first, then any. */
1020
+ function findChild(shape, segment, value) {
1021
+ switch (shape.kind) {
1022
+ case "tagged": {
1023
+ const active = activeTagged(shape, value);
1024
+ const variants = active === void 0 ? shape.variants : [active, ...shape.variants];
1025
+ for (const variant of variants) {
1026
+ const field = variant.fields.find((candidate) => candidate.key === segment);
1027
+ if (field !== void 0) return field;
1028
+ }
1029
+ return;
1030
+ }
1031
+ case "external": {
1032
+ const variant = shape.variants.find((candidate) => candidate.payload !== void 0 && candidate.tag === segment);
1033
+ return variant?.payload === void 0 ? void 0 : {
1034
+ key: segment,
1035
+ schema: variant.payload,
1036
+ required: true
1037
+ };
1038
+ }
1039
+ case "tuple": {
1040
+ const schema = shape.items[Number(segment)];
1041
+ return schema === void 0 ? void 0 : {
1042
+ key: segment,
1043
+ schema,
1044
+ required: true
1045
+ };
1046
+ }
1047
+ case "string-list": return /^\d+$/.test(segment) ? {
1048
+ key: segment,
1049
+ schema: shape.item,
1050
+ required: true
1051
+ } : void 0;
1052
+ default: return childrenOf(shape, value).find((candidate) => candidate.key === segment);
1053
+ }
1054
+ }
1055
+ /**
1056
+ * The field at a dot path.
1057
+ *
1058
+ * Walks the schema, not the value: a path through a union resolves in the variant the
1059
+ * `value` is on if it has the field, else in whichever variant does, so a `UiSchema` path
1060
+ * can name a field that is not showing right now.
1061
+ *
1062
+ * @param schema - The root schema.
1063
+ * @param path - Dot path from the root (`solver.robust_loss.Huber.scale`); `""` is the root.
1064
+ * @param root - The document holding `$defs` (defaults to `schema`).
1065
+ * @param value - The current value, to choose between a union's variants.
1066
+ * @returns The field (its schema as written, and whether it is required), or `undefined`
1067
+ * where the path leaves the schema.
1068
+ */
1069
+ function fieldAt(schema, path, root = schema, value) {
1070
+ let info = {
1071
+ key: "",
1072
+ schema,
1073
+ required: true
1074
+ };
1075
+ let current = value;
1076
+ for (const segment of splitPath(path)) {
1077
+ const next = findChild(shapeOf(info.schema, root), segment, current);
1078
+ if (next === void 0) return void 0;
1079
+ info = next;
1080
+ current = getAtPath(current, segment);
1081
+ }
1082
+ return info;
1083
+ }
1084
+ /**
1085
+ * The fields that are editable at a path, as the form would list them: an object's fields
1086
+ * in schema order, the active variant's fields (without the discriminator) for an internally
1087
+ * tagged union, the variant's payload for an externally tagged one, a tuple's positions.
1088
+ *
1089
+ * @param schema - The root schema.
1090
+ * @param path - Dot path from the root; `""` for the root.
1091
+ * @param root - The document holding `$defs` (defaults to `schema`).
1092
+ * @param value - The current root value, to choose between a union's variants (the first
1093
+ * variant when absent).
1094
+ * @returns The fields; empty for a leaf or a path outside the schema.
1095
+ */
1096
+ function fieldsAt(schema, path, root = schema, value) {
1097
+ const info = fieldAt(schema, path, root, value);
1098
+ return info === void 0 ? [] : childrenOf(shapeOf(info.schema, root), getAtPath(value, path));
1099
+ }
1100
+ //#endregion
1101
+ //#region src/api/uiSchema.ts
1102
+ const NO_UI$1 = {};
1103
+ /**
1104
+ * The presentation for a path: the exact entry, merged over the wildcard entry
1105
+ * (`cameras.*.id`) when the path has array indices.
1106
+ *
1107
+ * @param ui - The app's `UiSchema`, if any.
1108
+ * @param path - The field's dot path.
1109
+ * @returns The presentation; `{}` where the app said nothing.
1110
+ */
1111
+ function fieldUiAt(ui, path) {
1112
+ const table = ui?.fields;
1113
+ if (table === void 0) return NO_UI$1;
1114
+ const wildcard = path.replaceAll(/(^|\.)\d+(?=\.|$)/g, "$1*");
1115
+ const general = wildcard === path ? void 0 : table[wildcard];
1116
+ const exact = table[path];
1117
+ if (general === void 0) return exact ?? NO_UI$1;
1118
+ return exact === void 0 ? general : {
1119
+ ...general,
1120
+ ...exact
1121
+ };
1122
+ }
1123
+ //#endregion
1124
+ //#region src/api/firstParagraph.ts
1125
+ /**
1126
+ * Descriptions are Markdown (Rustdoc comments, docstrings) and the form shows them as plain
1127
+ * text in a hint. This is the conversion.
1128
+ */
1129
+ /** Text and a URL: `[text](url)` shows as `text`. */
1130
+ const LINK = /\[([^\]]+)\]\([^)]*\)/g;
1131
+ /** Rustdoc intra-doc link: ``[`Foo::bar`]`` shows as `Foo::bar`. */
1132
+ const CODE_LINK = /\[(`+)([^`]+)\1\]/g;
1133
+ const AUTOLINK = /<(https?:\/\/[^>\s]+)>/g;
1134
+ const CODE = /(`+)([^`]+?)\1/g;
1135
+ const BOLD = /(\*\*|__)(?=\S)(.+?)(?<=\S)\1/g;
1136
+ /** `*em*`; a lone `*` between spaces (a product) is not emphasis. */
1137
+ const STAR = /(?<![\\*])\*(?=\S)([^*]+?)(?<=\S)\*(?!\*)/g;
1138
+ /** `_em_`, but never inside a word: `snake_case_name` is not emphasis. */
1139
+ const UNDERSCORE = /(?<![\w\\])_(?=\S)([^_]+?)(?<=\S)_(?!\w)/g;
1140
+ const ESCAPE = /\\([\\`*_{}[\]()#+\-.!|<>~])/g;
1141
+ /**
1142
+ * The first paragraph of a Markdown description as plain text, for a one-line hint.
1143
+ *
1144
+ * Strips emphasis, inline code, links (text kept, URL dropped), Rustdoc intra-doc links and
1145
+ * backslash escapes, and joins the paragraph's lines with spaces. `snake_case` and a lone
1146
+ * `*` are left alone. Later paragraphs — a Rustdoc `# Example` section, say — are dropped.
1147
+ *
1148
+ * @param description - A schema `description`, or nothing.
1149
+ * @returns Plain text; `""` for no description.
1150
+ */
1151
+ function firstParagraph(description) {
1152
+ if (!description) return "";
1153
+ const [paragraph = ""] = description.trim().split(/\n[ \t]*\n/);
1154
+ return paragraph.replaceAll(/\s*\n\s*/g, " ").replaceAll(CODE_LINK, "$2").replaceAll(LINK, "$1").replaceAll(AUTOLINK, "$1").replaceAll(CODE, "$2").replaceAll(BOLD, "$2").replaceAll(STAR, "$1").replaceAll(UNDERSCORE, "$1").replaceAll(ESCAPE, "$1").replaceAll(/\s+/g, " ").trim();
1155
+ }
1156
+ //#endregion
1157
+ //#region src/components/valueForm/context.ts
1158
+ /**
1159
+ * What every node of a `SchemaValueForm` shares: the schema, the value, how to edit it, and
1160
+ * the app's layout. One context rather than props threaded through every container, because
1161
+ * a field is addressed by its path — it reads its own value and writes its own leaf, and
1162
+ * the containers in between need not know.
1163
+ */
1164
+ /** `null` outside a form. */
1165
+ const FormContext = createContext(null);
1166
+ /**
1167
+ * True inside a tuple row: cells drop their descriptions and range notes and sit in an
1168
+ * auto-fit grid, because a row of four numbers cannot afford a hint line each.
1169
+ */
1170
+ const DenseContext = createContext(false);
1171
+ /** The enclosing form's state. */
1172
+ function useForm() {
1173
+ const state = use(FormContext);
1174
+ if (state === null) throw new Error("A SchemaValueForm field was rendered outside its form.");
1175
+ return state;
1176
+ }
1177
+ //#endregion
1178
+ //#region src/components/valueForm/chrome.tsx
1179
+ /**
1180
+ * The furniture around a field: the grid it sits in, the cell it takes, and the hint and
1181
+ * range note beside its label. Shared by every control so that "where does the description
1182
+ * go" is decided once.
1183
+ */
1184
+ /**
1185
+ * The grid cell a field takes: the full row (`sm:col-span-2`) where it has two columns to
1186
+ * span, nothing otherwise.
1187
+ *
1188
+ * @param columns - The form's column count.
1189
+ * @param ui - The field's presentation (its `span` wins).
1190
+ * @param fallback - The span for a field the app said nothing about.
1191
+ * @returns A Tailwind class, or `undefined`.
1192
+ */
1193
+ function spanClass(columns, ui, fallback) {
1194
+ return columns === 2 && (ui.span ?? fallback) === 2 ? "sm:col-span-2" : void 0;
1195
+ }
1196
+ /** The field grid: two columns on `sm:` (or one), or an auto-fit row inside a tuple. */
1197
+ function Grid({ children }) {
1198
+ const { columns } = useForm();
1199
+ const dense = use(DenseContext);
1200
+ const density = useDensity();
1201
+ return /* @__PURE__ */ jsx("div", {
1202
+ className: cn("grid min-w-0", dense ? "grid-cols-[repeat(auto-fit,minmax(5.5rem,1fr))] gap-2" : cn(byDensity(density, "gap-x-5 gap-y-4", "gap-x-4 gap-y-2.5"), columns === 2 ? "grid-cols-1 sm:grid-cols-2" : "grid-cols-1")),
1203
+ children
1204
+ });
1205
+ }
1206
+ function present(node) {
1207
+ return node !== void 0 && node !== null && node !== false && node !== "";
1208
+ }
1209
+ /**
1210
+ * What a field shows besides its label: the description as an `InfoHint` or as an inline
1211
+ * line (or not at all), and the range note, together as the `Field` annotation.
1212
+ *
1213
+ * @param meta - The field.
1214
+ * @param range - The bounds as text, for a number.
1215
+ * @returns The hint (for a control that has no annotation slot), the inline description,
1216
+ * and the annotation.
1217
+ */
1218
+ function useChrome(meta, range = null) {
1219
+ const dense = use(DenseContext);
1220
+ const mode = meta.ui.descriptionAs ?? "hint";
1221
+ const text = meta.ui.hint ?? firstParagraph(meta.schema.description);
1222
+ const shown = !dense && present(text);
1223
+ const hint = shown && mode === "hint" ? /* @__PURE__ */ jsx(InfoHint, {
1224
+ label: `About ${meta.label}`,
1225
+ children: text
1226
+ }) : null;
1227
+ const description = shown && mode === "inline" ? text : void 0;
1228
+ const note = dense ? null : range;
1229
+ return {
1230
+ hint,
1231
+ description,
1232
+ annotation: note !== null || hint !== null ? /* @__PURE__ */ jsxs("span", {
1233
+ className: "inline-flex items-center gap-1.5",
1234
+ children: [note, hint]
1235
+ }) : void 0
1236
+ };
1237
+ }
1238
+ //#endregion
1239
+ //#region src/api/numberSpec.ts
1240
+ /**
1241
+ * Collect a number field's rules.
1242
+ *
1243
+ * `format: uint…` (Rust's unsigned widths) means "at least 0" even where the schema says
1244
+ * nothing else. A bound in `ui` replaces the schema's bound of that side, exclusive form
1245
+ * included.
1246
+ *
1247
+ * @param schema - The field's resolved schema.
1248
+ * @param ui - The app's presentation for the field.
1249
+ * @returns The rules.
1250
+ */
1251
+ function numberSpec(schema, ui = {}) {
1252
+ const integer = schema.type === "integer";
1253
+ const floor = schema.format?.startsWith("uint") === true ? 0 : void 0;
1254
+ return {
1255
+ integer,
1256
+ min: ui.min ?? schema.minimum ?? floor,
1257
+ max: ui.max ?? schema.maximum,
1258
+ exclusiveMin: ui.min === void 0 ? schema.exclusiveMinimum : void 0,
1259
+ exclusiveMax: ui.max === void 0 ? schema.exclusiveMaximum : void 0,
1260
+ step: ui.step ?? schema.multipleOf ?? (integer ? 1 : "any"),
1261
+ unit: ui.unit ?? schema["x-unit"]
1262
+ };
1263
+ }
1264
+ /**
1265
+ * Why a number is not acceptable.
1266
+ *
1267
+ * @param spec - The field's rules.
1268
+ * @param value - The parsed number.
1269
+ * @returns A short sentence for the field's error line, or `undefined` when it is fine.
1270
+ */
1271
+ function checkNumber(spec, value) {
1272
+ if (!Number.isFinite(value)) return "Enter a number";
1273
+ if (spec.integer && !Number.isInteger(value)) return "Must be a whole number";
1274
+ if (spec.min !== void 0 && value < spec.min) return `Must be ≥ ${spec.min}`;
1275
+ if (spec.exclusiveMin !== void 0 && value <= spec.exclusiveMin) return `Must be > ${spec.exclusiveMin}`;
1276
+ if (spec.max !== void 0 && value > spec.max) return `Must be ≤ ${spec.max}`;
1277
+ if (spec.exclusiveMax !== void 0 && value >= spec.exclusiveMax) return `Must be < ${spec.exclusiveMax}`;
1278
+ }
1279
+ /**
1280
+ * The bounds as a reader should see them, exclusive ones included.
1281
+ *
1282
+ * @param spec - The field's rules.
1283
+ * @returns `"≥ 2, ≤ 64"`, or `null` for an unbounded field.
1284
+ */
1285
+ function rangeText(spec) {
1286
+ const parts = [];
1287
+ if (spec.min !== void 0) parts.push(`≥ ${spec.min}`);
1288
+ else if (spec.exclusiveMin !== void 0) parts.push(`> ${spec.exclusiveMin}`);
1289
+ if (spec.max !== void 0) parts.push(`≤ ${spec.max}`);
1290
+ else if (spec.exclusiveMax !== void 0) parts.push(`< ${spec.exclusiveMax}`);
1291
+ return parts.length > 0 ? parts.join(", ") : null;
1292
+ }
1293
+ //#endregion
1294
+ //#region src/components/valueForm/leaves.tsx
1295
+ /**
1296
+ * The controls of a `SchemaValueForm`: one per kind of leaf value. Each reads its own value
1297
+ * from the form by path and writes its own leaf back; none knows its neighbours.
1298
+ */
1299
+ /** `required` as the marker shows it: a nullable field is never mandatory. */
1300
+ function marked(meta) {
1301
+ return meta.required && !meta.nullable;
1302
+ }
1303
+ /** Where `null` is a legal value, an empty control says so. */
1304
+ const NULL_PLACEHOLDER = "none";
1305
+ /** A number field: bounds, unit and a verdict on what was typed. */
1306
+ function NumberLeaf({ meta }) {
1307
+ const form = useForm();
1308
+ const value = getAtPath(form.value, meta.path);
1309
+ const spec = numberSpec(meta.schema, meta.ui);
1310
+ const chrome = useChrome(meta, rangeText(spec));
1311
+ const [error, setError] = useState();
1312
+ const fallback = meta.schema.default;
1313
+ const restore = meta.ui.restoreDefaultOnClear ?? true;
1314
+ let onClear;
1315
+ if (meta.nullable) onClear = () => form.setValue(meta.path, null);
1316
+ else if (restore && typeof fallback === "number") onClear = () => form.setValue(meta.path, fallback);
1317
+ else if (!meta.required) onClear = () => form.setValue(meta.path, void 0);
1318
+ else if (restore) onClear = () => form.setValue(meta.path, defaultValueForSchema(meta.schema, form.schema));
1319
+ const judge = (event) => {
1320
+ const text = event.currentTarget.value;
1321
+ const parsed = parseNumber(text);
1322
+ if (text.trim() === "") setError(void 0);
1323
+ else setError(parsed === null ? "Enter a number" : checkNumber(spec, parsed));
1324
+ };
1325
+ return /* @__PURE__ */ jsx(Field, {
1326
+ label: meta.label,
1327
+ required: marked(meta),
1328
+ annotation: chrome.annotation,
1329
+ description: chrome.description,
1330
+ error,
1331
+ className: spanClass(form.columns, meta.ui, 1),
1332
+ children: /* @__PURE__ */ jsx(NumberInput, {
1333
+ "aria-label": meta.label,
1334
+ disabled: form.disabled,
1335
+ placeholder: meta.nullable ? NULL_PLACEHOLDER : typeof fallback === "number" ? String(fallback) : void 0,
1336
+ value: typeof value === "number" ? value : null,
1337
+ min: spec.min,
1338
+ max: spec.max,
1339
+ step: spec.step,
1340
+ unit: spec.unit,
1341
+ onChange: judge,
1342
+ onBlur: () => setError(void 0),
1343
+ onValueChange: (next) => {
1344
+ if (checkNumber(spec, next) === void 0) form.setValue(meta.path, next);
1345
+ },
1346
+ onClear
1347
+ })
1348
+ });
1349
+ }
1350
+ /** A string field. Where `null` is legal, emptying it means `null`. */
1351
+ function TextLeaf({ meta }) {
1352
+ const form = useForm();
1353
+ const value = getAtPath(form.value, meta.path);
1354
+ const chrome = useChrome(meta);
1355
+ const fallback = meta.schema.default;
1356
+ return /* @__PURE__ */ jsx(Field, {
1357
+ label: meta.label,
1358
+ required: marked(meta),
1359
+ annotation: chrome.annotation,
1360
+ description: chrome.description,
1361
+ className: spanClass(form.columns, meta.ui, 1),
1362
+ children: /* @__PURE__ */ jsx(Input, {
1363
+ className: "font-mono",
1364
+ autoComplete: "off",
1365
+ spellCheck: false,
1366
+ "aria-label": meta.label,
1367
+ disabled: form.disabled,
1368
+ placeholder: meta.nullable ? NULL_PLACEHOLDER : typeof fallback === "string" ? fallback : void 0,
1369
+ value: typeof value === "string" ? value : "",
1370
+ onChange: (event) => {
1371
+ const text = event.currentTarget.value;
1372
+ form.setValue(meta.path, meta.nullable && text === "" ? null : text);
1373
+ }
1374
+ })
1375
+ });
1376
+ }
1377
+ /** A choice among a few values (all shown) or many (a picker). */
1378
+ function Chooser({ label, options, value, onChoose, unsetLabel, widget, disabled }) {
1379
+ const size = byDensity(useDensity(), "md", "sm");
1380
+ return widget === "segmented" || widget !== "select" && options.length <= 3 && unsetLabel === void 0 ? /* @__PURE__ */ jsx(SegmentedControl, {
1381
+ "aria-label": label,
1382
+ size,
1383
+ disabled,
1384
+ value,
1385
+ options,
1386
+ onValueChange: onChoose
1387
+ }) : /* @__PURE__ */ jsx(Select, {
1388
+ "aria-label": label,
1389
+ disabled,
1390
+ value,
1391
+ options,
1392
+ placeholder: unsetLabel ?? "Choose…",
1393
+ unsetLabel,
1394
+ onValueChange: onChoose
1395
+ });
1396
+ }
1397
+ /** A closed set of primitives: `enum`, `const`, or `oneOf` of `{ const }`. */
1398
+ function EnumLeaf({ meta, options }) {
1399
+ const form = useForm();
1400
+ const dense = use(DenseContext);
1401
+ const value = getAtPath(form.value, meta.path);
1402
+ const chrome = useChrome(meta);
1403
+ const shown = options.map((option) => ({
1404
+ value: String(option.value),
1405
+ label: meta.ui.enumLabels?.[String(option.value)] ?? option.label
1406
+ }));
1407
+ const selected = options.find((option) => option.value === value);
1408
+ const explained = !dense && meta.ui.descriptionAs !== "none" ? firstParagraph(selected?.description) : "";
1409
+ const description = explained !== "" && chrome.description !== void 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
1410
+ chrome.description,
1411
+ " ",
1412
+ explained
1413
+ ] }) : explained !== "" ? explained : chrome.description;
1414
+ return /* @__PURE__ */ jsx(Field, {
1415
+ as: "group",
1416
+ label: meta.label,
1417
+ required: marked(meta),
1418
+ annotation: chrome.annotation,
1419
+ description,
1420
+ className: spanClass(form.columns, meta.ui, 1),
1421
+ children: /* @__PURE__ */ jsx(Chooser, {
1422
+ label: meta.label,
1423
+ options: shown,
1424
+ value: selected === void 0 ? "" : String(selected.value),
1425
+ widget: meta.ui.widget,
1426
+ disabled: form.disabled,
1427
+ unsetLabel: meta.nullable ? "None" : void 0,
1428
+ onChoose: (chosen) => {
1429
+ if (chosen === "") {
1430
+ if (meta.nullable) form.setValue(meta.path, null);
1431
+ return;
1432
+ }
1433
+ const option = options.find((candidate) => String(candidate.value) === chosen);
1434
+ if (option !== void 0) form.setValue(meta.path, option.value);
1435
+ }
1436
+ })
1437
+ });
1438
+ }
1439
+ /** A boolean: a switch (the default) or a checkbox. */
1440
+ function BooleanLeaf({ meta }) {
1441
+ const form = useForm();
1442
+ const value = getAtPath(form.value, meta.path);
1443
+ const chrome = useChrome(meta);
1444
+ const props = {
1445
+ checked: value === true,
1446
+ onCheckedChange: (next) => form.setValue(meta.path, next),
1447
+ label: meta.label,
1448
+ description: chrome.description,
1449
+ disabled: form.disabled
1450
+ };
1451
+ return /* @__PURE__ */ jsxs("div", {
1452
+ className: cn("flex min-w-0 items-start gap-1.5", spanClass(form.columns, meta.ui, 1)),
1453
+ children: [meta.ui.widget === "checkbox" ? /* @__PURE__ */ jsx(Checkbox, { ...props }) : /* @__PURE__ */ jsx(Switch, { ...props }), chrome.hint !== null && /* @__PURE__ */ jsx("span", {
1454
+ className: "mt-0.5",
1455
+ children: chrome.hint
1456
+ })]
1457
+ });
1458
+ }
1459
+ function pretty(value) {
1460
+ return value === void 0 ? "" : JSON.stringify(value, null, 2);
1461
+ }
1462
+ /**
1463
+ * Anything the form has no control for, as JSON.
1464
+ *
1465
+ * What is typed is kept as typed. A valid edit goes to the form; an invalid one shows its
1466
+ * parse error and leaves the last good value where it was. The text only resets when the
1467
+ * value changes from outside.
1468
+ */
1469
+ function JsonLeaf({ meta }) {
1470
+ const form = useForm();
1471
+ const value = getAtPath(form.value, meta.path);
1472
+ const chrome = useChrome(meta);
1473
+ const canonical = JSON.stringify(value) ?? "";
1474
+ const [draft, setDraft] = useState(() => ({
1475
+ text: pretty(value),
1476
+ error: void 0,
1477
+ base: canonical
1478
+ }));
1479
+ if (draft.base !== canonical) setDraft({
1480
+ text: pretty(value),
1481
+ error: void 0,
1482
+ base: canonical
1483
+ });
1484
+ const edit = (text) => {
1485
+ if (text.trim() === "") {
1486
+ if (meta.required) setDraft({
1487
+ text,
1488
+ error: "Enter a JSON value",
1489
+ base: draft.base
1490
+ });
1491
+ else {
1492
+ setDraft({
1493
+ text,
1494
+ error: void 0,
1495
+ base: ""
1496
+ });
1497
+ form.setValue(meta.path, void 0);
1498
+ }
1499
+ return;
1500
+ }
1501
+ try {
1502
+ const parsed = JSON.parse(text);
1503
+ setDraft({
1504
+ text,
1505
+ error: void 0,
1506
+ base: JSON.stringify(parsed)
1507
+ });
1508
+ form.setValue(meta.path, parsed);
1509
+ } catch (problem) {
1510
+ setDraft({
1511
+ text,
1512
+ error: `Invalid JSON: ${problem instanceof Error ? problem.message : String(problem)}`,
1513
+ base: draft.base
1514
+ });
1515
+ }
1516
+ };
1517
+ return /* @__PURE__ */ jsx(Field, {
1518
+ label: meta.label,
1519
+ required: marked(meta),
1520
+ annotation: chrome.annotation,
1521
+ description: chrome.description,
1522
+ error: draft.error,
1523
+ className: spanClass(form.columns, meta.ui, 2),
1524
+ children: /* @__PURE__ */ jsx(Textarea, {
1525
+ rows: Math.min(Math.max(draft.text.split("\n").length, 3), 12),
1526
+ spellCheck: false,
1527
+ "aria-label": meta.label,
1528
+ disabled: form.disabled,
1529
+ value: draft.text,
1530
+ onChange: (event) => edit(event.currentTarget.value)
1531
+ })
1532
+ });
1533
+ }
1534
+ /** Grow or shrink the row ids to `length`, keeping the ids of the rows that stay. */
1535
+ function syncIds(rows, length) {
1536
+ if (rows.ids.length === length) return rows;
1537
+ const ids = rows.ids.slice(0, length);
1538
+ let next = rows.next;
1539
+ while (ids.length < length) ids.push(next++);
1540
+ return {
1541
+ ids,
1542
+ next
1543
+ };
1544
+ }
1545
+ /**
1546
+ * An array of strings as a list: one input per entry, add and remove.
1547
+ *
1548
+ * Each row has an id of its own, so removing the second of three keeps the focus and the
1549
+ * cursor of the others instead of re-keying them by position.
1550
+ */
1551
+ function StringListLeaf({ meta, minItems, maxItems }) {
1552
+ const form = useForm();
1553
+ const value = getAtPath(form.value, meta.path);
1554
+ const chrome = useChrome(meta);
1555
+ const raw = Array.isArray(value) ? value : [];
1556
+ const [rows, setRows] = useState(() => syncIds({
1557
+ ids: [],
1558
+ next: 0
1559
+ }, raw.length));
1560
+ const synced = syncIds(rows, raw.length);
1561
+ if (synced !== rows) setRows(synced);
1562
+ const write = (list) => form.setValue(meta.path, list);
1563
+ const canRemove = minItems === void 0 || raw.length > minItems;
1564
+ const canAdd = maxItems === void 0 || raw.length < maxItems;
1565
+ return /* @__PURE__ */ jsx(Field, {
1566
+ as: "group",
1567
+ label: meta.label,
1568
+ required: marked(meta),
1569
+ annotation: chrome.annotation,
1570
+ description: chrome.description,
1571
+ className: spanClass(form.columns, meta.ui, 2),
1572
+ children: /* @__PURE__ */ jsxs("div", {
1573
+ className: "flex flex-col gap-1.5",
1574
+ children: [raw.map((entry, index) => /* @__PURE__ */ jsxs("div", {
1575
+ className: "flex gap-1.5",
1576
+ children: [/* @__PURE__ */ jsx(Input, {
1577
+ className: "min-w-0 flex-1 font-mono",
1578
+ autoComplete: "off",
1579
+ spellCheck: false,
1580
+ "aria-label": `${meta.label} ${index + 1}`,
1581
+ disabled: form.disabled,
1582
+ value: displayValue(entry),
1583
+ onChange: (event) => {
1584
+ const copy = raw.slice();
1585
+ copy[index] = event.currentTarget.value;
1586
+ write(copy);
1587
+ }
1588
+ }), /* @__PURE__ */ jsx(Button, {
1589
+ variant: "ghost",
1590
+ "aria-label": `Remove ${meta.label} ${index + 1}`,
1591
+ disabled: form.disabled || !canRemove,
1592
+ onClick: () => {
1593
+ setRows({
1594
+ ids: synced.ids.filter((_, i) => i !== index),
1595
+ next: synced.next
1596
+ });
1597
+ write(raw.filter((_, i) => i !== index));
1598
+ },
1599
+ children: "×"
1600
+ })]
1601
+ }, synced.ids[index])), /* @__PURE__ */ jsx(Button, {
1602
+ className: "self-start",
1603
+ "aria-label": `Add ${meta.label}`,
1604
+ disabled: form.disabled || !canAdd,
1605
+ onClick: () => {
1606
+ setRows({
1607
+ ids: [...synced.ids, synced.next],
1608
+ next: synced.next + 1
1609
+ });
1610
+ write([...raw, ""]);
1611
+ },
1612
+ children: "Add"
1613
+ })]
1614
+ })
1615
+ });
1616
+ }
1617
+ //#endregion
1618
+ //#region src/components/valueForm/nodes.tsx
1619
+ /**
1620
+ * The tree of a `SchemaValueForm`: a field dispatcher and the containers that nest it.
1621
+ *
1622
+ * A node is addressed by its dot path. It reads its value from the form, writes it back by
1623
+ * path, and renders whatever its schema's shape calls for: a control for a leaf, a
1624
+ * fieldset for an object, a variant selector for a union, a row for a tuple, a switch for
1625
+ * a nullable composite.
1626
+ */
1627
+ const BOOLEANS = [{
1628
+ value: true,
1629
+ label: "true"
1630
+ }, {
1631
+ value: false,
1632
+ label: "false"
1633
+ }];
1634
+ /** Shapes that are a block of their own, so a nullable one gets a switch rather than an empty box. */
1635
+ function isComposite(shape) {
1636
+ return shape.kind === "object" || shape.kind === "tagged" || shape.kind === "external" || shape.kind === "tuple" || shape.kind === "string-list";
1637
+ }
1638
+ /** `ui.widget` can change what an array or any value is edited as. */
1639
+ function applyWidget(shape, meta, value) {
1640
+ const items = typeof meta.schema.items === "object" ? meta.schema.items : void 0;
1641
+ switch (meta.ui.widget) {
1642
+ case "json": return { kind: "json" };
1643
+ case "string-list": return meta.schema.type === "array" ? {
1644
+ kind: "string-list",
1645
+ item: items ?? { type: "string" }
1646
+ } : shape;
1647
+ case "tuple-row": return items !== void 0 && Array.isArray(value) ? {
1648
+ kind: "tuple",
1649
+ items: value.map(() => items)
1650
+ } : shape;
1651
+ default: return shape;
1652
+ }
1653
+ }
1654
+ /**
1655
+ * One field of the form, at a path.
1656
+ *
1657
+ * Honours the app's `hidden` and `renderField`, then renders the control or container its
1658
+ * schema's shape calls for. A nullable composite (an object that may be `null`) gets a
1659
+ * switch; a nullable leaf is an empty control.
1660
+ */
1661
+ function FieldNode({ path, name, node, required, bare = false }) {
1662
+ const form = useForm();
1663
+ const ui = fieldUiAt(form.ui, path);
1664
+ if (ui.hidden === true) return null;
1665
+ const { schema, nullable } = resolveSchema(node, form.schema);
1666
+ const value = getAtPath(form.value, path);
1667
+ const meta = {
1668
+ path,
1669
+ label: ui.label ?? labelFor(name, node),
1670
+ required,
1671
+ node,
1672
+ schema,
1673
+ nullable,
1674
+ ui
1675
+ };
1676
+ const shape = applyWidget(shapeOf(schema, form.schema), meta, value);
1677
+ if (form.renderField !== void 0) {
1678
+ const custom = form.renderField({
1679
+ path,
1680
+ schema,
1681
+ value,
1682
+ onChange: (next) => form.setValue(path, next),
1683
+ disabled: form.disabled
1684
+ });
1685
+ if (custom !== void 0) return /* @__PURE__ */ jsx("div", {
1686
+ className: spanClass(form.columns, ui, isComposite(shape) ? 2 : 1),
1687
+ children: custom
1688
+ });
1689
+ }
1690
+ if (nullable && isComposite(shape)) return /* @__PURE__ */ jsx(NullableNode, {
1691
+ meta,
1692
+ shape
1693
+ });
1694
+ return /* @__PURE__ */ jsx(ShapeNode, {
1695
+ meta,
1696
+ shape,
1697
+ bare
1698
+ });
1699
+ }
1700
+ /** Render a resolved shape. */
1701
+ function ShapeNode({ meta, shape, bare }) {
1702
+ switch (shape.kind) {
1703
+ case "integer":
1704
+ case "number": return /* @__PURE__ */ jsx(NumberLeaf, { meta });
1705
+ case "string": return /* @__PURE__ */ jsx(TextLeaf, { meta });
1706
+ case "boolean": return meta.nullable ? /* @__PURE__ */ jsx(EnumLeaf, {
1707
+ meta,
1708
+ options: BOOLEANS
1709
+ }) : /* @__PURE__ */ jsx(BooleanLeaf, { meta });
1710
+ case "enum": return /* @__PURE__ */ jsx(EnumLeaf, {
1711
+ meta,
1712
+ options: shape.options
1713
+ });
1714
+ case "string-list": return /* @__PURE__ */ jsx(StringListLeaf, {
1715
+ meta,
1716
+ minItems: meta.schema.minItems,
1717
+ maxItems: meta.schema.maxItems
1718
+ });
1719
+ case "json": return /* @__PURE__ */ jsx(JsonLeaf, { meta });
1720
+ case "object": return /* @__PURE__ */ jsx(ObjectNode, {
1721
+ meta,
1722
+ fields: shape.fields,
1723
+ bare
1724
+ });
1725
+ case "tagged":
1726
+ case "external": return /* @__PURE__ */ jsx(UnionNode, {
1727
+ meta,
1728
+ shape,
1729
+ bare
1730
+ });
1731
+ case "tuple": return /* @__PURE__ */ jsx(TupleNode, {
1732
+ meta,
1733
+ shape,
1734
+ bare
1735
+ });
1736
+ }
1737
+ }
1738
+ /** The fields of an object that are neither hidden by the app nor claimed by a group. */
1739
+ function useVisible(path, fields) {
1740
+ const form = useForm();
1741
+ return fields.filter((field) => {
1742
+ const child = joinPath(path, field.key);
1743
+ return !form.claimed.has(child) && fieldUiAt(form.ui, child).hidden !== true;
1744
+ });
1745
+ }
1746
+ /**
1747
+ * The fields of an object, each as a node, skipping hidden ones and ones a group has claimed.
1748
+ * Renders nothing when none is left.
1749
+ */
1750
+ function ObjectBody({ path, fields }) {
1751
+ const visible = useVisible(path, fields);
1752
+ if (visible.length === 0) return null;
1753
+ return /* @__PURE__ */ jsx(Grid, { children: visible.map((field) => /* @__PURE__ */ jsx(FieldNode, {
1754
+ path: joinPath(path, field.key),
1755
+ name: field.key,
1756
+ node: field.schema,
1757
+ required: field.required
1758
+ }, field.key)) });
1759
+ }
1760
+ /** The frame of a composite field: its label and hint over its content. `bare` drops the frame. */
1761
+ function Frame({ meta, bare, children }) {
1762
+ const form = useForm();
1763
+ const dense = use(DenseContext);
1764
+ const density = useDensity();
1765
+ const chrome = useChrome(meta);
1766
+ if (bare) return /* @__PURE__ */ jsx("div", {
1767
+ className: "flex min-w-0 flex-col gap-3",
1768
+ children
1769
+ });
1770
+ return /* @__PURE__ */ jsxs("fieldset", {
1771
+ className: cn("flex min-w-0 flex-col gap-3 rounded-panel border border-line", byDensity(density, "p-3", "p-2"), !dense && spanClass(form.columns, meta.ui, 2)),
1772
+ children: [
1773
+ /* @__PURE__ */ jsx("legend", {
1774
+ className: "px-1",
1775
+ children: /* @__PURE__ */ jsxs("span", {
1776
+ className: "inline-flex items-center gap-1.5 text-xs font-semibold text-fg",
1777
+ children: [meta.label, chrome.hint]
1778
+ })
1779
+ }),
1780
+ chrome.description !== void 0 && /* @__PURE__ */ jsx("p", {
1781
+ className: "text-xs leading-snug text-fg-muted",
1782
+ children: chrome.description
1783
+ }),
1784
+ children
1785
+ ]
1786
+ });
1787
+ }
1788
+ function ObjectNode({ meta, fields, bare }) {
1789
+ if (useVisible(meta.path, fields).length === 0) return null;
1790
+ return /* @__PURE__ */ jsx(Frame, {
1791
+ meta,
1792
+ bare,
1793
+ children: /* @__PURE__ */ jsx(ObjectBody, {
1794
+ path: meta.path,
1795
+ fields
1796
+ })
1797
+ });
1798
+ }
1799
+ /** A union: the variant selector, the variant's description, and the variant's fields. */
1800
+ function UnionNode({ meta, shape, bare }) {
1801
+ const form = useForm();
1802
+ const value = getAtPath(form.value, meta.path);
1803
+ const active = shape.kind === "tagged" ? activeTagged(shape, value) : activeExternal(shape, value);
1804
+ const options = shape.variants.map((variant) => ({
1805
+ value: variant.tag,
1806
+ label: meta.ui.enumLabels?.[variant.tag] ?? variant.label
1807
+ }));
1808
+ const explained = meta.ui.descriptionAs === "none" ? "" : firstParagraph(active?.description);
1809
+ let body = null;
1810
+ if (shape.kind === "tagged") {
1811
+ const variant = activeTagged(shape, value);
1812
+ if (variant !== void 0) body = /* @__PURE__ */ jsx(ObjectBody, {
1813
+ path: meta.path,
1814
+ fields: variant.fields
1815
+ });
1816
+ } else {
1817
+ const variant = activeExternal(shape, value);
1818
+ if (variant?.payload !== void 0) {
1819
+ const inner = joinPath(meta.path, variant.tag);
1820
+ const payload = shapeOf(variant.payload, form.schema);
1821
+ body = payload.kind === "object" ? /* @__PURE__ */ jsx(ObjectBody, {
1822
+ path: inner,
1823
+ fields: payload.fields
1824
+ }) : /* @__PURE__ */ jsx(Grid, { children: /* @__PURE__ */ jsx(FieldNode, {
1825
+ path: inner,
1826
+ name: variant.tag,
1827
+ node: variant.payload,
1828
+ required: true
1829
+ }) });
1830
+ }
1831
+ }
1832
+ return /* @__PURE__ */ jsxs(Frame, {
1833
+ meta,
1834
+ bare,
1835
+ children: [
1836
+ /* @__PURE__ */ jsx(Chooser, {
1837
+ label: meta.label,
1838
+ options,
1839
+ value: active?.tag ?? "",
1840
+ widget: meta.ui.widget,
1841
+ disabled: form.disabled,
1842
+ onChoose: (tag) => {
1843
+ const next = seedVariant(shape, tag, form.schema);
1844
+ if (next !== void 0) form.setValue(meta.path, next);
1845
+ }
1846
+ }),
1847
+ explained !== "" && /* @__PURE__ */ jsx("p", {
1848
+ className: "text-xs leading-snug text-fg-muted",
1849
+ children: explained
1850
+ }),
1851
+ body
1852
+ ]
1853
+ });
1854
+ }
1855
+ /**
1856
+ * A fixed-length array as a compact row: one cell per position (a row of numbers), or one
1857
+ * row per position when the positions are objects (a list of points).
1858
+ */
1859
+ function TupleNode({ meta, shape, bare }) {
1860
+ const form = useForm();
1861
+ const cells = shape.items.map((item, index) => {
1862
+ const name = String(index);
1863
+ return {
1864
+ name,
1865
+ item,
1866
+ resolved: shapeOf(item, form.schema),
1867
+ path: joinPath(meta.path, name)
1868
+ };
1869
+ });
1870
+ const rows = cells.some((cell) => cell.resolved.kind === "object");
1871
+ return /* @__PURE__ */ jsx(Frame, {
1872
+ meta,
1873
+ bare,
1874
+ children: /* @__PURE__ */ jsx(DenseContext, {
1875
+ value: true,
1876
+ children: rows ? /* @__PURE__ */ jsx("div", {
1877
+ className: "flex flex-col gap-2",
1878
+ children: cells.map((cell) => /* @__PURE__ */ jsxs("div", {
1879
+ role: "group",
1880
+ "aria-label": `${meta.label} ${cell.name}`,
1881
+ className: "flex items-start gap-2",
1882
+ children: [/* @__PURE__ */ jsx("span", {
1883
+ className: "w-4 shrink-0 pt-1.5 font-mono text-xs text-fg-subtle",
1884
+ "aria-hidden": true,
1885
+ children: cell.name
1886
+ }), /* @__PURE__ */ jsx("div", {
1887
+ className: "min-w-0 flex-1",
1888
+ children: cell.resolved.kind === "object" ? /* @__PURE__ */ jsx(ObjectBody, {
1889
+ path: cell.path,
1890
+ fields: cell.resolved.fields
1891
+ }) : /* @__PURE__ */ jsx(Grid, { children: /* @__PURE__ */ jsx(FieldNode, {
1892
+ path: cell.path,
1893
+ name: cell.name,
1894
+ node: cell.item,
1895
+ required: true
1896
+ }) })
1897
+ })]
1898
+ }, cell.name))
1899
+ }) : /* @__PURE__ */ jsx(Grid, { children: cells.map((cell) => /* @__PURE__ */ jsx(FieldNode, {
1900
+ path: cell.path,
1901
+ name: cell.name,
1902
+ node: cell.item,
1903
+ required: true
1904
+ }, cell.name)) })
1905
+ })
1906
+ });
1907
+ }
1908
+ /**
1909
+ * A composite that may be `null`: a switch for "set / unset", and the content only while set.
1910
+ * Switching it on seeds the content from the schema's defaults.
1911
+ */
1912
+ function NullableNode({ meta, shape }) {
1913
+ const form = useForm();
1914
+ const chrome = useChrome(meta);
1915
+ const value = getAtPath(form.value, meta.path);
1916
+ const set = value !== null && value !== void 0;
1917
+ const props = {
1918
+ checked: set,
1919
+ label: meta.label,
1920
+ description: chrome.description,
1921
+ disabled: form.disabled,
1922
+ onCheckedChange: (next) => form.setValue(meta.path, next ? seedNotNull(meta.node, form.schema) : null)
1923
+ };
1924
+ return /* @__PURE__ */ jsxs("div", {
1925
+ className: cn("flex min-w-0 flex-col gap-3", spanClass(form.columns, meta.ui, 2)),
1926
+ children: [/* @__PURE__ */ jsxs("div", {
1927
+ className: "flex items-start gap-1.5",
1928
+ children: [meta.ui.widget === "checkbox" ? /* @__PURE__ */ jsx(Checkbox, { ...props }) : /* @__PURE__ */ jsx(Switch, { ...props }), chrome.hint !== null && /* @__PURE__ */ jsx("span", {
1929
+ className: "mt-0.5",
1930
+ children: chrome.hint
1931
+ })]
1932
+ }), set && /* @__PURE__ */ jsx("div", {
1933
+ className: "min-w-0 border-l border-line pl-3",
1934
+ children: /* @__PURE__ */ jsx(ShapeNode, {
1935
+ meta,
1936
+ shape,
1937
+ bare: true
1938
+ })
1939
+ })]
1940
+ });
1941
+ }
1942
+ //#endregion
1943
+ //#region src/components/SchemaValueForm.tsx
1944
+ /**
1945
+ * A form that edits a whole JSON value, generated from the value's JSON Schema.
1946
+ *
1947
+ * `SchemaForm` is for *options*: every field starts unset and only what the operator
1948
+ * touches is sent. This is for *configs*: the value is complete — a calibration's settings,
1949
+ * a detector's parameters — and the form edits it in place, down to a nested struct, a
1950
+ * serde enum's data, a nullable block or a tuple of points, handing back the whole next
1951
+ * value on each edit. What the schema cannot say (grouping, labels, units, a different
1952
+ * control) the app says in a `UiSchema`.
1953
+ */
1954
+ const NO_UI = {};
1955
+ /** Controlled when `value` is given, otherwise the form keeps the value itself. */
1956
+ function useValue(value, seed, onValueChange) {
1957
+ const [inner, setInner] = useState(seed);
1958
+ const controlled = value !== void 0;
1959
+ return [controlled ? value : inner, (next) => {
1960
+ if (!controlled) setInner(next);
1961
+ onValueChange?.(next);
1962
+ }];
1963
+ }
1964
+ /**
1965
+ * Edit a JSON value through its schema.
1966
+ *
1967
+ * Renders by the schema's shape: a number is a `NumberInput` (with its bounds, unit and an
1968
+ * integer-only rule), a string an `Input`, a boolean a `Switch`, a closed set a
1969
+ * `SegmentedControl` or a `Select`, a struct a nested fieldset, a serde enum a variant
1970
+ * selector with the variant's fields (switching seeds them from the schema's defaults), a
1971
+ * `null`-able block a switch that sets and unsets it, a list of strings an editable list, a
1972
+ * fixed-length array a row of cells, and anything else a JSON textarea that keeps the last
1973
+ * valid value while showing the parse error.
1974
+ *
1975
+ * The first paragraph of a field's description is its `InfoHint`. Round-trips: a value in,
1976
+ * no edits, the same value out — the form never normalises on mount, and an edit changes
1977
+ * only the leaf touched.
1978
+ *
1979
+ * The root is a `div` carrying `data-columns` and, while disabled, `data-disabled`. Wraps itself in a
1980
+ * `TooltipProvider`, so it needs none above it.
1981
+ */
1982
+ function SchemaValueForm({ schema, value, defaultValue, onValueChange, ui = NO_UI, columns = 2, disabled = false, renderField, className, ref }) {
1983
+ const [current, commit] = useValue(value, () => defaultValue !== void 0 ? defaultValue : defaultValueForSchema(schema), onValueChange);
1984
+ const state = {
1985
+ schema,
1986
+ value: current,
1987
+ setValue: (path, next) => {
1988
+ const updated = setAtPath(current, path, next);
1989
+ if (!Object.is(updated, current)) commit(updated);
1990
+ },
1991
+ ui,
1992
+ disabled,
1993
+ columns,
1994
+ renderField,
1995
+ claimed: useMemo(() => new Set((ui.groups ?? []).flatMap((group) => group.fields)), [ui.groups])
1996
+ };
1997
+ const root = shapeOf(schema, schema);
1998
+ return /* @__PURE__ */ jsx(TooltipProvider, { children: /* @__PURE__ */ jsx(FormContext, {
1999
+ value: state,
2000
+ children: /* @__PURE__ */ jsxs("div", {
2001
+ ref,
2002
+ "data-columns": columns,
2003
+ "data-disabled": disabled ? "" : void 0,
2004
+ className: cn("flex min-w-0 flex-col gap-5", className),
2005
+ children: [root.kind === "object" && (ui.groups ?? []).map((group) => /* @__PURE__ */ jsx(GroupBlock, { group }, group.id)), root.kind === "object" ? /* @__PURE__ */ jsx(ObjectBody, {
2006
+ path: "",
2007
+ fields: root.fields
2008
+ }) : /* @__PURE__ */ jsx(FieldNode, {
2009
+ path: "",
2010
+ name: schema.title ?? "value",
2011
+ node: schema,
2012
+ required: true,
2013
+ bare: true
2014
+ })]
2015
+ })
2016
+ }) });
2017
+ }
2018
+ /** A `UiGroup`: its fields under a heading, folded away if the app said so. */
2019
+ function GroupBlock({ group }) {
2020
+ const { schema, value, ui } = useForm();
2021
+ const fields = group.fields.flatMap((path) => {
2022
+ const info = fieldAt(schema, path, schema, value);
2023
+ if (info === void 0 || fieldUiAt(ui, path).hidden === true) return [];
2024
+ return [{
2025
+ path,
2026
+ info
2027
+ }];
2028
+ });
2029
+ if (fields.length === 0) return null;
2030
+ const body = /* @__PURE__ */ jsx(Grid, { children: fields.map(({ path, info }) => /* @__PURE__ */ jsx(FieldNode, {
2031
+ path,
2032
+ name: path.split(".").at(-1) ?? path,
2033
+ node: info.schema,
2034
+ required: info.required
2035
+ }, path)) });
2036
+ if (group.collapsible === true) return /* @__PURE__ */ jsxs(Disclosure, {
2037
+ summary: group.title,
2038
+ count: fields.length,
2039
+ defaultOpen: group.defaultOpen ?? false,
2040
+ children: [group.hint !== void 0 && /* @__PURE__ */ jsx("p", {
2041
+ className: "mb-3 text-xs text-fg-muted",
2042
+ children: group.hint
2043
+ }), body]
2044
+ });
2045
+ return /* @__PURE__ */ jsx(Section, {
2046
+ title: group.title,
2047
+ hint: group.hint,
2048
+ children: body
2049
+ });
2050
+ }
2051
+ //#endregion
2052
+ export { SchemaForm, SchemaValueForm, defaultValueForSchema, describeFields, fieldAt, fieldsAt, firstParagraph, getAtPath, initialValues, jsonErrors, missingRequired, outOfRange, overrideCount, resolveRef, resolveSchema, setAtPath, shapeOf, toOptions };
434
2053
 
435
2054
  //# sourceMappingURL=index.js.map