import type { JSONSchema } from '../api' import { useForm } from './context' import { Widget } from './Form' import { defaultFor, discriminators, pickVariant, resolveSchema, variantLabel, variantsOf } from './resolve' /** oneOf / anyOf: choose a branch, then edit it with that branch's own form. */ export function VariantField({ schema: s, value, onChange, path }: { schema: JSONSchema; value: unknown; onChange(v: unknown): void; path: string }) { const { root } = useForm() const branches = variantsOf(s) ?? [] const current = pickVariant(root, branches, value) const choose = (i: number) => { if (i < 0) return onChange(undefined) const b = branches[i] const base = defaultFor(root, b) const consts = discriminators(root, b) // Keep what the old branch and the new one share, so switching does not wipe the user's input. const carried = value && typeof value === 'object' && base && typeof base === 'object' ? Object.fromEntries(Object.entries(value as object).filter(([k]) => k in (resolveSchema(root, b).schema.properties ?? {}))) : {} onChange(base && typeof base === 'object' && !Array.isArray(base) ? { ...base, ...carried, ...consts } : base) } return (