@vitavision/forms 0.6.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,459 @@
1
+ /**
2
+ * Turning a JSON Schema into a form, and a form back into options.
3
+ *
4
+ * An options model — a plugin's config, an algorithm's parameters — is meant to *drive*
5
+ * the UI form rather than have the form hardcoded and the schema's defaults merely hoped
6
+ * to agree with it. That stops being survivable the moment an option is *required* and
7
+ * nobody can type it.
8
+ *
9
+ * The logic lives here rather than in the component because it is where the decisions
10
+ * are: what control a schema node deserves, what an empty box means, and when a value is
11
+ * worth sending at all. Rendering is the easy half.
12
+ *
13
+ * Only the shapes pydantic (or an equivalent JSON Schema generator) actually emits are
14
+ * handled. A node this does not recognise becomes a JSON textarea rather than
15
+ * disappearing — a caller can always express what the model accepts, even where the form
16
+ * has nothing prettier to offer.
17
+ *
18
+ * ## Two things worth reading before touching `kindOf`
19
+ *
20
+ * `enum` has to be tested *before* `type`: `Literal["small", "medium"]` emits `enum`
21
+ * *alongside* `type: "string"`, and testing type first turns a closed set into a free text
22
+ * box whose placeholder is the only hint of what is accepted. A `StrEnum` is worse —
23
+ * pydantic emits it as `{"$ref": "#/$defs/ColorMode"}` with the default and description as
24
+ * siblings, and `$ref` is not in the type at all, so it falls through every branch to a
25
+ * JSON textarea unless `$defs` is resolved first.
26
+ *
27
+ * Numeric bounds are the same story: a field can carry `minimum`/`maximum` in the schema,
28
+ * and a control that ignores them turns an out-of-range value into a backend rejection
29
+ * reported nowhere near the field that caused it.
30
+ */
31
+
32
+ /** The subset of JSON Schema that pydantic (or an equivalent generator) emits for an options model. */
33
+ export type SchemaNode = {
34
+ type?: string;
35
+ title?: string;
36
+ description?: string;
37
+ default?: unknown;
38
+ items?: SchemaNode;
39
+ anyOf?: SchemaNode[];
40
+ additionalProperties?: SchemaNode | boolean;
41
+ /** A nested model's own fields. Recognised only so such a node is not mistaken for one
42
+ * of the shapes above; it still renders as a JSON textarea. */
43
+ properties?: Record<string, SchemaNode>;
44
+ enum?: unknown[];
45
+ $ref?: string;
46
+ minimum?: number;
47
+ maximum?: number;
48
+ exclusiveMinimum?: number;
49
+ exclusiveMaximum?: number;
50
+ multipleOf?: number;
51
+ /** The schema's own answer to "does the caller have to think about this?" — pydantic's
52
+ * `json_schema_extra={"x-primary": True}`. Overrides the default-based guess in both
53
+ * directions; a required field is primary regardless. */
54
+ "x-primary"?: boolean;
55
+ };
56
+
57
+ /**
58
+ * An options model's JSON Schema, as pydantic or schemars emits it for a whole model: the
59
+ * top-level object whose `properties` become the form's fields.
60
+ */
61
+ export type OptionsSchema = {
62
+ properties?: Record<string, SchemaNode>;
63
+ required?: string[];
64
+ /** Where an `Enum` or a nested model lands. Pydantic never inlines those. */
65
+ $defs?: Record<string, SchemaNode>;
66
+ };
67
+
68
+ /** Which control a field is rendered as — decided from its schema node by `describeFields`. */
69
+ export type FieldKind =
70
+ | "text"
71
+ | "number"
72
+ | "boolean"
73
+ | "string-list"
74
+ | "json"
75
+ /** A closed set, few enough to show all at once. */
76
+ | "choice-inline"
77
+ /** A closed set, too many to show at once. */
78
+ | "choice";
79
+
80
+ /** One entry of a closed set: the value as sent (stringified) and the label as shown. */
81
+ export type ChoiceOption = { value: string; label: string };
82
+
83
+ /**
84
+ * Everything the form needs to render one field, derived once from the schema by
85
+ * `describeFields` so the component makes no decisions of its own.
86
+ */
87
+ export type FieldSpec = {
88
+ name: string;
89
+ label: string;
90
+ description: string | null;
91
+ kind: FieldKind;
92
+ required: boolean;
93
+ /** Rendered into the empty control as a hint, never submitted on the caller's behalf. */
94
+ placeholder: string;
95
+ /** What applies when the field is left empty. Shown, not sent. */
96
+ fallback: unknown;
97
+ /** Behind a disclosure: there is already a working answer for this one. */
98
+ advanced: boolean;
99
+ /** The closed set, in schema order. Empty for every kind but the two choices. */
100
+ options: ChoiceOption[];
101
+ /** True when a choice's values are numbers, so the chosen one is sent as one. */
102
+ numeric: boolean;
103
+ /** Bounds the control can enforce. `"any"` step frees a float from the default of 1. */
104
+ min?: number;
105
+ max?: number;
106
+ step?: number | "any" | undefined;
107
+ /** The bounds as a reader should see them, exclusive ones included. */
108
+ range: string | null;
109
+ };
110
+
111
+ const DEFS_PREFIX = "#/$defs/";
112
+
113
+ /**
114
+ * Follow a `$ref` into `$defs`.
115
+ *
116
+ * The merge order matters and is the opposite of the obvious one. Pydantic writes the
117
+ * field's `default` and `description` *beside* the `$ref`, while the target carries the
118
+ * enum's own `title` and sometimes its own docstring as a `description`. The field's
119
+ * statement about itself wins; the type's is the fallback.
120
+ */
121
+ function deref(node: SchemaNode, defs: Record<string, SchemaNode> | undefined): SchemaNode {
122
+ if (node.$ref === undefined) return node;
123
+ if (!node.$ref.startsWith(DEFS_PREFIX)) return node;
124
+
125
+ const target = defs?.[node.$ref.slice(DEFS_PREFIX.length)];
126
+ if (target === undefined) return node;
127
+
128
+ const rest: SchemaNode = { ...node };
129
+ delete rest.$ref;
130
+ return { ...target, ...rest };
131
+ }
132
+
133
+ /**
134
+ * Look through pydantic's `str | None` encoding to the type that carries the meaning.
135
+ *
136
+ * An optional string arrives as `anyOf: [{type: "string"}, {type: "null"}]`, and treating
137
+ * that as an unrecognised node would give every nullable option a JSON textarea.
138
+ */
139
+ function unwrap(node: SchemaNode): SchemaNode {
140
+ if (!node.anyOf) return node;
141
+ const meaningful = node.anyOf.filter((branch) => branch.type !== "null");
142
+ return meaningful.length === 1 ? { ...node, ...meaningful[0] } : node;
143
+ }
144
+
145
+ /**
146
+ * The node that says what this field *is*.
147
+ *
148
+ * Dereferenced on both sides of the unwrap because either can hold the `$ref`: a plain
149
+ * `ColorMode` is a bare `$ref`, while an `Optional[ColorMode]` hides one inside `anyOf`.
150
+ */
151
+ function resolve(node: SchemaNode, defs: Record<string, SchemaNode> | undefined): SchemaNode {
152
+ return deref(unwrap(deref(node, defs)), defs);
153
+ }
154
+
155
+ function kindOf(resolved: SchemaNode): FieldKind {
156
+ // Before `type`, always: a `Literal` carries both, and the closed set is the stronger
157
+ // statement of the two.
158
+ if (Array.isArray(resolved.enum) && resolved.enum.length > 0) {
159
+ return resolved.enum.length <= 3 ? "choice-inline" : "choice";
160
+ }
161
+ if (resolved.type === "boolean") return "boolean";
162
+ if (resolved.type === "integer" || resolved.type === "number") return "number";
163
+ if (resolved.type === "string") return "text";
164
+ if (resolved.type === "array" && unwrap(resolved.items ?? {}).type === "string") {
165
+ return "string-list";
166
+ }
167
+ return "json";
168
+ }
169
+
170
+ /**
171
+ * Which options a caller has to think about, and which already have an answer.
172
+ *
173
+ * The schema says this without anyone maintaining a second list: a field whose default is
174
+ * *empty* — `[]`, `null`, `""`, or absent entirely — is one nothing can do anything useful
175
+ * with until it is filled in. A field with a real default already works, and someone
176
+ * filling in the form should not have to read past nine vocabulary options to answer the
177
+ * question that actually needs an answer.
178
+ */
179
+ function isAdvanced(node: SchemaNode): boolean {
180
+ const fallback = node.default;
181
+ if (fallback === undefined || fallback === null) return false;
182
+ if (Array.isArray(fallback)) return fallback.length > 0;
183
+ if (fallback === "") return false;
184
+ if (typeof fallback === "object") return Object.keys(fallback).length > 0;
185
+ return true;
186
+ }
187
+
188
+ /**
189
+ * A schema that marks its decisions says so with `x-primary`; one that does not is read by
190
+ * its defaults. The guess works for an adapter, whose open questions have empty defaults,
191
+ * and fails for a model's hyperparameters, where *every* field has a working default and the
192
+ * two that matter are indistinguishable from the fifteen that do not.
193
+ *
194
+ * Read from the raw node first: a `$ref` field carries its extras beside the reference.
195
+ */
196
+ function isPrimary(node: SchemaNode, resolved: SchemaNode): boolean {
197
+ const hint = node["x-primary"] ?? resolved["x-primary"];
198
+ if (hint !== undefined) return hint;
199
+ return !isAdvanced(resolved);
200
+ }
201
+
202
+ /** Raw control state: what the operator chose, not what will be sent. */
203
+ export type RawValues = Record<string, string | boolean>;
204
+
205
+ /**
206
+ * Humanise `normal_dirs` into `Normal dirs`.
207
+ *
208
+ * Pydantic emits a `title` for every field whether or not anyone wrote one, and its
209
+ * generated form is Title Case — `Csv Path`, `Defect Type From Dir` — which reads like a
210
+ * spreadsheet header rather than a form label. So a title is used only when it is *not*
211
+ * the one pydantic would have generated, which is exactly when a human chose it.
212
+ *
213
+ * Read from the *unresolved* node on purpose. Dereferencing pulls in the enum class's own
214
+ * title, so a resolved `color` field would be labelled "ColorMode".
215
+ */
216
+ function labelFor(name: string, node: SchemaNode): string {
217
+ const words = name.split("_");
218
+ const generated = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
219
+ if (node.title && node.title !== generated) return node.title;
220
+
221
+ const spaced = words.join(" ");
222
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
223
+ }
224
+
225
+ /**
226
+ * A value as a person reads it: scalars as themselves, anything structured as JSON rather
227
+ * than `[object Object]`.
228
+ */
229
+ export function displayValue(value: unknown): string {
230
+ if (value === null || value === undefined) return "";
231
+ if (typeof value === "string") return value;
232
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return value.toString();
233
+ return JSON.stringify(value) ?? "";
234
+ }
235
+
236
+ function placeholderFor(kind: FieldKind, fallback: unknown): string {
237
+ if (kind === "string-list") {
238
+ return Array.isArray(fallback) && fallback.length > 0 ? fallback.join(", ") : "a, b, c";
239
+ }
240
+ if (kind === "json") return "{}";
241
+ return displayValue(fallback);
242
+ }
243
+
244
+ /** `rgb` reads better as `Rgb` in a picker, but `bilinear` must not become `Bi Linear`. */
245
+ function optionLabel(value: unknown): string {
246
+ const text = String(value);
247
+ return text.charAt(0).toUpperCase() + text.slice(1);
248
+ }
249
+
250
+ function optionsFor(resolved: SchemaNode, kind: FieldKind): ChoiceOption[] {
251
+ if (kind !== "choice" && kind !== "choice-inline") return [];
252
+ return (resolved.enum ?? []).map((value) => ({
253
+ value: String(value),
254
+ label: optionLabel(value),
255
+ }));
256
+ }
257
+
258
+ /** The bounds as prose, keeping the distinction the HTML control cannot express. */
259
+ function rangeOf(resolved: SchemaNode): string | null {
260
+ const parts: string[] = [];
261
+ if (resolved.minimum !== undefined) parts.push(`≥ ${resolved.minimum}`);
262
+ else if (resolved.exclusiveMinimum !== undefined) parts.push(`> ${resolved.exclusiveMinimum}`);
263
+ if (resolved.maximum !== undefined) parts.push(`≤ ${resolved.maximum}`);
264
+ else if (resolved.exclusiveMaximum !== undefined) parts.push(`< ${resolved.exclusiveMaximum}`);
265
+ return parts.length > 0 ? parts.join(", ") : null;
266
+ }
267
+
268
+ function stepOf(resolved: SchemaNode): number | "any" | undefined {
269
+ if (resolved.multipleOf !== undefined) return resolved.multipleOf;
270
+ if (resolved.type === "integer") return 1;
271
+ // A number input steps by 1 unless told otherwise, which marks a learning rate of 0.0001
272
+ // invalid and refuses to submit it.
273
+ return "any";
274
+ }
275
+
276
+ /**
277
+ * Derive the form's fields from an options schema, in schema order.
278
+ *
279
+ * Resolves `$ref`s into `$defs`, looks through `anyOf: [T, null]`, picks a control per node
280
+ * (see `FieldKind`), and folds a field under "Advanced" when it is optional and its default
281
+ * already works — unless the schema says otherwise with `"x-primary"`.
282
+ *
283
+ * @param schema - The model's JSON Schema (draft 2020-12, as pydantic or schemars emit it).
284
+ * @returns One `FieldSpec` per property; empty for a model with no options.
285
+ */
286
+ export function describeFields(schema: OptionsSchema): FieldSpec[] {
287
+ const required = new Set(schema.required ?? []);
288
+ const defs = schema.$defs;
289
+
290
+ return Object.entries(schema.properties ?? {}).map(([name, node]) => {
291
+ const resolved = resolve(node, defs);
292
+ const kind = kindOf(resolved);
293
+ const numeric =
294
+ (kind === "choice" || kind === "choice-inline") &&
295
+ (resolved.type === "integer" || resolved.type === "number");
296
+
297
+ return {
298
+ name,
299
+ // From the raw node: the resolved one carries the enum type's title, not the field's.
300
+ label: labelFor(name, node),
301
+ description: node.description ?? resolved.description ?? null,
302
+ kind,
303
+ required: required.has(name),
304
+ fallback: resolved.default,
305
+ placeholder: placeholderFor(kind, resolved.default),
306
+ advanced: !required.has(name) && !isPrimary(node, resolved),
307
+ options: optionsFor(resolved, kind),
308
+ numeric,
309
+ ...(kind === "number"
310
+ ? {
311
+ min: resolved.minimum ?? resolved.exclusiveMinimum,
312
+ max: resolved.maximum ?? resolved.exclusiveMaximum,
313
+ step: stepOf(resolved),
314
+ }
315
+ : {}),
316
+ range: kind === "number" ? rangeOf(resolved) : null,
317
+ };
318
+ });
319
+ }
320
+
321
+ /**
322
+ * The controls' starting state.
323
+ *
324
+ * Text, list and choice controls start **empty even when the schema has a default**, and
325
+ * that is deliberate: a pre-filled box says "this is your value" when what is true is "this
326
+ * is what happens if you say nothing". Pre-filling would also mean every run sent every
327
+ * default back, so a later change to a default would silently not reach anyone who had
328
+ * once opened the form. The default is shown as the placeholder instead — and for a
329
+ * segmented control, as the segment already highlighted.
330
+ *
331
+ * Booleans are the exception — a checkbox has no empty state, so it starts at the
332
+ * default and is always sent.
333
+ */
334
+ export function initialValues(fields: FieldSpec[]): RawValues {
335
+ const values: RawValues = {};
336
+ for (const field of fields) {
337
+ values[field.name] = field.kind === "boolean" ? field.fallback === true : "";
338
+ }
339
+ return values;
340
+ }
341
+
342
+ /**
343
+ * Build the options object to send.
344
+ *
345
+ * An untouched control contributes **nothing**, so the receiving side's own default
346
+ * applies and stays the single definition of it. That is what keeps a default from
347
+ * existing twice, once here and once wherever it is enforced, with the two free to drift.
348
+ */
349
+ export function toOptions(fields: FieldSpec[], values: RawValues): Record<string, unknown> {
350
+ const options: Record<string, unknown> = {};
351
+
352
+ for (const field of fields) {
353
+ const raw = values[field.name];
354
+
355
+ if (field.kind === "boolean") {
356
+ // Always sent: a checkbox cannot express "unset", so leaving it out would make its
357
+ // rendered state and the value in force disagree whenever the default is `true`.
358
+ options[field.name] = raw === true;
359
+ continue;
360
+ }
361
+
362
+ const text = typeof raw === "string" ? raw.trim() : "";
363
+ if (text === "") continue;
364
+
365
+ switch (field.kind) {
366
+ case "string-list":
367
+ options[field.name] = text
368
+ .split(",")
369
+ .map((item) => item.trim())
370
+ .filter(Boolean);
371
+ break;
372
+ case "number": {
373
+ const parsed = Number(text);
374
+ if (Number.isFinite(parsed)) options[field.name] = parsed;
375
+ break;
376
+ }
377
+ case "choice":
378
+ case "choice-inline": {
379
+ // `Literal[1, 2, 3]` is a closed set whose members are numbers; the control can
380
+ // only hand back a string, so the schema's own type decides what is sent.
381
+ if (!field.numeric) {
382
+ options[field.name] = text;
383
+ break;
384
+ }
385
+ const parsed = Number(text);
386
+ if (Number.isFinite(parsed)) options[field.name] = parsed;
387
+ break;
388
+ }
389
+ case "json":
390
+ try {
391
+ options[field.name] = JSON.parse(text);
392
+ } catch {
393
+ // Left out rather than sent as a string: the receiving side would reject it with
394
+ // a less useful message than the one `jsonErrors` puts next to the field.
395
+ }
396
+ break;
397
+ default:
398
+ options[field.name] = text;
399
+ }
400
+ }
401
+
402
+ return options;
403
+ }
404
+
405
+ /** How many options the operator has actually changed, for the tab that hides them. */
406
+ export function overrideCount(fields: FieldSpec[], values: RawValues): number {
407
+ const initial = initialValues(fields);
408
+ return fields.filter((field) => values[field.name] !== initial[field.name]).length;
409
+ }
410
+
411
+ /** Which JSON fields do not parse, so the form can say so before the run starts. */
412
+ export function jsonErrors(fields: FieldSpec[], values: RawValues): string[] {
413
+ return fields
414
+ .filter((field) => field.kind === "json")
415
+ .filter((field) => {
416
+ const raw = values[field.name];
417
+ if (typeof raw !== "string" || raw.trim() === "") return false;
418
+ try {
419
+ JSON.parse(raw);
420
+ return false;
421
+ } catch {
422
+ return true;
423
+ }
424
+ })
425
+ .map((field) => field.label);
426
+ }
427
+
428
+ /** Required fields the operator has not filled in. Blocks the run. */
429
+ export function missingRequired(fields: FieldSpec[], values: RawValues): string[] {
430
+ return fields
431
+ .filter((field) => field.required)
432
+ .filter((field) => {
433
+ const raw = values[field.name];
434
+ if (typeof raw === "boolean") return false;
435
+ return (raw ?? "").trim() === "";
436
+ })
437
+ .map((field) => field.label);
438
+ }
439
+
440
+ /**
441
+ * Fields whose typed value is outside the bounds the schema states.
442
+ *
443
+ * Native `min`/`max` stop the spinner and mark the input invalid, but nothing stops a
444
+ * paste, so the check is repeated here where it can block the button.
445
+ */
446
+ export function outOfRange(fields: FieldSpec[], values: RawValues): string[] {
447
+ return fields
448
+ .filter((field) => field.kind === "number")
449
+ .filter((field) => {
450
+ const raw = values[field.name];
451
+ if (typeof raw !== "string" || raw.trim() === "") return false;
452
+ const parsed = Number(raw);
453
+ if (!Number.isFinite(parsed)) return true;
454
+ if (field.min !== undefined && parsed < field.min) return true;
455
+ if (field.max !== undefined && parsed > field.max) return true;
456
+ return false;
457
+ })
458
+ .map((field) => field.label);
459
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * An options form, generated from a JSON Schema.
3
+ *
4
+ * Adding an adapter, a model, or a measurement method costs a config module and a registry
5
+ * entry, and *nothing here* — that is the point of generating the form from the schema
6
+ * instead of hardcoding it. Every decision about which control a field deserves lives in
7
+ * `api/schemaForm.ts`; this file only renders.
8
+ *
9
+ * Two behaviours are worth knowing while reading the markup:
10
+ *
11
+ * * An empty control means **unset**, and the caller's own default applies. The default
12
+ * is shown — as a placeholder, as the pre-highlighted segment, or as the picker's
13
+ * leading entry — so a reader can see what happens if they say nothing, without that
14
+ * value being claimed as their choice.
15
+ * * A field the schema requires is marked, and the caller blocks the run on it.
16
+ *
17
+ * The layout is a two-column grid: a form of eight numeric parameters, each a full-width
18
+ * control over a full-width description, runs to screens of scrolling for a form that
19
+ * often needs nothing touched at all. Fields whose value is genuinely wide — a list, a
20
+ * JSON object, a statement with a switch — still span both columns.
21
+ */
22
+
23
+ import {
24
+ Disclosure,
25
+ Field,
26
+ NumberInput,
27
+ SegmentedControl,
28
+ Select,
29
+ Switch,
30
+ Textarea,
31
+ Input,
32
+ } from "@vitavision/ui";
33
+ import { displayValue, type FieldSpec, type RawValues } from "../api/schemaForm";
34
+
35
+ /**
36
+ * Which kinds are worth a full row. Everything else pairs up.
37
+ *
38
+ * A JSON object needs the width to be editable at all, and a switch reads as a sentence
39
+ * with its explanation beside it. A comma-separated list does *not* qualify: three of them
40
+ * in a row can run as tall as the layout this rule exists to avoid.
41
+ */
42
+ const WIDE: ReadonlySet<FieldSpec["kind"]> = new Set(["json", "boolean"]);
43
+
44
+ /**
45
+ * An options form rendered from `describeFields(schema)`: primary fields first, the rest
46
+ * folded under "Advanced", each with the control its schema node calls for.
47
+ *
48
+ * Controlled: `values` holds the raw control values (strings, or booleans for switches),
49
+ * and an empty string means "unset — the schema's default applies". Turn them into the
50
+ * options to send with `toOptions`, and gate a run on `missingRequired`, `outOfRange` and
51
+ * `jsonErrors`.
52
+ */
53
+ export function SchemaForm({
54
+ fields,
55
+ values,
56
+ onChange,
57
+ }: {
58
+ fields: FieldSpec[];
59
+ values: RawValues;
60
+ onChange: (next: RawValues) => void;
61
+ }) {
62
+ if (fields.length === 0) {
63
+ return <p className="text-sm text-fg-muted">This plugin takes no options.</p>;
64
+ }
65
+
66
+ const set = (name: string, value: string | boolean) => onChange({ ...values, [name]: value });
67
+ const render = (field: FieldSpec) => (
68
+ <SchemaField
69
+ key={field.name}
70
+ field={field}
71
+ value={values[field.name] ?? ""}
72
+ onChange={(value) => set(field.name, value)}
73
+ />
74
+ );
75
+
76
+ const primary = fields.filter((field) => !field.advanced);
77
+ const advanced = fields.filter((field) => field.advanced);
78
+
79
+ // Where nothing is required — the normal shape of a model's own hyperparameters, as
80
+ // against an adapter's "which folder holds the good images" — there is nothing to fold
81
+ // away from. Hiding every field behind a disclosure would leave a box containing only a
82
+ // disclosure, so they simply render.
83
+ if (primary.length === 0) {
84
+ return <Grid>{advanced.map(render)}</Grid>;
85
+ }
86
+
87
+ return (
88
+ <div className="flex flex-col gap-4">
89
+ <Grid>{primary.map(render)}</Grid>
90
+ {advanced.length > 0 && (
91
+ <Disclosure summary="Advanced" count={advanced.length}>
92
+ <Grid>{advanced.map(render)}</Grid>
93
+ </Disclosure>
94
+ )}
95
+ </div>
96
+ );
97
+ }
98
+
99
+ function Grid({ children }: { children: React.ReactNode }) {
100
+ return <div className="grid grid-cols-1 gap-x-5 gap-y-4 sm:grid-cols-2">{children}</div>;
101
+ }
102
+
103
+ function SchemaField({
104
+ field,
105
+ value,
106
+ onChange,
107
+ }: {
108
+ field: FieldSpec;
109
+ value: string | boolean;
110
+ onChange: (value: string | boolean) => void;
111
+ }) {
112
+ const span = WIDE.has(field.kind) ? "sm:col-span-2" : undefined;
113
+
114
+ // A switch reads as a statement and carries its own label, rather than sitting under one.
115
+ // It is also the one control with no "unset" position.
116
+ if (field.kind === "boolean") {
117
+ return (
118
+ <div className={span}>
119
+ <Switch
120
+ checked={value === true}
121
+ onCheckedChange={onChange}
122
+ label={field.label}
123
+ description={field.description}
124
+ />
125
+ </div>
126
+ );
127
+ }
128
+
129
+ const text = typeof value === "string" ? value : "";
130
+ const fallback = field.fallback === undefined || field.fallback === null
131
+ ? undefined
132
+ : displayValue(field.fallback);
133
+
134
+ if (field.kind === "choice-inline") {
135
+ return (
136
+ <Field
137
+ as="group"
138
+ label={field.label}
139
+ description={field.description}
140
+ required={field.required}
141
+ className={span}
142
+ >
143
+ <SegmentedControl
144
+ aria-label={field.label}
145
+ value={text}
146
+ defaultValue={fallback}
147
+ options={field.options}
148
+ onValueChange={onChange}
149
+ />
150
+ </Field>
151
+ );
152
+ }
153
+
154
+ if (field.kind === "choice") {
155
+ return (
156
+ <Field
157
+ as="group"
158
+ label={field.label}
159
+ description={field.description}
160
+ required={field.required}
161
+ className={span}
162
+ >
163
+ <Select
164
+ aria-label={field.label}
165
+ value={text}
166
+ onValueChange={onChange}
167
+ options={field.options}
168
+ placeholder={fallback === undefined ? "Choose…" : `Default · ${fallback}`}
169
+ unsetLabel={fallback === undefined ? undefined : `Default · ${fallback}`}
170
+ />
171
+ </Field>
172
+ );
173
+ }
174
+
175
+ return (
176
+ <Field
177
+ label={field.label}
178
+ description={
179
+ field.kind === "string-list"
180
+ ? [field.description, "Comma-separated."].filter(Boolean).join(" ")
181
+ : field.description
182
+ }
183
+ required={field.required}
184
+ annotation={field.range}
185
+ className={span}
186
+ >
187
+ {field.kind === "json" ? (
188
+ <Textarea
189
+ rows={2}
190
+ aria-label={field.label}
191
+ placeholder={field.placeholder}
192
+ value={text}
193
+ onChange={(event) => onChange(event.target.value)}
194
+ />
195
+ ) : field.kind === "number" ? (
196
+ <NumberInput
197
+ aria-label={field.label}
198
+ placeholder={field.placeholder}
199
+ min={field.min}
200
+ max={field.max}
201
+ step={field.step}
202
+ value={text}
203
+ onChange={(event) => onChange(event.target.value)}
204
+ />
205
+ ) : (
206
+ <Input
207
+ className="font-mono"
208
+ aria-label={field.label}
209
+ placeholder={field.placeholder}
210
+ value={text}
211
+ onChange={(event) => onChange(event.target.value)}
212
+ />
213
+ )}
214
+ </Field>
215
+ );
216
+ }
package/src/index.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A JSON Schema (draft 2020-12, as schemars and pydantic emit it) rendered as an options form.
3
+ *
4
+ * `describeFields` turns the schema into field specs, `SchemaForm` renders them, and
5
+ * `toOptions` / `missingRequired` / `outOfRange` / `jsonErrors` turn the form's raw values
6
+ * back into the options to send and the reasons not to send them yet.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+
11
+ export { SchemaForm } from "./components/SchemaForm";
12
+
13
+ export {
14
+ describeFields,
15
+ initialValues,
16
+ jsonErrors,
17
+ missingRequired,
18
+ outOfRange,
19
+ overrideCount,
20
+ toOptions,
21
+ type ChoiceOption,
22
+ type FieldKind,
23
+ type FieldSpec,
24
+ type OptionsSchema,
25
+ type RawValues,
26
+ type SchemaNode,
27
+ } from "./api/schemaForm";