@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.
@@ -0,0 +1,505 @@
1
+ /**
2
+ * Reading a schema as the shape of a *value*: what a node is, which fields it has, and
3
+ * what a fresh one looks like.
4
+ *
5
+ * `SchemaForm` asks "which control does this option deserve?". `SchemaValueForm` asks the
6
+ * deeper question — "what can this value be, all the way down?" — and the answer has to
7
+ * cover what Rust's serde does to enums:
8
+ *
9
+ * - a **plain enum** is `oneOf` of `{ const }`, or `enum`;
10
+ * - an **externally tagged** enum is `"None"` for a unit variant and `{ "Huber": { … } }`
11
+ * (or `{ "Fixed": 2 }`, a newtype) for a variant that carries data;
12
+ * - an **internally tagged** enum is an object whose `kind` (or any property that is a
13
+ * `const` in every variant) names the variant.
14
+ *
15
+ * Everything here is pure: the component only renders what these functions decide.
16
+ */
17
+
18
+ import { getAtPath, splitPath } from "./valuePath";
19
+ import { resolveSchema, type JsonSchema } from "./schemaNode";
20
+
21
+ /** A primitive an enum can hold. */
22
+ export type EnumValue = string | number | boolean;
23
+
24
+ /** One value of a closed set. */
25
+ export interface EnumOption {
26
+ /** The value as stored. */
27
+ value: EnumValue;
28
+ /** The label as shown: the variant's `title`, else the value. */
29
+ label: string;
30
+ /** The variant's own description (a `oneOf` entry's), if it has one. */
31
+ description?: string | undefined;
32
+ }
33
+
34
+ /** One field of an object: its key, its schema as written, and whether it must be present. */
35
+ export interface FieldInfo {
36
+ /** The property key. */
37
+ key: string;
38
+ /** The property's schema as written (a `$ref` is not followed). */
39
+ schema: JsonSchema;
40
+ /** Whether the object's `required` lists the key. */
41
+ required: boolean;
42
+ }
43
+
44
+ /** A variant of an internally tagged enum. */
45
+ export interface TaggedVariant {
46
+ /** The discriminator's value for this variant. */
47
+ tag: string;
48
+ /** The variant's `title`, else the tag. */
49
+ label: string;
50
+ /** The variant's description. */
51
+ description?: string | undefined;
52
+ /** The variant's object schema, resolved. */
53
+ schema: JsonSchema;
54
+ /** The variant's fields, without the discriminator. */
55
+ fields: FieldInfo[];
56
+ }
57
+
58
+ /** A variant of an externally tagged enum. */
59
+ export interface ExternalVariant {
60
+ /** The variant name: the string for a unit variant, the sole key for one with data. */
61
+ tag: string;
62
+ /** The variant's `title`, else the tag. */
63
+ label: string;
64
+ /** The variant's description. */
65
+ description?: string | undefined;
66
+ /** What the variant carries (a struct's fields, or a newtype's one value); none for a unit variant. */
67
+ payload: JsonSchema | undefined;
68
+ }
69
+
70
+ /** What a schema node is, as far as a form is concerned. */
71
+ export type SchemaShape =
72
+ /** A struct: its fields in schema order. */
73
+ | { kind: "object"; fields: FieldInfo[] }
74
+ | { kind: "string" }
75
+ | { kind: "integer" }
76
+ | { kind: "number" }
77
+ | { kind: "boolean" }
78
+ /** A closed set of primitives: `enum`, `const`, or `oneOf` of `{ const }`. */
79
+ | { kind: "enum"; options: EnumOption[] }
80
+ /** An enum whose variants are objects named by a shared `const` property. */
81
+ | { kind: "tagged"; discriminator: string; variants: TaggedVariant[] }
82
+ /** A serde externally tagged enum. */
83
+ | { kind: "external"; variants: ExternalVariant[] }
84
+ /** An array of plain strings. */
85
+ | { kind: "string-list"; item: JsonSchema }
86
+ /** A fixed-length array: `prefixItems`, or `minItems === maxItems` of numbers or objects. */
87
+ | { kind: "tuple"; items: JsonSchema[] }
88
+ /** Anything else: edited as JSON. */
89
+ | { kind: "json" };
90
+
91
+ type TaggedShape = Extract<SchemaShape, { kind: "tagged" }>;
92
+ type ExternalShape = Extract<SchemaShape, { kind: "external" }>;
93
+
94
+ /** The longest fixed-length array shown as a row of cells rather than as JSON. */
95
+ const MAX_TUPLE = 32;
96
+ /** Discriminator names tried first; any other shared `const` property works too. */
97
+ const PREFERRED_DISCRIMINATORS = ["kind", "type", "tag", "variant"];
98
+ /** Recursion limit for seeding a value from a self-referential schema. */
99
+ const MAX_DEPTH = 8;
100
+
101
+ function isPrimitive(value: unknown): value is EnumValue {
102
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
103
+ }
104
+
105
+ function isRecord(value: unknown): value is Record<string, unknown> {
106
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107
+ }
108
+
109
+ function fieldsOf(schema: JsonSchema, omit?: string): FieldInfo[] {
110
+ const required = new Set(schema.required ?? []);
111
+ return Object.entries(schema.properties ?? {})
112
+ .filter(([key]) => key !== omit)
113
+ .map(([key, property]) => ({ key, schema: property, required: required.has(key) }));
114
+ }
115
+
116
+ /** The primitives a `const` / `enum` variant fixes, or `undefined` if it is not one. */
117
+ function constValues(variant: JsonSchema): EnumValue[] | undefined {
118
+ if (variant.properties !== undefined) return undefined;
119
+ if (Object.hasOwn(variant, "const")) return isPrimitive(variant.const) ? [variant.const] : undefined;
120
+ if (Array.isArray(variant.enum) && variant.enum.length > 0 && variant.enum.every(isPrimitive)) {
121
+ return variant.enum;
122
+ }
123
+ return undefined;
124
+ }
125
+
126
+ function constString(property: JsonSchema | undefined, root: JsonSchema): string | undefined {
127
+ if (property === undefined) return undefined;
128
+ const [value] = constValues(resolveSchema(property, root).schema) ?? [];
129
+ return typeof value === "string" ? value : undefined;
130
+ }
131
+
132
+ function classifyTagged(variants: JsonSchema[], root: JsonSchema): TaggedShape | undefined {
133
+ if (!variants.every((variant) => variant.properties !== undefined)) return undefined;
134
+ const [first] = variants;
135
+ const keys = Object.keys(first?.properties ?? {});
136
+ const candidates = [
137
+ ...PREFERRED_DISCRIMINATORS.filter((key) => keys.includes(key)),
138
+ ...keys.filter((key) => !PREFERRED_DISCRIMINATORS.includes(key)),
139
+ ];
140
+
141
+ for (const discriminator of candidates) {
142
+ const tags = variants.map((variant) => constString(variant.properties?.[discriminator], root));
143
+ if (!tags.every((tag): tag is string => tag !== undefined)) continue;
144
+ if (new Set(tags).size !== tags.length) continue;
145
+ return {
146
+ kind: "tagged",
147
+ discriminator,
148
+ variants: variants.map((variant, index) => ({
149
+ tag: tags[index] ?? "",
150
+ label: variant.title ?? tags[index] ?? "",
151
+ description: variant.description,
152
+ schema: variant,
153
+ fields: fieldsOf(variant, discriminator),
154
+ })),
155
+ };
156
+ }
157
+ return undefined;
158
+ }
159
+
160
+ function classifyExternal(variants: JsonSchema[]): ExternalShape | undefined {
161
+ const out: ExternalVariant[] = [];
162
+ for (const variant of variants) {
163
+ const units = constValues(variant);
164
+ if (units !== undefined) {
165
+ if (!units.every((unit) => typeof unit === "string")) return undefined;
166
+ for (const unit of units) {
167
+ out.push({ tag: String(unit), label: variant.title ?? String(unit), description: variant.description, payload: undefined });
168
+ }
169
+ continue;
170
+ }
171
+ const keys = Object.keys(variant.properties ?? {});
172
+ const [tag] = keys;
173
+ const payload = tag === undefined ? undefined : variant.properties?.[tag];
174
+ if (keys.length !== 1 || tag === undefined || payload === undefined || variant.additionalProperties === true) {
175
+ return undefined;
176
+ }
177
+ out.push({ tag, label: variant.title ?? tag, description: variant.description, payload });
178
+ }
179
+ return new Set(out.map((variant) => variant.tag)).size === out.length ? { kind: "external", variants: out } : undefined;
180
+ }
181
+
182
+ function classifyUnion(branches: JsonSchema[], root: JsonSchema): SchemaShape {
183
+ const variants = branches.map((branch) => resolveSchema(branch, root).schema);
184
+
185
+ const options: EnumOption[] = [];
186
+ for (const variant of variants) {
187
+ for (const value of constValues(variant) ?? []) {
188
+ options.push({ value, label: variant.title ?? String(value), description: variant.description });
189
+ }
190
+ }
191
+ if (variants.every((variant) => constValues(variant) !== undefined)) return { kind: "enum", options };
192
+
193
+ return classifyTagged(variants, root) ?? classifyExternal(variants) ?? { kind: "json" };
194
+ }
195
+
196
+ function classifyArray(schema: JsonSchema, root: JsonSchema): SchemaShape {
197
+ if (schema.prefixItems !== undefined && schema.prefixItems.length > 0) {
198
+ return { kind: "tuple", items: schema.prefixItems };
199
+ }
200
+ const items = typeof schema.items === "object" ? schema.items : undefined;
201
+ if (items === undefined) return { kind: "json" };
202
+
203
+ const item = resolveSchema(items, root).schema;
204
+ const itemShape = classify(item, root);
205
+ if (itemShape.kind === "string") return { kind: "string-list", item: items };
206
+
207
+ const count = schema.minItems;
208
+ const fixed = count !== undefined && count === schema.maxItems && count >= 1 && count <= MAX_TUPLE;
209
+ if (fixed && (itemShape.kind === "number" || itemShape.kind === "integer" || itemShape.kind === "object")) {
210
+ return { kind: "tuple", items: Array.from({ length: count }, () => items) };
211
+ }
212
+ return { kind: "json" };
213
+ }
214
+
215
+ function classify(schema: JsonSchema, root: JsonSchema): SchemaShape {
216
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
217
+ return schema.enum.every(isPrimitive)
218
+ ? { kind: "enum", options: schema.enum.map((value) => ({ value, label: String(value) })) }
219
+ : { kind: "json" };
220
+ }
221
+ if (Object.hasOwn(schema, "const")) {
222
+ return isPrimitive(schema.const)
223
+ ? { kind: "enum", options: [{ value: schema.const, label: String(schema.const) }] }
224
+ : { kind: "json" };
225
+ }
226
+
227
+ const branches = schema.oneOf ?? schema.anyOf;
228
+ if (branches !== undefined && branches.length > 0) return classifyUnion(branches, root);
229
+
230
+ if (schema.properties !== undefined) {
231
+ const fields = fieldsOf(schema);
232
+ // `{}` closed is a unit struct; `{}` open is a map the form cannot enumerate.
233
+ return fields.length > 0 || schema.additionalProperties === false ? { kind: "object", fields } : { kind: "json" };
234
+ }
235
+
236
+ switch (schema.type) {
237
+ case "string":
238
+ return { kind: "string" };
239
+ case "integer":
240
+ return { kind: "integer" };
241
+ case "number":
242
+ return { kind: "number" };
243
+ case "boolean":
244
+ return { kind: "boolean" };
245
+ case "array":
246
+ return classifyArray(schema, root);
247
+ default:
248
+ return { kind: "json" };
249
+ }
250
+ }
251
+
252
+ /**
253
+ * What a schema node is.
254
+ *
255
+ * Looks through `$ref` and the "or null" encodings first (see `resolveSchema`), then
256
+ * decides among the shapes of `SchemaShape`. A node it does not recognise is `json`, never
257
+ * an error: a caller can always express what the model accepts.
258
+ *
259
+ * @param node - A schema node as written.
260
+ * @param root - The document holding `$defs` (defaults to `node`).
261
+ * @returns The shape.
262
+ */
263
+ export function shapeOf(node: JsonSchema, root: JsonSchema = node): SchemaShape {
264
+ return classify(resolveSchema(node, root).schema, root);
265
+ }
266
+
267
+ /**
268
+ * The variant an internally tagged value is on.
269
+ *
270
+ * @param shape - A `tagged` shape.
271
+ * @param value - The current value.
272
+ * @returns The variant whose tag is in the value's discriminator, or `undefined` for a
273
+ * value that names none (absent, not an object, an unknown tag).
274
+ */
275
+ export function activeTagged(shape: TaggedShape, value: unknown): TaggedVariant | undefined {
276
+ const tag = isRecord(value) ? value[shape.discriminator] : undefined;
277
+ return typeof tag === "string" ? shape.variants.find((variant) => variant.tag === tag) : undefined;
278
+ }
279
+
280
+ /**
281
+ * The variant an externally tagged value is on.
282
+ *
283
+ * @param shape - An `external` shape.
284
+ * @param value - The current value: the string of a unit variant, or an object with the
285
+ * variant's name as its key.
286
+ * @returns The variant, or `undefined` for a value that names none.
287
+ */
288
+ export function activeExternal(shape: ExternalShape, value: unknown): ExternalVariant | undefined {
289
+ if (typeof value === "string") {
290
+ return shape.variants.find((variant) => variant.payload === undefined && variant.tag === value);
291
+ }
292
+ if (!isRecord(value)) return undefined;
293
+ return shape.variants.find((variant) => variant.payload !== undefined && Object.hasOwn(value, variant.tag));
294
+ }
295
+
296
+ function seedOf(schema: JsonSchema, root: JsonSchema, depth: number, notNull: boolean): unknown {
297
+ const { schema: s, nullable } = resolveSchema(schema, root);
298
+ if (s.default !== undefined && !(notNull && s.default === null)) return s.default;
299
+ if (nullable && !notNull) return null;
300
+ if (depth > MAX_DEPTH) return null;
301
+
302
+ const shape = classify(s, root);
303
+ switch (shape.kind) {
304
+ case "enum":
305
+ return shape.options[0]?.value ?? null;
306
+ case "string":
307
+ return "";
308
+ case "boolean":
309
+ return false;
310
+ case "integer":
311
+ case "number":
312
+ return seedNumber(s, shape.kind === "integer");
313
+ case "object": {
314
+ const out: Record<string, unknown> = {};
315
+ for (const field of shape.fields) {
316
+ const hasDefault = resolveSchema(field.schema, root).schema.default !== undefined;
317
+ if (field.required || hasDefault) out[field.key] = seedOf(field.schema, root, depth + 1, false);
318
+ }
319
+ return out;
320
+ }
321
+ case "tagged": {
322
+ const [variant] = shape.variants;
323
+ return variant === undefined ? null : seedTagged(shape, variant, root, depth);
324
+ }
325
+ case "external": {
326
+ const [variant] = shape.variants;
327
+ return variant === undefined ? null : seedExternal(variant, root, depth);
328
+ }
329
+ case "tuple":
330
+ return shape.items.map((item) => seedOf(item, root, depth + 1, false));
331
+ case "string-list":
332
+ return [];
333
+ case "json": {
334
+ const [first] = s.oneOf ?? s.anyOf ?? [];
335
+ if (first !== undefined) return seedOf(first, root, depth + 1, false);
336
+ if (s.type === "array") return [];
337
+ return s.type === "object" ? {} : null;
338
+ }
339
+ }
340
+ }
341
+
342
+ function seedNumber(schema: JsonSchema, integer: boolean): number {
343
+ const lower = schema.minimum ?? (schema.format?.startsWith("uint") === true ? 0 : undefined);
344
+ const exclusiveLower = schema.exclusiveMinimum;
345
+ const upper = schema.maximum ?? schema.exclusiveMaximum;
346
+
347
+ let value = 0;
348
+ if (lower !== undefined && value < lower) value = lower;
349
+ if (exclusiveLower !== undefined && value <= exclusiveLower) {
350
+ value = integer ? exclusiveLower + 1 : upper !== undefined ? (exclusiveLower + upper) / 2 : exclusiveLower + 1;
351
+ }
352
+ if (upper !== undefined && value > upper) value = lower ?? upper;
353
+ return integer ? Math.ceil(value) : value;
354
+ }
355
+
356
+ function seedTagged(shape: TaggedShape, variant: TaggedVariant, root: JsonSchema, depth: number): unknown {
357
+ const body = seedOf(variant.schema, root, depth + 1, false);
358
+ return { ...(isRecord(body) ? body : {}), [shape.discriminator]: variant.tag };
359
+ }
360
+
361
+ function seedExternal(variant: ExternalVariant, root: JsonSchema, depth: number): unknown {
362
+ return variant.payload === undefined ? variant.tag : { [variant.tag]: seedOf(variant.payload, root, depth + 1, false) };
363
+ }
364
+
365
+ /**
366
+ * A fresh value for a schema.
367
+ *
368
+ * Takes the `default` when there is one (a `default` written beside a `$ref` wins over the
369
+ * target's), `null` for a nullable node, and otherwise builds the value from the shape:
370
+ * an object gets its required fields and the fields that have a default, an enum its first
371
+ * value, a union its first variant, a number the nearest legal value to 0, a string `""`.
372
+ * The result is JSON, and for a schema this package can read, valid against it.
373
+ *
374
+ * @param schema - A schema node.
375
+ * @param root - The document holding `$defs` (defaults to `schema`).
376
+ * @returns The seed value.
377
+ */
378
+ export function defaultValueForSchema(schema: JsonSchema, root: JsonSchema = schema): unknown {
379
+ return seedOf(schema, root, 0, false);
380
+ }
381
+
382
+ /**
383
+ * The seed for a node that is switched on from `null`: its default, unless that default is
384
+ * itself `null`, in which case the value the shape implies.
385
+ *
386
+ * @param schema - A schema node.
387
+ * @param root - The document holding `$defs`.
388
+ * @returns A value that is not `null` (for a node that can hold anything else).
389
+ */
390
+ export function seedNotNull(schema: JsonSchema, root: JsonSchema): unknown {
391
+ return seedOf(schema, root, 0, true);
392
+ }
393
+
394
+ /**
395
+ * The value for a union after the user picks a variant: the variant's own seed, with its
396
+ * tag in place.
397
+ *
398
+ * @param shape - A `tagged` or `external` shape.
399
+ * @param tag - The chosen variant's tag.
400
+ * @param root - The document holding `$defs`.
401
+ * @returns The new value, or `undefined` if the shape has no such variant.
402
+ */
403
+ export function seedVariant(shape: TaggedShape | ExternalShape, tag: string, root: JsonSchema): unknown {
404
+ if (shape.kind === "tagged") {
405
+ const variant = shape.variants.find((candidate) => candidate.tag === tag);
406
+ return variant === undefined ? undefined : seedTagged(shape, variant, root, 0);
407
+ }
408
+ const variant = shape.variants.find((candidate) => candidate.tag === tag);
409
+ return variant === undefined ? undefined : seedExternal(variant, root, 0);
410
+ }
411
+
412
+ /** The fields of the shape for the value as it stands (the active variant, for a union). */
413
+ function childrenOf(shape: SchemaShape, value: unknown): FieldInfo[] {
414
+ switch (shape.kind) {
415
+ case "object":
416
+ return shape.fields;
417
+ case "tagged":
418
+ return (activeTagged(shape, value) ?? shape.variants[0])?.fields ?? [];
419
+ case "external": {
420
+ const variant = activeExternal(shape, value);
421
+ return variant?.payload === undefined ? [] : [{ key: variant.tag, schema: variant.payload, required: true }];
422
+ }
423
+ case "tuple":
424
+ return shape.items.map((schema, index) => ({ key: String(index), schema, required: true }));
425
+ case "string-list":
426
+ return Array.isArray(value) ? value.map((_, index) => ({ key: String(index), schema: shape.item, required: true })) : [];
427
+ default:
428
+ return [];
429
+ }
430
+ }
431
+
432
+ /** The child called `segment`, wherever it is — the active variant first, then any. */
433
+ function findChild(shape: SchemaShape, segment: string, value: unknown): FieldInfo | undefined {
434
+ switch (shape.kind) {
435
+ case "tagged": {
436
+ const active = activeTagged(shape, value);
437
+ const variants = active === undefined ? shape.variants : [active, ...shape.variants];
438
+ for (const variant of variants) {
439
+ const field = variant.fields.find((candidate) => candidate.key === segment);
440
+ if (field !== undefined) return field;
441
+ }
442
+ return undefined;
443
+ }
444
+ case "external": {
445
+ const variant = shape.variants.find((candidate) => candidate.payload !== undefined && candidate.tag === segment);
446
+ return variant?.payload === undefined ? undefined : { key: segment, schema: variant.payload, required: true };
447
+ }
448
+ case "tuple": {
449
+ const schema = shape.items[Number(segment)];
450
+ return schema === undefined ? undefined : { key: segment, schema, required: true };
451
+ }
452
+ case "string-list":
453
+ return /^\d+$/.test(segment) ? { key: segment, schema: shape.item, required: true } : undefined;
454
+ default:
455
+ return childrenOf(shape, value).find((candidate) => candidate.key === segment);
456
+ }
457
+ }
458
+
459
+ /**
460
+ * The field at a dot path.
461
+ *
462
+ * Walks the schema, not the value: a path through a union resolves in the variant the
463
+ * `value` is on if it has the field, else in whichever variant does, so a `UiSchema` path
464
+ * can name a field that is not showing right now.
465
+ *
466
+ * @param schema - The root schema.
467
+ * @param path - Dot path from the root (`solver.robust_loss.Huber.scale`); `""` is the root.
468
+ * @param root - The document holding `$defs` (defaults to `schema`).
469
+ * @param value - The current value, to choose between a union's variants.
470
+ * @returns The field (its schema as written, and whether it is required), or `undefined`
471
+ * where the path leaves the schema.
472
+ */
473
+ export function fieldAt(
474
+ schema: JsonSchema,
475
+ path: string,
476
+ root: JsonSchema = schema,
477
+ value?: unknown,
478
+ ): FieldInfo | undefined {
479
+ let info: FieldInfo = { key: "", schema, required: true };
480
+ let current = value;
481
+ for (const segment of splitPath(path)) {
482
+ const next = findChild(shapeOf(info.schema, root), segment, current);
483
+ if (next === undefined) return undefined;
484
+ info = next;
485
+ current = getAtPath(current, segment);
486
+ }
487
+ return info;
488
+ }
489
+
490
+ /**
491
+ * The fields that are editable at a path, as the form would list them: an object's fields
492
+ * in schema order, the active variant's fields (without the discriminator) for an internally
493
+ * tagged union, the variant's payload for an externally tagged one, a tuple's positions.
494
+ *
495
+ * @param schema - The root schema.
496
+ * @param path - Dot path from the root; `""` for the root.
497
+ * @param root - The document holding `$defs` (defaults to `schema`).
498
+ * @param value - The current root value, to choose between a union's variants (the first
499
+ * variant when absent).
500
+ * @returns The fields; empty for a leaf or a path outside the schema.
501
+ */
502
+ export function fieldsAt(schema: JsonSchema, path: string, root: JsonSchema = schema, value?: unknown): FieldInfo[] {
503
+ const info = fieldAt(schema, path, root, value);
504
+ return info === undefined ? [] : childrenOf(shapeOf(info.schema, root), getAtPath(value, path));
505
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * What an app says about a form that the schema cannot: which fields go together, what to
3
+ * call them, and when a different control is wanted.
4
+ *
5
+ * A schema describes the *data*. It rarely knows that `roi_xywh` is four pixels, that three
6
+ * fields belong under "Detection", or that `refinement` reads better as a strip of
7
+ * segments than a drop-down. That is layout, and it belongs to the app, not to the Rust
8
+ * struct, so it travels beside the schema as a `UiSchema` instead of inside it.
9
+ */
10
+
11
+ import type { ReactNode } from "react";
12
+
13
+ import type { JsonSchema } from "./schemaNode";
14
+
15
+ /** A titled set of fields, rendered together. */
16
+ export interface UiGroup {
17
+ /** Stable id, used for keys and test hooks. */
18
+ id: string;
19
+ /** The heading. */
20
+ title: string;
21
+ /**
22
+ * The fields in the group, as dot paths from the form's root: `threshold`, `solver`,
23
+ * `solver.max_iters`. A path to an object brings its whole subtree; a path to a leaf
24
+ * brings only that leaf, and the object's other fields stay in the ungrouped remainder.
25
+ */
26
+ fields: string[];
27
+ /** Fold the group away behind a `Disclosure`. Otherwise it is a `Section`. */
28
+ collapsible?: boolean | undefined;
29
+ /** Whether a collapsible group starts open. Defaults to closed. */
30
+ defaultOpen?: boolean | undefined;
31
+ /** A line of explanation under the heading. */
32
+ hint?: ReactNode;
33
+ }
34
+
35
+ /** The widgets a field can be forced into with `FieldUi.widget`. */
36
+ export type FieldWidget =
37
+ | "number"
38
+ | "text"
39
+ | "select"
40
+ | "segmented"
41
+ | "checkbox"
42
+ | "switch"
43
+ | "json"
44
+ | "tuple-row"
45
+ | "string-list";
46
+
47
+ /** Per-field presentation, looked up by the field's dot path. */
48
+ export interface FieldUi {
49
+ /** The label, instead of the schema's `title` or the humanised key. */
50
+ label?: string | undefined;
51
+ /** Explanation shown in place of the schema's description. */
52
+ hint?: ReactNode;
53
+ /** Do not render the field. Its value is kept as it is. */
54
+ hidden?: boolean | undefined;
55
+ /**
56
+ * The control, instead of the one the schema's shape calls for. A widget that does not
57
+ * fit the field (`segmented` on a number) is ignored.
58
+ */
59
+ widget?: FieldWidget | undefined;
60
+ /** The unit written in the field, instead of the schema's `x-unit`. */
61
+ unit?: string | undefined;
62
+ /** Lower bound the control enforces, instead of the schema's `minimum`. */
63
+ min?: number | undefined;
64
+ /** Upper bound the control enforces, instead of the schema's `maximum`. */
65
+ max?: number | undefined;
66
+ /** Arrow-key step, instead of the schema's `multipleOf` (or 1 for an integer). */
67
+ step?: number | undefined;
68
+ /**
69
+ * Labels for an enum's values and a union's variants, by value or tag:
70
+ * `{ brown_conrady5: "Brown-Conrady" }`.
71
+ */
72
+ enumLabels?: Record<string, string> | undefined;
73
+ /** Columns the field takes in the grid. Containers and lists default to the full row. */
74
+ span?: 1 | 2 | undefined;
75
+ /**
76
+ * Where the description goes: `hint` (the default) is an `InfoHint` beside the label,
77
+ * `inline` is a line under the control, `none` drops it.
78
+ */
79
+ descriptionAs?: "hint" | "inline" | "none" | undefined;
80
+ /**
81
+ * Clearing a number input puts the default back (the default, `true`): the schema's
82
+ * non-null `default`, else the nearest legal value for a required field, else — for an
83
+ * optional field with no usable default — nothing, which removes the key (the schema
84
+ * default then applies). With `false` the field is left empty where it can be (an
85
+ * optional field loses its key) and keeps its value where it cannot (a required,
86
+ * non-nullable one). A required nullable field is set to `null`. An optional field is
87
+ * never set to `null` unless `clearTo` says so.
88
+ */
89
+ restoreDefaultOnClear?: boolean | undefined;
90
+ /**
91
+ * For a nullable field, what clearing writes. `"null"` writes `null` even when the key is
92
+ * optional — the way to let a user choose `None` for an `Option<T>` whose default is
93
+ * `Some(…)`, since for a serde `#[serde(default)]` field an absent key means the default
94
+ * and `null` means `None`. Left out, clearing an optional field removes the key and
95
+ * clearing a required nullable one writes `null` (see `restoreDefaultOnClear`). It has no
96
+ * effect on a field that is not nullable.
97
+ */
98
+ clearTo?: "null" | undefined;
99
+ }
100
+
101
+ /**
102
+ * App-supplied layout for a `SchemaValueForm`.
103
+ *
104
+ * Paths are dot paths from the root of the *value*: `solver.max_iters`, `sensor.kind`.
105
+ * An array element is its index (`cameras.0.id`), and `*` stands for any index
106
+ * (`cameras.*.id`). For a serde externally-tagged enum the tag is a path segment
107
+ * (`solver.robust_loss.Huber.scale`).
108
+ */
109
+ export interface UiSchema {
110
+ /**
111
+ * Groups, in order. Fields in a group render under its heading; every visible field not
112
+ * claimed by a group renders after the groups, in schema order.
113
+ */
114
+ groups?: UiGroup[] | undefined;
115
+ /** Per-field presentation, by dot path. */
116
+ fields?: Record<string, FieldUi> | undefined;
117
+ }
118
+
119
+ /** What `renderField` is given for a field. */
120
+ export interface RenderFieldContext {
121
+ /** The field's dot path from the root. */
122
+ path: string;
123
+ /** The field's schema with `$ref` and "or null" looked through. */
124
+ schema: JsonSchema;
125
+ /** The field's current value; `undefined` where the key is absent. */
126
+ value: unknown;
127
+ /** Replace the field's value (`undefined` removes the key). */
128
+ onChange: (next: unknown) => void;
129
+ /** Whether the whole form is disabled. */
130
+ disabled: boolean;
131
+ }
132
+
133
+ /**
134
+ * Take over a field. Return `undefined` to let the form's own control render, anything else
135
+ * to render in its place (and in its grid cell, with the field's span).
136
+ */
137
+ export type RenderField = (context: RenderFieldContext) => ReactNode;
138
+
139
+ const NO_UI: FieldUi = {};
140
+
141
+ /**
142
+ * The presentation for a path: the exact entry, merged over the wildcard entry
143
+ * (`cameras.*.id`) when the path has array indices.
144
+ *
145
+ * @param ui - The app's `UiSchema`, if any.
146
+ * @param path - The field's dot path.
147
+ * @returns The presentation; `{}` where the app said nothing.
148
+ */
149
+ export function fieldUiAt(ui: UiSchema | undefined, path: string): FieldUi {
150
+ const table = ui?.fields;
151
+ if (table === undefined) return NO_UI;
152
+ const wildcard = path.replaceAll(/(^|\.)\d+(?=\.|$)/g, "$1*");
153
+ const general = wildcard === path ? undefined : table[wildcard];
154
+ const exact = table[path];
155
+ if (general === undefined) return exact ?? NO_UI;
156
+ return exact === undefined ? general : { ...general, ...exact };
157
+ }