@vitavision/forms 0.6.5 → 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,331 @@
1
+ /**
2
+ * The tree of a `SchemaValueForm`: a field dispatcher and the containers that nest it.
3
+ *
4
+ * A node is addressed by its dot path. It reads its value from the form, writes it back by
5
+ * path, and renders whatever its schema's shape calls for: a control for a leaf, a
6
+ * fieldset for an object, a variant selector for a union, a row for a tuple, a switch for
7
+ * a nullable composite.
8
+ */
9
+
10
+ import { Checkbox, Switch, byDensity, cn, useDensity } from "@vitavision/ui";
11
+ import { use, type ReactNode } from "react";
12
+
13
+ import { firstParagraph } from "../../api/firstParagraph";
14
+ import { labelFor, resolveSchema, type JsonSchema } from "../../api/schemaNode";
15
+ import {
16
+ activeExternal,
17
+ activeTagged,
18
+ seedNotNull,
19
+ seedVariant,
20
+ shapeOf,
21
+ type FieldInfo,
22
+ type SchemaShape,
23
+ } from "../../api/schemaValue";
24
+ import { fieldUiAt } from "../../api/uiSchema";
25
+ import { getAtPath, joinPath } from "../../api/valuePath";
26
+ import { Grid, spanClass, useChrome, type FieldMeta } from "./chrome";
27
+ import { Chooser, BooleanLeaf, EnumLeaf, JsonLeaf, NumberLeaf, StringListLeaf, TextLeaf } from "./leaves";
28
+ import { DenseContext, useForm } from "./context";
29
+
30
+ type TaggedShape = Extract<SchemaShape, { kind: "tagged" }>;
31
+ type ExternalShape = Extract<SchemaShape, { kind: "external" }>;
32
+ type TupleShape = Extract<SchemaShape, { kind: "tuple" }>;
33
+
34
+ const BOOLEANS = [
35
+ { value: true, label: "true" },
36
+ { value: false, label: "false" },
37
+ ];
38
+
39
+ /** Shapes that are a block of their own, so a nullable one gets a switch rather than an empty box. */
40
+ function isComposite(shape: SchemaShape): boolean {
41
+ return (
42
+ shape.kind === "object" ||
43
+ shape.kind === "tagged" ||
44
+ shape.kind === "external" ||
45
+ shape.kind === "tuple" ||
46
+ shape.kind === "string-list"
47
+ );
48
+ }
49
+
50
+ /** `ui.widget` can change what an array or any value is edited as. */
51
+ function applyWidget(shape: SchemaShape, meta: FieldMeta, value: unknown): SchemaShape {
52
+ const items = typeof meta.schema.items === "object" ? meta.schema.items : undefined;
53
+ switch (meta.ui.widget) {
54
+ case "json":
55
+ return { kind: "json" };
56
+ case "string-list":
57
+ return meta.schema.type === "array" ? { kind: "string-list", item: items ?? { type: "string" } } : shape;
58
+ case "tuple-row":
59
+ return items !== undefined && Array.isArray(value)
60
+ ? { kind: "tuple", items: (value as unknown[]).map(() => items) }
61
+ : shape;
62
+ default:
63
+ return shape;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * One field of the form, at a path.
69
+ *
70
+ * Honours the app's `hidden` and `renderField`, then renders the control or container its
71
+ * schema's shape calls for. A nullable composite (an object that may be `null`) gets a
72
+ * switch; a nullable leaf is an empty control.
73
+ */
74
+ export function FieldNode({
75
+ path,
76
+ name,
77
+ node,
78
+ required,
79
+ bare = false,
80
+ }: {
81
+ path: string;
82
+ /** The key (or index) the field has in its parent, for the default label. */
83
+ name: string;
84
+ /** The schema as written. */
85
+ node: JsonSchema;
86
+ required: boolean;
87
+ /** Without the container's own chrome (legend, border): the root, and a switched-on nullable. */
88
+ bare?: boolean;
89
+ }) {
90
+ const form = useForm();
91
+ const ui = fieldUiAt(form.ui, path);
92
+ if (ui.hidden === true) return null;
93
+
94
+ const { schema, nullable } = resolveSchema(node, form.schema);
95
+ const value = getAtPath(form.value, path);
96
+ const meta: FieldMeta = { path, label: ui.label ?? labelFor(name, node), required, node, schema, nullable, ui };
97
+ const shape = applyWidget(shapeOf(schema, form.schema), meta, value);
98
+
99
+ if (form.renderField !== undefined) {
100
+ const custom = form.renderField({
101
+ path,
102
+ schema,
103
+ value,
104
+ onChange: (next) => form.setValue(path, next),
105
+ disabled: form.disabled,
106
+ });
107
+ if (custom !== undefined) {
108
+ return <div className={spanClass(form.columns, ui, isComposite(shape) ? 2 : 1)}>{custom}</div>;
109
+ }
110
+ }
111
+
112
+ if (nullable && isComposite(shape)) return <NullableNode meta={meta} shape={shape} />;
113
+ return <ShapeNode meta={meta} shape={shape} bare={bare} />;
114
+ }
115
+
116
+ /** Render a resolved shape. */
117
+ function ShapeNode({ meta, shape, bare }: { meta: FieldMeta; shape: SchemaShape; bare: boolean }) {
118
+ switch (shape.kind) {
119
+ case "integer":
120
+ case "number":
121
+ return <NumberLeaf meta={meta} />;
122
+ case "string":
123
+ return <TextLeaf meta={meta} />;
124
+ case "boolean":
125
+ return meta.nullable ? <EnumLeaf meta={meta} options={BOOLEANS} /> : <BooleanLeaf meta={meta} />;
126
+ case "enum":
127
+ return <EnumLeaf meta={meta} options={shape.options} />;
128
+ case "string-list":
129
+ return <StringListLeaf meta={meta} minItems={meta.schema.minItems} maxItems={meta.schema.maxItems} />;
130
+ case "json":
131
+ return <JsonLeaf meta={meta} />;
132
+ case "object":
133
+ return <ObjectNode meta={meta} fields={shape.fields} bare={bare} />;
134
+ case "tagged":
135
+ case "external":
136
+ return <UnionNode meta={meta} shape={shape} bare={bare} />;
137
+ case "tuple":
138
+ return <TupleNode meta={meta} shape={shape} bare={bare} />;
139
+ }
140
+ }
141
+
142
+ /** The fields of an object that are neither hidden by the app nor claimed by a group. */
143
+ function useVisible(path: string, fields: FieldInfo[]): FieldInfo[] {
144
+ const form = useForm();
145
+ return fields.filter((field) => {
146
+ const child = joinPath(path, field.key);
147
+ return !form.claimed.has(child) && fieldUiAt(form.ui, child).hidden !== true;
148
+ });
149
+ }
150
+
151
+ /**
152
+ * The fields of an object, each as a node, skipping hidden ones and ones a group has claimed.
153
+ * Renders nothing when none is left.
154
+ */
155
+ export function ObjectBody({ path, fields }: { path: string; fields: FieldInfo[] }) {
156
+ const visible = useVisible(path, fields);
157
+ if (visible.length === 0) return null;
158
+
159
+ return (
160
+ <Grid>
161
+ {visible.map((field) => (
162
+ <FieldNode key={field.key} path={joinPath(path, field.key)} name={field.key} node={field.schema} required={field.required} />
163
+ ))}
164
+ </Grid>
165
+ );
166
+ }
167
+
168
+ /** The frame of a composite field: its label and hint over its content. `bare` drops the frame. */
169
+ function Frame({ meta, bare, children }: { meta: FieldMeta; bare: boolean; children: ReactNode }) {
170
+ const form = useForm();
171
+ const dense = use(DenseContext);
172
+ const density = useDensity();
173
+ const chrome = useChrome(meta);
174
+ if (bare) return <div className="flex min-w-0 flex-col gap-3">{children}</div>;
175
+
176
+ return (
177
+ <fieldset
178
+ className={cn(
179
+ "flex min-w-0 flex-col gap-3 rounded-panel border border-line",
180
+ byDensity(density, "p-3", "p-2"),
181
+ !dense && spanClass(form.columns, meta.ui, 2),
182
+ )}
183
+ >
184
+ <legend className="px-1">
185
+ <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-fg">
186
+ {meta.label}
187
+ {chrome.hint}
188
+ </span>
189
+ </legend>
190
+ {chrome.description !== undefined && <p className="text-xs leading-snug text-fg-muted">{chrome.description}</p>}
191
+ {children}
192
+ </fieldset>
193
+ );
194
+ }
195
+
196
+ function ObjectNode({ meta, fields, bare }: { meta: FieldMeta; fields: FieldInfo[]; bare: boolean }) {
197
+ if (useVisible(meta.path, fields).length === 0) return null;
198
+ return (
199
+ <Frame meta={meta} bare={bare}>
200
+ <ObjectBody path={meta.path} fields={fields} />
201
+ </Frame>
202
+ );
203
+ }
204
+
205
+ /** A union: the variant selector, the variant's description, and the variant's fields. */
206
+ function UnionNode({ meta, shape, bare }: { meta: FieldMeta; shape: TaggedShape | ExternalShape; bare: boolean }) {
207
+ const form = useForm();
208
+ const value = getAtPath(form.value, meta.path);
209
+ const active = shape.kind === "tagged" ? activeTagged(shape, value) : activeExternal(shape, value);
210
+ const options = shape.variants.map((variant) => ({
211
+ value: variant.tag,
212
+ label: meta.ui.enumLabels?.[variant.tag] ?? variant.label,
213
+ }));
214
+ const explained = meta.ui.descriptionAs === "none" ? "" : firstParagraph(active?.description);
215
+
216
+ let body: ReactNode = null;
217
+ if (shape.kind === "tagged") {
218
+ const variant = activeTagged(shape, value);
219
+ if (variant !== undefined) body = <ObjectBody path={meta.path} fields={variant.fields} />;
220
+ } else {
221
+ const variant = activeExternal(shape, value);
222
+ if (variant?.payload !== undefined) {
223
+ const inner = joinPath(meta.path, variant.tag);
224
+ const payload = shapeOf(variant.payload, form.schema);
225
+ body =
226
+ payload.kind === "object" ? (
227
+ <ObjectBody path={inner} fields={payload.fields} />
228
+ ) : (
229
+ <Grid>
230
+ <FieldNode path={inner} name={variant.tag} node={variant.payload} required />
231
+ </Grid>
232
+ );
233
+ }
234
+ }
235
+
236
+ return (
237
+ <Frame meta={meta} bare={bare}>
238
+ <Chooser
239
+ label={meta.label}
240
+ options={options}
241
+ value={active?.tag ?? ""}
242
+ widget={meta.ui.widget}
243
+ disabled={form.disabled}
244
+ onChoose={(tag) => {
245
+ const next = seedVariant(shape, tag, form.schema);
246
+ if (next !== undefined) form.setValue(meta.path, next);
247
+ }}
248
+ />
249
+ {explained !== "" && <p className="text-xs leading-snug text-fg-muted">{explained}</p>}
250
+ {body}
251
+ </Frame>
252
+ );
253
+ }
254
+
255
+ /**
256
+ * A fixed-length array as a compact row: one cell per position (a row of numbers), or one
257
+ * row per position when the positions are objects (a list of points).
258
+ */
259
+ function TupleNode({ meta, shape, bare }: { meta: FieldMeta; shape: TupleShape; bare: boolean }) {
260
+ const form = useForm();
261
+ const cells = shape.items.map((item, index) => {
262
+ const name = String(index);
263
+ return { name, item, resolved: shapeOf(item, form.schema), path: joinPath(meta.path, name) };
264
+ });
265
+ const rows = cells.some((cell) => cell.resolved.kind === "object");
266
+
267
+ return (
268
+ <Frame meta={meta} bare={bare}>
269
+ <DenseContext value>
270
+ {rows ? (
271
+ <div className="flex flex-col gap-2">
272
+ {cells.map((cell) => (
273
+ <div key={cell.name} role="group" aria-label={`${meta.label} ${cell.name}`} className="flex items-start gap-2">
274
+ <span className="w-4 shrink-0 pt-1.5 font-mono text-xs text-fg-subtle" aria-hidden>
275
+ {cell.name}
276
+ </span>
277
+ <div className="min-w-0 flex-1">
278
+ {cell.resolved.kind === "object" ? (
279
+ <ObjectBody path={cell.path} fields={cell.resolved.fields} />
280
+ ) : (
281
+ <Grid>
282
+ <FieldNode path={cell.path} name={cell.name} node={cell.item} required />
283
+ </Grid>
284
+ )}
285
+ </div>
286
+ </div>
287
+ ))}
288
+ </div>
289
+ ) : (
290
+ <Grid>
291
+ {cells.map((cell) => (
292
+ <FieldNode key={cell.name} path={cell.path} name={cell.name} node={cell.item} required />
293
+ ))}
294
+ </Grid>
295
+ )}
296
+ </DenseContext>
297
+ </Frame>
298
+ );
299
+ }
300
+
301
+ /**
302
+ * A composite that may be `null`: a switch for "set / unset", and the content only while set.
303
+ * Switching it on seeds the content from the schema's defaults.
304
+ */
305
+ function NullableNode({ meta, shape }: { meta: FieldMeta; shape: SchemaShape }) {
306
+ const form = useForm();
307
+ const chrome = useChrome(meta);
308
+ const value = getAtPath(form.value, meta.path);
309
+ const set = value !== null && value !== undefined;
310
+ const props = {
311
+ checked: set,
312
+ label: meta.label,
313
+ description: chrome.description,
314
+ disabled: form.disabled,
315
+ onCheckedChange: (next: boolean) => form.setValue(meta.path, next ? seedNotNull(meta.node, form.schema) : null),
316
+ };
317
+
318
+ return (
319
+ <div className={cn("flex min-w-0 flex-col gap-3", spanClass(form.columns, meta.ui, 2))}>
320
+ <div className="flex items-start gap-1.5">
321
+ {meta.ui.widget === "checkbox" ? <Checkbox {...props} /> : <Switch {...props} />}
322
+ {chrome.hint !== null && <span className="mt-0.5">{chrome.hint}</span>}
323
+ </div>
324
+ {set && (
325
+ <div className="min-w-0 border-l border-line pl-3">
326
+ <ShapeNode meta={meta} shape={shape} bare />
327
+ </div>
328
+ )}
329
+ </div>
330
+ );
331
+ }
package/src/index.ts CHANGED
@@ -5,10 +5,17 @@
5
5
  * `toOptions` / `missingRequired` / `outOfRange` / `jsonErrors` turn the form's raw values
6
6
  * back into the options to send and the reasons not to send them yet.
7
7
  *
8
+ * `SchemaValueForm` is the other form: it edits a *whole* value (a config, nested to any
9
+ * depth, with serde enums and nullable blocks) and hands back the whole next value. It reads
10
+ * the schema through the same resolver, exposed here as `resolveSchema` and `shapeOf`, with
11
+ * `defaultValueForSchema`, `fieldAt` / `fieldsAt`, `getAtPath` / `setAtPath` and
12
+ * `firstParagraph` as pure helpers; a `UiSchema` carries the layout the schema cannot.
13
+ *
8
14
  * @packageDocumentation
9
15
  */
10
16
 
11
17
  export { SchemaForm } from "./components/SchemaForm";
18
+ export { SchemaValueForm, type SchemaValueFormProps } from "./components/SchemaValueForm";
12
19
 
13
20
  export {
14
21
  describeFields,
@@ -25,3 +32,20 @@ export {
25
32
  type RawValues,
26
33
  type SchemaNode,
27
34
  } from "./api/schemaForm";
35
+
36
+ export { firstParagraph } from "./api/firstParagraph";
37
+ export { resolveRef, resolveSchema, type JsonSchema, type ResolvedSchema } from "./api/schemaNode";
38
+ export {
39
+ defaultValueForSchema,
40
+ fieldAt,
41
+ fieldsAt,
42
+ shapeOf,
43
+ type EnumOption,
44
+ type EnumValue,
45
+ type ExternalVariant,
46
+ type FieldInfo,
47
+ type SchemaShape,
48
+ type TaggedVariant,
49
+ } from "./api/schemaValue";
50
+ export type { FieldUi, FieldWidget, RenderField, RenderFieldContext, UiGroup, UiSchema } from "./api/uiSchema";
51
+ export { getAtPath, setAtPath } from "./api/valuePath";