Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

SchemaForm.tsx

598 lines15.0 KB

1/**
2 * Generative UI: a form rendered entirely from a JSON Schema at render time.
3 * No component here knows anything about any particular provider — controls
4 * are chosen from schema keywords (enum, type, bounds, anyOf/oneOf, $defs).
5 */
6import { useId, useState } from 'react'
7import {
8 asJsonValue,
9 enumValues,
10 isJsonObject,
11 matchVariant,
12 num,
13 obj,
14 properties,
15 requiredNames,
16 resolveRef,
17 schemaLabel,
18 schemaType,
19 seedValue,
20 str,
21 variants,
22} from '../lib/jsonschema'
23import type { JsonObject, JsonValue, SchemaNode } from '../lib/jsonschema'
24​
25const MAX_DEPTH = 9
26​
27interface ControlProps {
28 schema: SchemaNode
29 root: SchemaNode
30 value: JsonValue | undefined
31 onChange: (value: JsonValue) => void
32 depth: number
34​
35export function SchemaForm({
36 schema,
37 value,
38 onChange,
39}: {
40 schema: SchemaNode
41 value: JsonValue
42 onChange: (value: JsonValue) => void
43}) {
44 return (
45 <SchemaControl
46 schema={schema}
47 root={schema}
48 value={value}
49 onChange={onChange}
50 depth={0}
51 />
52 )
54​
55function SchemaControl(props: ControlProps) {
56 const { root, value, onChange, depth } = props
57 const schema = resolveRef(props.schema, root)
58​
59 if (depth > MAX_DEPTH) {
60 return <RawJsonControl value={value} onChange={onChange} />
61 }
62​
63 const constant = asJsonValue(schema['const'])
64 if (constant !== undefined && enumValues(schema) === undefined) {
65 return <ConstBadge value={constant} />
66 }
67​
68 const options = enumValues(schema)
69 if (options !== undefined) {
70 return <EnumControl options={options} value={value} onChange={onChange} />
71 }
72​
73 const variantList = variants(schema, root)
74 if (variantList !== undefined) {
75 if (variantList.length === 1 && variantList[0] !== undefined) {
76 return (
77 <SchemaControl
78 schema={variantList[0]}
79 root={root}
80 value={value}
81 onChange={onChange}
82 depth={depth}
83 />
84 )
85 }
86 return (
87 <VariantControl
88 root={root}
89 value={value}
90 onChange={onChange}
91 depth={depth}
92 variantList={variantList}
93 />
94 )
95 }
96​
97 switch (schemaType(schema)) {
98 case 'boolean':
99 return <BooleanControl value={value} onChange={onChange} />
100 case 'integer':
101 case 'number':
102 return (
103 <NumberControl
104 schema={schema}
105 value={value}
106 onChange={onChange}
107 integer={schemaType(schema) === 'integer'}
108 />
109 )
110 case 'string':
111 return <StringControl schema={schema} value={value} onChange={onChange} />
112 case 'array':
113 return (
114 <ArrayControl
115 schema={schema}
116 root={root}
117 value={value}
118 onChange={onChange}
119 depth={depth}
120 />
121 )
122 case 'object':
123 return (
124 <ObjectControl
125 schema={schema}
126 root={root}
127 value={value}
128 onChange={onChange}
129 depth={depth}
130 />
131 )
132 default:
133 return <RawJsonControl value={value} onChange={onChange} />
134 }
136​
137function ConstBadge({ value }: { value: JsonValue }) {
138 return (
139 <span className="const-badge" title="fixed by the schema (const)">
140 {typeof value === 'string' ? value : JSON.stringify(value)}
141 </span>
142 )
144​
145function EnumControl({
146 options,
147 value,
148 onChange,
149}: {
150 options: Array<JsonValue>
151 value: JsonValue | undefined
152 onChange: (value: JsonValue) => void
153}) {
154 const asLabel = (option: JsonValue) =>
155 typeof option === 'string' ? option : JSON.stringify(option)
156 if (options.length <= 6) {
157 return (
158 <div className="chip-row" role="radiogroup">
159 {options.map((option) => (
160 <button
161 key={asLabel(option)}
162 type="button"
163 role="radio"
164 aria-checked={value === option}
165 className={value === option ? 'chip chip-on' : 'chip'}
166 onClick={() => onChange(option)}
167 >
168 {asLabel(option)}
169 </button>
170 ))}
171 </div>
172 )
173 }
174 const selected = options.findIndex((option) => option === value)
175 return (
176 <select
177 className="field-input"
178 value={selected === -1 ? '' : String(selected)}
179 onChange={(event) => {
180 const next = options[Number(event.target.value)]
181 if (next !== undefined) onChange(next)
182 }}
183 >
184 {selected === -1 && <option value="">— choose —</option>}
185 {options.map((option, index) => (
186 <option key={asLabel(option)} value={String(index)}>
187 {asLabel(option)}
188 </option>
189 ))}
190 </select>
191 )
193​
194function BooleanControl({
195 value,
196 onChange,
197}: {
198 value: JsonValue | undefined
199 onChange: (value: JsonValue) => void
200}) {
201 const on = value === true
202 return (
203 <button
204 type="button"
205 role="switch"
206 aria-checked={on}
207 className={on ? 'toggle toggle-on' : 'toggle'}
208 onClick={() => onChange(!on)}
209 >
210 <span className="toggle-thumb" />
211 <span className="toggle-text">{on ? 'true' : 'false'}</span>
212 </button>
213 )
215​
216function NumberControl({
217 schema,
218 value,
219 onChange,
220 integer,
221}: {
222 schema: SchemaNode
223 value: JsonValue | undefined
224 onChange: (value: JsonValue) => void
225 integer: boolean
226}) {
227 const min = num(schema, 'minimum')
228 const max = num(schema, 'maximum')
229 const current = typeof value === 'number' ? value : (min ?? 0)
230 const parse = (text: string) => {
231 const parsed = integer ? parseInt(text, 10) : parseFloat(text)
232 if (!Number.isNaN(parsed)) onChange(parsed)
233 }
234 if (min !== undefined && max !== undefined && max > min) {
235 const step = integer ? 1 : (max - min) / 100
236 return (
237 <div className="number-rail">
238 <input
239 type="range"
240 min={min}
241 max={max}
242 step={step}
243 value={current}
244 onChange={(event) => parse(event.target.value)}
245 />
246 <input
247 type="number"
248 className="field-input number-readout"
249 min={min}
250 max={max}
251 step={step}
252 value={current}
253 onChange={(event) => parse(event.target.value)}
254 />
255 </div>
256 )
257 }
258 return (
259 <input
260 type="number"
261 className="field-input number-readout"
262 min={min}
263 max={max}
264 value={typeof value === 'number' ? value : ''}
265 onChange={(event) => parse(event.target.value)}
266 />
267 )
269​
270const LONG_TEXT_HINT = /prompt|content|text|message|instruction|description/i
271​
272function StringControl({
273 schema,
274 value,
275 onChange,
276}: {
277 schema: SchemaNode
278 value: JsonValue | undefined
279 onChange: (value: JsonValue) => void
280}) {
281 const text = typeof value === 'string' ? value : ''
282 const title = str(schema, 'title') ?? str(schema, 'description') ?? ''
283 const long =
284 (num(schema, 'maxLength') ?? 0) > 160 || LONG_TEXT_HINT.test(title)
285 if (long) {
286 return (
287 <textarea
288 className="field-input field-textarea"
289 rows={3}
290 value={text}
291 placeholder={str(schema, 'example')}
292 onChange={(event) => onChange(event.target.value)}
293 />
294 )
295 }
296 return (
297 <input
298 type={str(schema, 'format') === 'uri' ? 'url' : 'text'}
299 className="field-input"
300 value={text}
301 placeholder={str(schema, 'example') ?? str(schema, 'format')}
302 onChange={(event) => onChange(event.target.value)}
303 />
304 )
306​
307function VariantControl({
308 root,
309 value,
310 onChange,
311 depth,
312 variantList,
313}: Omit<ControlProps, 'schema'> & { variantList: Array<SchemaNode> }) {
314 const [picked, setPicked] = useState(() => matchVariant(value, variantList))
315 const active = variantList[Math.min(picked, variantList.length - 1)]
316 return (
317 <div className="variant">
318 <div className="variant-tabs" role="tablist">
319 {variantList.map((variant, index) => (
320 <button
321 key={index}
322 type="button"
323 role="tab"
324 aria-selected={index === picked}
325 className={index === picked ? 'tab tab-on' : 'tab'}
326 onClick={() => {
327 setPicked(index)
328 onChange(seedValue(variant, root))
329 }}
330 >
331 {schemaLabel(variant, `option ${String(index + 1)}`)}
332 </button>
333 ))}
334 </div>
335 {active !== undefined && (
336 <SchemaControl
337 schema={active}
338 root={root}
339 value={value}
340 onChange={onChange}
341 depth={depth + 1}
342 />
343 )}
344 </div>
345 )
347​
348function ArrayControl({ schema, root, value, onChange, depth }: ControlProps) {
349 const items = obj(schema, 'items')
350 const list = Array.isArray(value) ? value : []
351 const setIndex = (index: number, next: JsonValue) => {
352 const copy = [...list]
353 copy[index] = next
354 onChange(copy)
355 }
356 return (
357 <div className="array-box">
358 {list.map((item, index) => (
359 <div className="array-row" key={index}>
360 <span className="array-index">{index}</span>
361 <div className="array-item">
362 {items !== undefined ? (
363 <SchemaControl
364 schema={items}
365 root={root}
366 value={item}
367 onChange={(next) => setIndex(index, next)}
368 depth={depth + 1}
369 />
370 ) : (
371 <RawJsonControl
372 value={item}
373 onChange={(next) => setIndex(index, next)}
374 />
375 )}
376 </div>
377 <button
378 type="button"
379 className="ghost-button"
380 aria-label={`remove item ${String(index)}`}
381 onClick={() => onChange(list.filter((_, at) => at !== index))}
382 >
383 ×
384 </button>
385 </div>
386 ))}
387 <button
388 type="button"
389 className="add-button"
390 onClick={() =>
391 onChange([
392 ...list,
393 items !== undefined ? seedValue(items, root) : null,
394 ])
395 }
396 >
397 + add {items !== undefined ? schemaLabel(items, 'item') : 'item'}
398 </button>
399 </div>
400 )
402​
403function ObjectControl({ schema, root, value, onChange, depth }: ControlProps) {
404 const record: JsonObject = isJsonObject(value) ? value : {}
405 const required = requiredNames(schema)
406 const props = properties(schema)
407 const present = props.filter(([name]) => required.has(name) || name in record)
408 const absent = props.filter(
409 ([name]) => !required.has(name) && !(name in record),
410 )
411 const setProp = (name: string, next: JsonValue) => {
412 onChange({ ...record, [name]: next })
413 }
414 const dropProp = (name: string) => {
415 const { [name]: _, ...rest } = record
416 onChange(rest)
417 }
418 return (
419 <div className={depth === 0 ? 'object-root' : 'object-box'}>
420 {present.map(([name, prop]) => {
421 const resolved = resolveRef(prop, root)
422 return (
423 <Field
424 key={name}
425 name={name}
426 required={required.has(name)}
427 description={str(resolved, 'description')}
428 onRemove={required.has(name) ? undefined : () => dropProp(name)}
429 >
430 <SchemaControl
431 schema={prop}
432 root={root}
433 value={record[name]}
434 onChange={(next) => setProp(name, next)}
435 depth={depth + 1}
436 />
437 </Field>
438 )
439 })}
440 {absent.length > 0 && (
441 <div className="optional-row">
442 {absent.map(([name, prop]) => (
443 <button
444 key={name}
445 type="button"
446 className="optional-chip"
447 title={str(resolveRef(prop, root), 'description')}
448 onClick={() => setProp(name, seedValue(prop, root))}
449 >
450 + {name}
451 </button>
452 ))}
453 </div>
454 )}
455 </div>
456 )
458​
459function Field({
460 name,
461 required,
462 description,
463 onRemove,
464 children,
465}: {
466 name: string
467 required: boolean
468 description: string | undefined
469 onRemove: (() => void) | undefined
470 children: React.ReactNode
471}) {
472 const id = useId()
473 const [open, setOpen] = useState(false)
474 const blurb = description?.split(/\n/, 1)[0]
475 return (
476 <div className="field" data-required={required}>
477 <div className="field-head">
478 <label htmlFor={id} className="field-name">
479 {name}
480 {required && <span className="field-req">*</span>}
481 </label>
482 {blurb !== undefined && blurb.length > 0 && (
483 <button
484 type="button"
485 className="field-hint-toggle"
486 aria-expanded={open}
487 onClick={() => setOpen(!open)}
488 >
489 ?
490 </button>
491 )}
492 {onRemove !== undefined && (
493 <button
494 type="button"
495 className="ghost-button"
496 aria-label={`remove ${name}`}
497 onClick={onRemove}
498 >
499 ×
500 </button>
501 )}
502 </div>
503 {open && blurb !== undefined && <p className="field-hint">{blurb}</p>}
504 <div id={id}>{children}</div>
505 </div>
506 )
508​
509function RawJsonControl({
510 value,
511 onChange,
512}: {
513 value: JsonValue | undefined
514 onChange: (value: JsonValue) => void
515}) {
516 const [draft, setDraft] = useState(() =>
517 JSON.stringify(value ?? null, null, 2),
518 )
519 const [bad, setBad] = useState(false)
520 return (
521 <textarea
522 className={
523 bad
524 ? 'field-input field-textarea json-bad'
525 : 'field-input field-textarea'
526 }
527 rows={4}
528 spellCheck={false}
529 value={draft}
530 onChange={(event) => {
531 setDraft(event.target.value)
532 try {
533 const parsed = asJsonValue(JSON.parse(event.target.value))
534 if (parsed !== undefined) {
535 onChange(parsed)
536 setBad(false)
537 }
538 } catch {
539 setBad(true)
540 }
541 }}
542 />
543 )
545​
546/** Pretty, colorized read-only JSON tree for the payload pane. */
547export function JsonView({ value }: { value: JsonValue }) {
548 return <pre className="json-view">{renderJson(value, 0)}</pre>
550​
551function renderJson(value: JsonValue, indent: number): React.ReactNode {
552 const pad = ' '.repeat(indent)
553 const inner = ' '.repeat(indent + 1)
554 if (value === null) return <span className="j-null">null</span>
555 if (typeof value === 'string')
556 return <span className="j-str">{JSON.stringify(value)}</span>
557 if (typeof value === 'number')
558 return <span className="j-num">{String(value)}</span>
559 if (typeof value === 'boolean')
560 return <span className="j-bool">{String(value)}</span>
561 if (Array.isArray(value)) {
562 if (value.length === 0) return '[]'
563 return (
564 <>
565 {'[\n'}
566 {value.map((item, index) => (
567 <span key={index}>
568 {inner}
569 {renderJson(item, indent + 1)}
570 {index < value.length - 1 ? ',' : ''}
571 {'\n'}
572 </span>
573 ))}
574 {pad}
575 {']'}
576 </>
577 )
578 }
579 const entries = Object.entries(value)
580 if (entries.length === 0) return '{}'
581 return (
582 <>
583 {'{\n'}
584 {entries.map(([key, item], index) => (
585 <span key={key}>
586 {inner}
587 <span className="j-key">{JSON.stringify(key)}</span>
588 {': '}
589 {renderJson(item, indent + 1)}
590 {index < entries.length - 1 ? ',' : ''}
591 {'\n'}
592 </span>
593 ))}
594 {pad}
595 {'}'}
596 </>
597 )