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