@vitavision/forms 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Reading and writing a JSON value by dot path, without mutating it.
3
+ *
4
+ * A form edits one leaf of a value it does not own: the caller holds the value, the form
5
+ * reports the next one. So an edit must produce a new root that shares every untouched
6
+ * subtree with the old one (cheap to compare, safe to hold in state) and must leave the old
7
+ * root exactly as it was.
8
+ *
9
+ * A path is dot-separated keys, with array indices as numbers: `solver.max_iters`,
10
+ * `cameras.0.id`. A key that itself contains a dot cannot be addressed; the Rust and
11
+ * Python configs these forms are for do not have them.
12
+ */
13
+
14
+ const INDEX = /^(0|[1-9]\d*)$/;
15
+
16
+ function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+
20
+ /**
21
+ * Split a dot path into its segments.
22
+ *
23
+ * @param path - `a.b.0`, or `""` for the root.
24
+ * @returns `["a", "b", "0"]`, or `[]` for the root.
25
+ */
26
+ export function splitPath(path: string): string[] {
27
+ return path === "" ? [] : path.split(".");
28
+ }
29
+
30
+ /**
31
+ * Join a parent path and a key.
32
+ *
33
+ * @param parent - A dot path; `""` is the root.
34
+ * @param key - A property key or an array index.
35
+ * @returns The child's path.
36
+ */
37
+ export function joinPath(parent: string, key: string): string {
38
+ return parent === "" ? key : `${parent}.${key}`;
39
+ }
40
+
41
+ /**
42
+ * Read the value at a path.
43
+ *
44
+ * @param value - The root value.
45
+ * @param path - Dot path; `""` is the root itself.
46
+ * @returns What is there, or `undefined` where any step of the path is missing.
47
+ */
48
+ export function getAtPath(value: unknown, path: string): unknown {
49
+ let current = value;
50
+ for (const segment of splitPath(path)) {
51
+ if (Array.isArray(current)) {
52
+ current = INDEX.test(segment) ? (current as unknown[])[Number(segment)] : undefined;
53
+ } else if (isRecord(current) && Object.hasOwn(current, segment)) {
54
+ current = current[segment];
55
+ } else {
56
+ return undefined;
57
+ }
58
+ }
59
+ return current;
60
+ }
61
+
62
+ function setIn(value: unknown, segments: readonly string[], depth: number, next: unknown): unknown {
63
+ const segment = segments[depth];
64
+ if (segment === undefined) return next;
65
+
66
+ const isIndex = INDEX.test(segment);
67
+ if (Array.isArray(value) || (!isRecord(value) && isIndex)) {
68
+ if (!isIndex) return value;
69
+ const list = Array.isArray(value) ? (value as unknown[]) : [];
70
+ const index = Number(segment);
71
+ const updated = setIn(list[index], segments, depth + 1, next);
72
+ if (updated === undefined) {
73
+ // Removing an element; setting a hole is not JSON.
74
+ return index < list.length ? list.filter((_, i) => i !== index) : value;
75
+ }
76
+ if (Object.is(updated, list[index])) return value;
77
+ const copy = list.slice();
78
+ copy[index] = updated;
79
+ return copy;
80
+ }
81
+
82
+ const record = isRecord(value) ? value : {};
83
+ const has = Object.hasOwn(record, segment);
84
+ const updated = setIn(has ? record[segment] : undefined, segments, depth + 1, next);
85
+ if (updated === undefined) {
86
+ if (!has) return value;
87
+ const copy = { ...record };
88
+ delete copy[segment];
89
+ return copy;
90
+ }
91
+ if (has && Object.is(updated, record[segment])) return value;
92
+ return { ...record, [segment]: updated };
93
+ }
94
+
95
+ /**
96
+ * Write a value at a path, immutably.
97
+ *
98
+ * Every subtree off the path is shared with the input, the input is never touched, and
99
+ * setting what is already there returns the input itself. Containers that do not exist are
100
+ * created (an array before an index, an object before a key). Keys the path does not
101
+ * mention — including ones a schema does not know about — are kept.
102
+ *
103
+ * @param value - The root value.
104
+ * @param path - Dot path; `""` replaces the root.
105
+ * @param next - The new value. `undefined` removes the key (or array element) instead.
106
+ * @returns The new root.
107
+ */
108
+ export function setAtPath(value: unknown, path: string, next: unknown): unknown {
109
+ return setIn(value, splitPath(path), 0, next);
110
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * A form that edits a whole JSON value, generated from the value's JSON Schema.
3
+ *
4
+ * `SchemaForm` is for *options*: every field starts unset and only what the operator
5
+ * touches is sent. This is for *configs*: the value is complete — a calibration's settings,
6
+ * a detector's parameters — and the form edits it in place, down to a nested struct, a
7
+ * serde enum's data, a nullable block or a tuple of points, handing back the whole next
8
+ * value on each edit. What the schema cannot say (grouping, labels, units, a different
9
+ * control) the app says in a `UiSchema`.
10
+ */
11
+
12
+ import { Disclosure, Section, TooltipProvider, cn } from "@vitavision/ui";
13
+ import { useMemo, useState, type Ref } from "react";
14
+
15
+ import type { JsonSchema } from "../api/schemaNode";
16
+ import { defaultValueForSchema, fieldAt, shapeOf } from "../api/schemaValue";
17
+ import { fieldUiAt, type RenderField, type UiGroup, type UiSchema } from "../api/uiSchema";
18
+ import { setAtPath } from "../api/valuePath";
19
+ import { Grid } from "./valueForm/chrome";
20
+ import { FormContext, useForm, type FormState } from "./valueForm/context";
21
+ import { FieldNode, ObjectBody } from "./valueForm/nodes";
22
+
23
+ const NO_UI: UiSchema = {};
24
+
25
+ /** Props of `SchemaValueForm`. */
26
+ export interface SchemaValueFormProps {
27
+ /**
28
+ * The value's JSON Schema (draft 2020-12, as schemars emits it), `$defs` included. Not
29
+ * watched for change in the uncontrolled mode: give the form a `key` per schema.
30
+ */
31
+ schema: JsonSchema;
32
+ /** The value, for a controlled form. Complete: the form edits it, it does not complete it. */
33
+ value?: unknown;
34
+ /**
35
+ * The starting value, for an uncontrolled form. Without either, the form starts from
36
+ * `defaultValueForSchema(schema)`.
37
+ */
38
+ defaultValue?: unknown;
39
+ /**
40
+ * Called with the whole next value on each edit. The previous value is never mutated;
41
+ * untouched subtrees are shared with it, and keys the schema does not know are kept.
42
+ */
43
+ onValueChange?: ((next: unknown) => void) | undefined;
44
+ /** Layout the schema cannot carry: groups, labels, units, widgets. */
45
+ ui?: UiSchema | undefined;
46
+ /** `2` (the default) puts fields side by side from `sm:` up; `1` is one column, for a narrow rail. */
47
+ columns?: 1 | 2 | undefined;
48
+ /** Blocks every control. The value is still shown. */
49
+ disabled?: boolean | undefined;
50
+ /**
51
+ * Take over a field. Called for every field before the form's own control; return
52
+ * `undefined` to let the form render it. The result is placed in the field's grid cell
53
+ * as it is, so wrap it in a `Field` if it should look like its neighbours.
54
+ */
55
+ renderField?: RenderField | undefined;
56
+ /** Merged with the form's own classes through `cn`. */
57
+ className?: string | undefined;
58
+ /** The root element. */
59
+ ref?: Ref<HTMLDivElement> | undefined;
60
+ }
61
+
62
+ /** Controlled when `value` is given, otherwise the form keeps the value itself. */
63
+ function useValue(
64
+ value: unknown,
65
+ seed: () => unknown,
66
+ onValueChange: ((next: unknown) => void) | undefined,
67
+ ): [unknown, (next: unknown) => void] {
68
+ const [inner, setInner] = useState(seed);
69
+ const controlled = value !== undefined;
70
+ return [
71
+ controlled ? value : inner,
72
+ (next) => {
73
+ if (!controlled) setInner(next);
74
+ onValueChange?.(next);
75
+ },
76
+ ];
77
+ }
78
+
79
+ /**
80
+ * Edit a JSON value through its schema.
81
+ *
82
+ * Renders by the schema's shape: a number is a `NumberInput` (with its bounds, unit and an
83
+ * integer-only rule), a string an `Input`, a boolean a `Switch`, a closed set a
84
+ * `SegmentedControl` or a `Select`, a struct a nested fieldset, a serde enum a variant
85
+ * selector with the variant's fields (switching seeds them from the schema's defaults), a
86
+ * `null`-able block a switch that sets and unsets it, a list of strings an editable list, a
87
+ * fixed-length array a row of cells, and anything else a JSON textarea that keeps the last
88
+ * valid value while showing the parse error.
89
+ *
90
+ * The first paragraph of a field's description is its `InfoHint`. Round-trips: a value in,
91
+ * no edits, the same value out — the form never normalises on mount, and an edit changes
92
+ * only the leaf touched.
93
+ *
94
+ * The root is a `div` carrying `data-columns` and, while disabled, `data-disabled`. Wraps itself in a
95
+ * `TooltipProvider`, so it needs none above it.
96
+ */
97
+ export function SchemaValueForm({
98
+ schema,
99
+ value,
100
+ defaultValue,
101
+ onValueChange,
102
+ ui = NO_UI,
103
+ columns = 2,
104
+ disabled = false,
105
+ renderField,
106
+ className,
107
+ ref,
108
+ }: SchemaValueFormProps) {
109
+ const [current, commit] = useValue(
110
+ value,
111
+ () => (defaultValue !== undefined ? defaultValue : defaultValueForSchema(schema)),
112
+ onValueChange,
113
+ );
114
+ const claimed = useMemo(() => new Set((ui.groups ?? []).flatMap((group) => group.fields)), [ui.groups]);
115
+
116
+ const state: FormState = {
117
+ schema,
118
+ value: current,
119
+ setValue: (path, next) => {
120
+ const updated = setAtPath(current, path, next);
121
+ // Setting what is already there hands back the same value: nothing to report.
122
+ if (!Object.is(updated, current)) commit(updated);
123
+ },
124
+ ui,
125
+ disabled,
126
+ columns,
127
+ renderField,
128
+ claimed,
129
+ };
130
+
131
+ const root = shapeOf(schema, schema);
132
+
133
+ return (
134
+ <TooltipProvider>
135
+ <FormContext value={state}>
136
+ <div
137
+ ref={ref}
138
+ data-columns={columns}
139
+ data-disabled={disabled ? "" : undefined}
140
+ className={cn("flex min-w-0 flex-col gap-5", className)}
141
+ >
142
+ {root.kind === "object" && (ui.groups ?? []).map((group) => <GroupBlock key={group.id} group={group} />)}
143
+ {root.kind === "object" ? (
144
+ <ObjectBody path="" fields={root.fields} />
145
+ ) : (
146
+ <FieldNode path="" name={schema.title ?? "value"} node={schema} required bare />
147
+ )}
148
+ </div>
149
+ </FormContext>
150
+ </TooltipProvider>
151
+ );
152
+ }
153
+
154
+ /** A `UiGroup`: its fields under a heading, folded away if the app said so. */
155
+ function GroupBlock({ group }: { group: UiGroup }) {
156
+ const { schema, value, ui } = useForm();
157
+ const fields = group.fields.flatMap((path) => {
158
+ const info = fieldAt(schema, path, schema, value);
159
+ if (info === undefined || fieldUiAt(ui, path).hidden === true) return [];
160
+ return [{ path, info }];
161
+ });
162
+ if (fields.length === 0) return null;
163
+
164
+ const body = (
165
+ <Grid>
166
+ {fields.map(({ path, info }) => (
167
+ <FieldNode
168
+ key={path}
169
+ path={path}
170
+ name={path.split(".").at(-1) ?? path}
171
+ node={info.schema}
172
+ required={info.required}
173
+ />
174
+ ))}
175
+ </Grid>
176
+ );
177
+
178
+ if (group.collapsible === true) {
179
+ return (
180
+ <Disclosure summary={group.title} count={fields.length} defaultOpen={group.defaultOpen ?? false}>
181
+ {group.hint !== undefined && <p className="mb-3 text-xs text-fg-muted">{group.hint}</p>}
182
+ {body}
183
+ </Disclosure>
184
+ );
185
+ }
186
+ return (
187
+ <Section title={group.title} hint={group.hint}>
188
+ {body}
189
+ </Section>
190
+ );
191
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The furniture around a field: the grid it sits in, the cell it takes, and the hint and
3
+ * range note beside its label. Shared by every control so that "where does the description
4
+ * go" is decided once.
5
+ */
6
+
7
+ import { InfoHint, byDensity, cn, useDensity } from "@vitavision/ui";
8
+ import { use, type ReactNode } from "react";
9
+
10
+ import { firstParagraph } from "../../api/firstParagraph";
11
+ import type { JsonSchema } from "../../api/schemaNode";
12
+ import type { FieldUi } from "../../api/uiSchema";
13
+ import { DenseContext, useForm } from "./context";
14
+
15
+ /** Everything a control needs to know about its field. */
16
+ export interface FieldMeta {
17
+ /** The field's dot path from the root. */
18
+ path: string;
19
+ /** The label shown. */
20
+ label: string;
21
+ /** Whether the parent object requires the key. */
22
+ required: boolean;
23
+ /** The schema as written. */
24
+ node: JsonSchema;
25
+ /** The schema with `$ref` and "or null" looked through. */
26
+ schema: JsonSchema;
27
+ /** Whether `null` is accepted. */
28
+ nullable: boolean;
29
+ /** The app's presentation for the field. */
30
+ ui: FieldUi;
31
+ }
32
+
33
+ /**
34
+ * The grid cell a field takes: the full row (`sm:col-span-2`) where it has two columns to
35
+ * span, nothing otherwise.
36
+ *
37
+ * @param columns - The form's column count.
38
+ * @param ui - The field's presentation (its `span` wins).
39
+ * @param fallback - The span for a field the app said nothing about.
40
+ * @returns A Tailwind class, or `undefined`.
41
+ */
42
+ export function spanClass(columns: 1 | 2, ui: FieldUi, fallback: 1 | 2): string | undefined {
43
+ return columns === 2 && (ui.span ?? fallback) === 2 ? "sm:col-span-2" : undefined;
44
+ }
45
+
46
+ /** The field grid: two columns on `sm:` (or one), or an auto-fit row inside a tuple. */
47
+ export function Grid({ children }: { children: ReactNode }) {
48
+ const { columns } = useForm();
49
+ const dense = use(DenseContext);
50
+ const density = useDensity();
51
+ return (
52
+ <div
53
+ className={cn(
54
+ "grid min-w-0",
55
+ dense
56
+ ? "grid-cols-[repeat(auto-fit,minmax(5.5rem,1fr))] gap-2"
57
+ : cn(
58
+ byDensity(density, "gap-x-5 gap-y-4", "gap-x-4 gap-y-2.5"),
59
+ columns === 2 ? "grid-cols-1 sm:grid-cols-2" : "grid-cols-1",
60
+ ),
61
+ )}
62
+ >
63
+ {children}
64
+ </div>
65
+ );
66
+ }
67
+
68
+ function present(node: ReactNode): boolean {
69
+ return node !== undefined && node !== null && node !== false && node !== "";
70
+ }
71
+
72
+ /**
73
+ * What a field shows besides its label: the description as an `InfoHint` or as an inline
74
+ * line (or not at all), and the range note, together as the `Field` annotation.
75
+ *
76
+ * @param meta - The field.
77
+ * @param range - The bounds as text, for a number.
78
+ * @returns The hint (for a control that has no annotation slot), the inline description,
79
+ * and the annotation.
80
+ */
81
+ export function useChrome(
82
+ meta: FieldMeta,
83
+ range: string | null = null,
84
+ ): { hint: ReactNode; description: ReactNode; annotation: ReactNode } {
85
+ const dense = use(DenseContext);
86
+ const mode = meta.ui.descriptionAs ?? "hint";
87
+ const text: ReactNode = meta.ui.hint ?? firstParagraph(meta.schema.description);
88
+ const shown = !dense && present(text);
89
+
90
+ const hint = shown && mode === "hint" ? <InfoHint label={`About ${meta.label}`}>{text}</InfoHint> : null;
91
+ const description = shown && mode === "inline" ? text : undefined;
92
+ const note = dense ? null : range;
93
+ const annotation =
94
+ note !== null || hint !== null ? (
95
+ <span className="inline-flex items-center gap-1.5">
96
+ {note}
97
+ {hint}
98
+ </span>
99
+ ) : undefined;
100
+ return { hint, description, annotation };
101
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * What every node of a `SchemaValueForm` shares: the schema, the value, how to edit it, and
3
+ * the app's layout. One context rather than props threaded through every container, because
4
+ * a field is addressed by its path — it reads its own value and writes its own leaf, and
5
+ * the containers in between need not know.
6
+ */
7
+
8
+ import { createContext, use } from "react";
9
+
10
+ import type { JsonSchema } from "../../api/schemaNode";
11
+ import type { RenderField, UiSchema } from "../../api/uiSchema";
12
+
13
+ /** The form's state, for the nodes below it. */
14
+ export interface FormState {
15
+ /** The root schema, which also holds `$defs`. */
16
+ schema: JsonSchema;
17
+ /** The current root value. */
18
+ value: unknown;
19
+ /** Replace the value at a dot path; `undefined` removes the key. */
20
+ setValue: (path: string, next: unknown) => void;
21
+ /** The app's layout. */
22
+ ui: UiSchema;
23
+ /** Whether every control is disabled. */
24
+ disabled: boolean;
25
+ /** One column, or two on `sm:` and up. */
26
+ columns: 1 | 2;
27
+ /** The app's escape hatch. */
28
+ renderField: RenderField | undefined;
29
+ /** Paths a group has claimed, so the ungrouped remainder skips them. */
30
+ claimed: ReadonlySet<string>;
31
+ }
32
+
33
+ /** `null` outside a form. */
34
+ export const FormContext = createContext<FormState | null>(null);
35
+
36
+ /**
37
+ * True inside a tuple row: cells drop their descriptions and range notes and sit in an
38
+ * auto-fit grid, because a row of four numbers cannot afford a hint line each.
39
+ */
40
+ export const DenseContext = createContext(false);
41
+
42
+ /** The enclosing form's state. */
43
+ export function useForm(): FormState {
44
+ const state = use(FormContext);
45
+ if (state === null) throw new Error("A SchemaValueForm field was rendered outside its form.");
46
+ return state;
47
+ }