@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,395 @@
1
+ /**
2
+ * The controls of a `SchemaValueForm`: one per kind of leaf value. Each reads its own value
3
+ * from the form by path and writes its own leaf back; none knows its neighbours.
4
+ */
5
+
6
+ import {
7
+ Button,
8
+ Checkbox,
9
+ Field,
10
+ Input,
11
+ NumberInput,
12
+ SegmentedControl,
13
+ Select,
14
+ Switch,
15
+ Textarea,
16
+ byDensity,
17
+ cn,
18
+ parseNumber,
19
+ useDensity,
20
+ } from "@vitavision/ui";
21
+ import { use, useState, type ChangeEvent, type ReactNode } from "react";
22
+
23
+ import { firstParagraph } from "../../api/firstParagraph";
24
+ import { checkNumber, numberSpec, rangeText } from "../../api/numberSpec";
25
+ import { displayValue } from "../../api/schemaForm";
26
+ import type { EnumOption } from "../../api/schemaValue";
27
+ import { defaultValueForSchema } from "../../api/schemaValue";
28
+ import { getAtPath } from "../../api/valuePath";
29
+ import type { FieldWidget } from "../../api/uiSchema";
30
+ import { useChrome, spanClass, type FieldMeta } from "./chrome";
31
+ import { DenseContext, useForm } from "./context";
32
+
33
+ /** `required` as the marker shows it: a nullable field is never mandatory. */
34
+ function marked(meta: FieldMeta): boolean {
35
+ return meta.required && !meta.nullable;
36
+ }
37
+
38
+ /** Where `null` is a legal value, an empty control says so. */
39
+ const NULL_PLACEHOLDER = "none";
40
+
41
+ /** A number field: bounds, unit and a verdict on what was typed. */
42
+ export function NumberLeaf({ meta }: { meta: FieldMeta }) {
43
+ const form = useForm();
44
+ const value = getAtPath(form.value, meta.path);
45
+ const spec = numberSpec(meta.schema, meta.ui);
46
+ const chrome = useChrome(meta, rangeText(spec));
47
+ const [error, setError] = useState<string | undefined>();
48
+
49
+ const fallback = meta.schema.default;
50
+ const restore = meta.ui.restoreDefaultOnClear ?? true;
51
+ let onClear: (() => void) | undefined;
52
+ if (meta.nullable) onClear = () => form.setValue(meta.path, null);
53
+ else if (restore && typeof fallback === "number") onClear = () => form.setValue(meta.path, fallback);
54
+ else if (!meta.required) onClear = () => form.setValue(meta.path, undefined);
55
+ else if (restore) onClear = () => form.setValue(meta.path, defaultValueForSchema(meta.schema, form.schema));
56
+
57
+ const judge = (event: ChangeEvent<HTMLInputElement>) => {
58
+ const text = event.currentTarget.value;
59
+ const parsed = parseNumber(text);
60
+ if (text.trim() === "") setError(undefined);
61
+ else setError(parsed === null ? "Enter a number" : checkNumber(spec, parsed));
62
+ };
63
+
64
+ return (
65
+ <Field
66
+ label={meta.label}
67
+ required={marked(meta)}
68
+ annotation={chrome.annotation}
69
+ description={chrome.description}
70
+ error={error}
71
+ className={spanClass(form.columns, meta.ui, 1)}
72
+ >
73
+ <NumberInput
74
+ aria-label={meta.label}
75
+ disabled={form.disabled}
76
+ placeholder={meta.nullable ? NULL_PLACEHOLDER : typeof fallback === "number" ? String(fallback) : undefined}
77
+ value={typeof value === "number" ? value : null}
78
+ min={spec.min}
79
+ max={spec.max}
80
+ step={spec.step}
81
+ unit={spec.unit}
82
+ onChange={judge}
83
+ onBlur={() => setError(undefined)}
84
+ onValueChange={(next) => {
85
+ // The control already holds back what is out of `[min, max]`; the integer rule and
86
+ // the exclusive bounds are ours.
87
+ if (checkNumber(spec, next) === undefined) form.setValue(meta.path, next);
88
+ }}
89
+ onClear={onClear}
90
+ />
91
+ </Field>
92
+ );
93
+ }
94
+
95
+ /** A string field. Where `null` is legal, emptying it means `null`. */
96
+ export function TextLeaf({ meta }: { meta: FieldMeta }) {
97
+ const form = useForm();
98
+ const value = getAtPath(form.value, meta.path);
99
+ const chrome = useChrome(meta);
100
+ const fallback = meta.schema.default;
101
+
102
+ return (
103
+ <Field
104
+ label={meta.label}
105
+ required={marked(meta)}
106
+ annotation={chrome.annotation}
107
+ description={chrome.description}
108
+ className={spanClass(form.columns, meta.ui, 1)}
109
+ >
110
+ <Input
111
+ className="font-mono"
112
+ autoComplete="off"
113
+ spellCheck={false}
114
+ aria-label={meta.label}
115
+ disabled={form.disabled}
116
+ placeholder={meta.nullable ? NULL_PLACEHOLDER : typeof fallback === "string" ? fallback : undefined}
117
+ value={typeof value === "string" ? value : ""}
118
+ onChange={(event) => {
119
+ const text = event.currentTarget.value;
120
+ form.setValue(meta.path, meta.nullable && text === "" ? null : text);
121
+ }}
122
+ />
123
+ </Field>
124
+ );
125
+ }
126
+
127
+ /** A choice among a few values (all shown) or many (a picker). */
128
+ export function Chooser({
129
+ label,
130
+ options,
131
+ value,
132
+ onChoose,
133
+ unsetLabel,
134
+ widget,
135
+ disabled,
136
+ }: {
137
+ label: string;
138
+ options: { value: string; label: string }[];
139
+ /** The chosen option's value, or `""`. */
140
+ value: string;
141
+ onChoose: (value: string) => void;
142
+ /** Adds an entry that returns the field to unset (a nullable value). */
143
+ unsetLabel?: string | undefined;
144
+ widget?: FieldWidget | undefined;
145
+ disabled: boolean;
146
+ }) {
147
+ const size = byDensity(useDensity(), "md", "sm");
148
+ const strip = widget === "segmented" || (widget !== "select" && options.length <= 3 && unsetLabel === undefined);
149
+ return strip ? (
150
+ <SegmentedControl
151
+ aria-label={label}
152
+ size={size}
153
+ disabled={disabled}
154
+ value={value}
155
+ options={options}
156
+ onValueChange={onChoose}
157
+ />
158
+ ) : (
159
+ <Select
160
+ aria-label={label}
161
+ disabled={disabled}
162
+ value={value}
163
+ options={options}
164
+ placeholder={unsetLabel ?? "Choose…"}
165
+ unsetLabel={unsetLabel}
166
+ onValueChange={onChoose}
167
+ />
168
+ );
169
+ }
170
+
171
+ /** A closed set of primitives: `enum`, `const`, or `oneOf` of `{ const }`. */
172
+ export function EnumLeaf({ meta, options }: { meta: FieldMeta; options: EnumOption[] }) {
173
+ const form = useForm();
174
+ const dense = use(DenseContext);
175
+ const value = getAtPath(form.value, meta.path);
176
+ const chrome = useChrome(meta);
177
+
178
+ const shown = options.map((option) => ({
179
+ value: String(option.value),
180
+ label: meta.ui.enumLabels?.[String(option.value)] ?? option.label,
181
+ }));
182
+ const selected = options.find((option) => option.value === value);
183
+ // The chosen variant's own sentence ("No distortion; no parameter block.") under the strip.
184
+ const explained =
185
+ !dense && meta.ui.descriptionAs !== "none" ? firstParagraph(selected?.description) : "";
186
+ const description: ReactNode =
187
+ explained !== "" && chrome.description !== undefined ? (
188
+ <>
189
+ {chrome.description} {explained}
190
+ </>
191
+ ) : explained !== "" ? (
192
+ explained
193
+ ) : (
194
+ chrome.description
195
+ );
196
+
197
+ return (
198
+ <Field
199
+ as="group"
200
+ label={meta.label}
201
+ required={marked(meta)}
202
+ annotation={chrome.annotation}
203
+ description={description}
204
+ className={spanClass(form.columns, meta.ui, 1)}
205
+ >
206
+ <Chooser
207
+ label={meta.label}
208
+ options={shown}
209
+ value={selected === undefined ? "" : String(selected.value)}
210
+ widget={meta.ui.widget}
211
+ disabled={form.disabled}
212
+ unsetLabel={meta.nullable ? "None" : undefined}
213
+ onChoose={(chosen) => {
214
+ if (chosen === "") {
215
+ if (meta.nullable) form.setValue(meta.path, null);
216
+ return;
217
+ }
218
+ const option = options.find((candidate) => String(candidate.value) === chosen);
219
+ if (option !== undefined) form.setValue(meta.path, option.value);
220
+ }}
221
+ />
222
+ </Field>
223
+ );
224
+ }
225
+
226
+ /** A boolean: a switch (the default) or a checkbox. */
227
+ export function BooleanLeaf({ meta }: { meta: FieldMeta }) {
228
+ const form = useForm();
229
+ const value = getAtPath(form.value, meta.path);
230
+ const chrome = useChrome(meta);
231
+ const props = {
232
+ checked: value === true,
233
+ onCheckedChange: (next: boolean) => form.setValue(meta.path, next),
234
+ label: meta.label,
235
+ description: chrome.description,
236
+ disabled: form.disabled,
237
+ };
238
+
239
+ return (
240
+ <div className={cn("flex min-w-0 items-start gap-1.5", spanClass(form.columns, meta.ui, 1))}>
241
+ {meta.ui.widget === "checkbox" ? <Checkbox {...props} /> : <Switch {...props} />}
242
+ {chrome.hint !== null && <span className="mt-0.5">{chrome.hint}</span>}
243
+ </div>
244
+ );
245
+ }
246
+
247
+ function pretty(value: unknown): string {
248
+ return value === undefined ? "" : JSON.stringify(value, null, 2);
249
+ }
250
+
251
+ /**
252
+ * Anything the form has no control for, as JSON.
253
+ *
254
+ * What is typed is kept as typed. A valid edit goes to the form; an invalid one shows its
255
+ * parse error and leaves the last good value where it was. The text only resets when the
256
+ * value changes from outside.
257
+ */
258
+ export function JsonLeaf({ meta }: { meta: FieldMeta }) {
259
+ const form = useForm();
260
+ const value = getAtPath(form.value, meta.path);
261
+ const chrome = useChrome(meta);
262
+ const canonical = JSON.stringify(value) ?? "";
263
+ const [draft, setDraft] = useState<{ text: string; error: string | undefined; base: string }>(() => ({
264
+ text: pretty(value),
265
+ error: undefined,
266
+ base: canonical,
267
+ }));
268
+ if (draft.base !== canonical) setDraft({ text: pretty(value), error: undefined, base: canonical });
269
+
270
+ const edit = (text: string) => {
271
+ if (text.trim() === "") {
272
+ if (meta.required) {
273
+ setDraft({ text, error: "Enter a JSON value", base: draft.base });
274
+ } else {
275
+ setDraft({ text, error: undefined, base: "" });
276
+ form.setValue(meta.path, undefined);
277
+ }
278
+ return;
279
+ }
280
+ try {
281
+ const parsed: unknown = JSON.parse(text);
282
+ setDraft({ text, error: undefined, base: JSON.stringify(parsed) });
283
+ form.setValue(meta.path, parsed);
284
+ } catch (problem) {
285
+ setDraft({ text, error: `Invalid JSON: ${problem instanceof Error ? problem.message : String(problem)}`, base: draft.base });
286
+ }
287
+ };
288
+
289
+ return (
290
+ <Field
291
+ label={meta.label}
292
+ required={marked(meta)}
293
+ annotation={chrome.annotation}
294
+ description={chrome.description}
295
+ error={draft.error}
296
+ className={spanClass(form.columns, meta.ui, 2)}
297
+ >
298
+ <Textarea
299
+ rows={Math.min(Math.max(draft.text.split("\n").length, 3), 12)}
300
+ spellCheck={false}
301
+ aria-label={meta.label}
302
+ disabled={form.disabled}
303
+ value={draft.text}
304
+ onChange={(event) => edit(event.currentTarget.value)}
305
+ />
306
+ </Field>
307
+ );
308
+ }
309
+
310
+ interface RowIds {
311
+ ids: number[];
312
+ next: number;
313
+ }
314
+
315
+ /** Grow or shrink the row ids to `length`, keeping the ids of the rows that stay. */
316
+ function syncIds(rows: RowIds, length: number): RowIds {
317
+ if (rows.ids.length === length) return rows;
318
+ const ids = rows.ids.slice(0, length);
319
+ let next = rows.next;
320
+ while (ids.length < length) ids.push(next++);
321
+ return { ids, next };
322
+ }
323
+
324
+ /**
325
+ * An array of strings as a list: one input per entry, add and remove.
326
+ *
327
+ * Each row has an id of its own, so removing the second of three keeps the focus and the
328
+ * cursor of the others instead of re-keying them by position.
329
+ */
330
+ export function StringListLeaf({ meta, minItems, maxItems }: { meta: FieldMeta; minItems?: number | undefined; maxItems?: number | undefined }) {
331
+ const form = useForm();
332
+ const value = getAtPath(form.value, meta.path);
333
+ const chrome = useChrome(meta);
334
+ const raw: unknown[] = Array.isArray(value) ? (value as unknown[]) : [];
335
+ const [rows, setRows] = useState<RowIds>(() => syncIds({ ids: [], next: 0 }, raw.length));
336
+ const synced = syncIds(rows, raw.length);
337
+ if (synced !== rows) setRows(synced);
338
+
339
+ const write = (list: unknown[]) => form.setValue(meta.path, list);
340
+ const canRemove = minItems === undefined || raw.length > minItems;
341
+ const canAdd = maxItems === undefined || raw.length < maxItems;
342
+
343
+ return (
344
+ <Field
345
+ as="group"
346
+ label={meta.label}
347
+ required={marked(meta)}
348
+ annotation={chrome.annotation}
349
+ description={chrome.description}
350
+ className={spanClass(form.columns, meta.ui, 2)}
351
+ >
352
+ <div className="flex flex-col gap-1.5">
353
+ {raw.map((entry, index) => (
354
+ <div key={synced.ids[index]} className="flex gap-1.5">
355
+ <Input
356
+ className="min-w-0 flex-1 font-mono"
357
+ autoComplete="off"
358
+ spellCheck={false}
359
+ aria-label={`${meta.label} ${index + 1}`}
360
+ disabled={form.disabled}
361
+ value={displayValue(entry)}
362
+ onChange={(event) => {
363
+ const copy = raw.slice();
364
+ copy[index] = event.currentTarget.value;
365
+ write(copy);
366
+ }}
367
+ />
368
+ <Button
369
+ variant="ghost"
370
+ aria-label={`Remove ${meta.label} ${index + 1}`}
371
+ disabled={form.disabled || !canRemove}
372
+ onClick={() => {
373
+ setRows({ ids: synced.ids.filter((_, i) => i !== index), next: synced.next });
374
+ write(raw.filter((_, i) => i !== index));
375
+ }}
376
+ >
377
+ ×
378
+ </Button>
379
+ </div>
380
+ ))}
381
+ <Button
382
+ className="self-start"
383
+ aria-label={`Add ${meta.label}`}
384
+ disabled={form.disabled || !canAdd}
385
+ onClick={() => {
386
+ setRows({ ids: [...synced.ids, synced.next], next: synced.next + 1 });
387
+ write([...raw, ""]);
388
+ }}
389
+ >
390
+ Add
391
+ </Button>
392
+ </div>
393
+ </Field>
394
+ );
395
+ }