SchemaForm Declarative Form
Describe a form with one schema (a JSON Schema subset) plus an optional uiSchema (UI annotations). The component compiles it into a render plan and mounts it on the form family. Value management and field validation state stay in oas-form; error injection, array-level validation, reaction evaluation and compilation are owned by this component.
Value contract (read first):
getValues()andoas-submit.detail.valuesfollow the form kernel's string semantics — leaves are always strings (numberyields"42",booleanyields"true", arrays yield JSON strings). Before evaluation and validation the component projects values by the schematyperead-only ("42"→ 42), while submitted values are unchanged. Type-preserving output is planned for a later version.
Scope: V1 covers declarative compilation, rendering, validation,
whenSchema-only reactions and array add/remove. Expression reactions, controlledvalues/setValues, custom widget registration and array tables come later (calling them raises a dev warning, never a silent failure). Useoas-questionnairefor multi-step flows.
Basic usage
schema / uiSchema / initialValues all support property + JSON attribute dual channels (assign objects in host frameworks; use schema='{...}' in static HTML). Field labels come from title and help text from description; required on a parent object is compiled into child field requirements.
Basic: input / number / switch / enum / email
Reactions (whenSchema)
reactions live on the source field's uiSchema node. A whenSchema condition is a JSON Schema validation; scope defaults to the field itself ($self). fulfill accepts visible / disabled / required / value; otherwise falls back to the static annotation. visible: false unmounts the field (its value is not submitted and not validated); inside array rows the key slot is kept as an empty string. Refresh is directed by a dependency graph — only fields whose conditions depend on the changed path are re-evaluated.
Value reactions (fulfill.value): when the condition holds, the expression result is written into the target field (strings follow the kernel string semantics; numbers / booleans / null may also be written as literals). The value expression shares the compiler and dependency graph with when; written values participate in the fixed-point iteration (8-round cap, a dev warning keeps the last round when it does not converge) and drive downstream reactions. When the condition is false, otherwise.value is written if declared; otherwise the current value is kept. Writes only apply to visible targets — the hidden / unmounted semantics of visible: false take precedence.
Hide/require fields by country, lock input by plan
Value reaction: qty × price writes the total, and reaching the threshold unlocks the discount
Reactions (when expressions)
when is the restricted expression track (V1b): the condition is a string, paths use {path} placeholders (dot notation plus [i], array wildcard []) and the source field is $self. Frozen syntax: values (string / number / true/false/null), comparisons == != > >= < <= (numeric when both sides are numbers, otherwise string comparison), logic && || ! with parentheses, arithmetic + - * / % (numbers only — a non-numeric operand yields NaN at runtime, and NaN comparisons are always false), membership in / contains(), and a function library of 20: iif / empty / len / sum / min / max / lower / upper / concat / join / split / substring / replace / trim / round / abs / floor / ceil / formatDate / dateAdd (iif is lazy; concatenate strings with concat(...strings) — + is numeric addition only; formatDate freezes the tokens yyyy MM dd HH mm ss, uses the local timezone, prints unknown tokens verbatim with a dev warning; dateAdd supports day / hour / minute / month — month arithmetic clamps to the month end (Jan 31 + 1 month → Feb 28, Feb 29 in leap years; negative amounts behave the same) and keeps the time of day; there is no now() — non-determinism conflicts with the static recomputation model, feed the current time through a controlled value instead). Assignments / statements / loops / arrow functions / template strings / regex literals / property access chains are compile-time errors; syntax errors, unknown fields and unknown functions only disable that single reaction (dev warning) while the rest keep working. The two tracks differ in expressiveness — they are not advertised as equivalent; prefer whenSchema when you want JSON Schema semantics.
Host functions: after registerExprFunction(name, fn) you can call the function by name. Their dependencies cannot be extracted statically, so reactions using host functions recompute on every value change (everything else still uses the directed dependency graph). Register before setting the schema. Host first: when a host function shares a name with a built-in, the host implementation wins (with a one-time dev warning) instead of being silently shadowed.
when expression: plan + seats drive invoice visibility and note requirement
Arrays and nesting
Object arrays render through oas-form-list: the initial array length drives row creation (one initial row renders one row), add/remove use the existing row interactions, and row fields are re-indexed. Array-level validation (minItems / maxItems / uniqueItems / required) runs in this component; errors are injected into the array path and rendered below the list as part="array-error" (role="alert").
Object array: initial rows / add-remove / minItems error
Nested arrays: users → matrix (field names users.N.matrix.M.label)
Empty array + minItems: submit shows the array-level error (part=array-error)
Nested array-level validation: inner minItems lands on that row's own error slot
Inline-edit table (array-table)
Object arrays can also render as an inline-edit table with uiSchema.widget: 'array-table'. Row content is still rendered by this component (each cell is a form-item, so value collection / validation / reactions / error injection all work unchanged); the table only adds the two-dimensional layout, the header row and the row-action column — it is the same value semantics as oas-form-list in a different presentation.
- Columns come from the declaration order of
items.properties. Column-level annotations live onusers[].field:width(numbers are px, strings are used as grid tracks such as'2fr'),align(left/center/right),hidden(visually hidden but the cell and its value are kept); awidgetoverride also applies to cells. - Cells do not render their own label (the header carries it) and the
*of required fields moves to the header; widget widths are constrained to the cell withmax-width: 100%(fixed-width controls never spill into the action column). - The action column holds remove / duplicate / move-up / move-down; the add button appends below the table. Semantics match
oas-form-listrow operations (deep copy / value swap, focus returns by row position,aria-liveannouncements). - Column resizing: drag the divider at the right edge of a header (or focus the handle and press
←/→for 8px,Shiftfor 24px,Hometo restore the annotationwidth). The numericwidthis only an initial value; the runtime width is display state and is never written back to the uiSchema. - Column reordering: drag a header cell to change the display order (the drop target shows an insertion hint). This is display state too: the
items.properties/ uiSchema order remains authoritative, and field names, values and validation are untouched. - Cross-row paste: pasting TSV (
\tseparates columns, newlines separate rows) into any cell fills right/down from that cell and appends rows as needed. Content beyondmaxItemsis truncated with anaria-liveannouncement and a one-time dev warning per instance; hidden columns are skipped; a single-value paste is left to the native input. Pasted values go through the existing widget write channel, so type mismatches are caught by the validation chain. Paste emitsoas-paste(detail: { startRow, startColumn, rows, columns, truncated, addedRows }, whereaddedRowsis the number of appended rows) and refreshesdirty/ reactions in the same turn. Error visuals are cleared only for row-appending pastes (addedRows > 0); value-only pastes keep the error state of unfixed fields. - Events:
oas-add/oas-remove(detail: { index }),oas-duplicate/oas-move(detail: { from, to }),oas-paste(bulk TSV fill). - Row operations change values but do not emit
oas-values-change(contract preserved); the component refreshesdirty, reactions and the controlled write baseline in the same turn, so the host only needs to follow along in its ownvalues(a controlled host write will not roll the operation back). - Structure changes (
schema/uiSchema) restore the current row counts; rewritinginitialValuesandreset()go back to the initial row count. Switching between the two widgets keeps the data (row-count and value snapshots combined). - Table semantics use ARIA (
role="table"/columnheader/row/cell) plus CSS grid for geometry; no native<table>(slots cannot producetd, and row content must stay in light DOM for the form kernel). - Virtual scrolling (
virtual): windowed rendering for thousand-row arrays — only the visible window plus overscan is mounted (overscanadjustable, 5 rows per side by default), row heights are measured and calibrated (estimated-row-heightseeds the initial estimate; the default estimate is overwritten by measured self-calibration), and spacers keep the total height stable. Row wrappers all stay in the light DOM:aria-rowcountalways reports the total, and controlled writes / validation / name renumbering / row operations / paste semantics are unchanged. When present, theviewport-heightattribute is synced into the container's inlinemax-height(box height and window calculation share one source, so tail rows stay reachable when scrolled to the bottom; removing the attribute falls back to the CSS default of 320px, with the CSS--oas-array-table-viewport-heightoverride); the header stays outside the scroll area (naturally sticky), and in virtual mode "add row" scrolls the new row into view and focuses its first field. - Division of labour with the full-featured
oas-table: this widget targets lightweight forms and does not do paging / server-side window fetching / bulk operations / cell merging (large local arrays usevirtualwindowed rendering).
Inline-edit table: column annotations + row actions (duplicate / move / remove)
Resize columns / reorder columns / paste TSV (drag the header divider or header cells; paste multi-line TSV into a cell)
Virtual scrolling (standalone usage: click to fill 300 rows, scroll to watch windowing)
Layout: grid / group / tabs
layout.span (1–24) occupies grid columns when the form uses layout="grid". layout.type="group" renders an object node as a group container; layout.type="tabs" with tabs: [{ key, title, fields }] renders tabs (role=tablist, arrow keys / Home / End switch tabs). Fields omitted from every tab are merged into the first tab with a dev warning (never silently dropped).
Group + tabs + grid span
Error injection (server validation)
setErrors([{ path, message, severity? }]) injects server errors. Paths are normalized by parseNamePath (users[0].name equals users.0.name). Injected errors take precedence over rule errors until the field value changes again. severity: 'warning' only informs (role="status", no aria-invalid); an error on the same path takes exclusive precedence.
setErrors / clearErrors / warning
Controlled values and dirty state
In controlled mode the values property is the source of truth: it acts as the baseline on mount, and each later change is written as a leaf-level diff (only changed paths, no DOM rebuild, no focus loss). A value tree node that exactly matches a rendered field name is written as a whole value — array-valued fields (array of enum → a single oas-checkbox-group) accept { tags: ['a', 'b'] } directly, while object-array container keys still descend to row fields. Keys removed by the host clear the corresponding field. Host writes never emit oas-values-change (no echo loop); only user interaction does. Arrays grow via min (rows are never removed by this channel — row removal stays with form-list). setValues(patch) is the method form of the same channel; dirty compares against the component-held pristine snapshot (a small explicit piece outside the kernel). When both values and initialValues are provided, values wins.
Controlled values: host change → diff write; setValues() and dirty
Custom widgets
registerSchemaWidget(name, tag, { reader, writer }) maps a registration name to a custom element; the schema only references the name (uiSchema.widget: 'score'). It calls registerFormControl internally (the kernel's only value-collection extension point), so reader / writer must follow the kernel contract (read a string, write the controlled value).
Hard constraint: non-custom-element widgets (Vue / React components or native tags) cannot take part in value collection — the kernel matches value channels by element tag. A tag without a hyphen is rejected with a dev warning. Register before setting the schema.
Custom widget: five-level score control (custom element + reader/writer)
Value transforms (convert / transform)
Both directions have a hook (bare keys; the host registers implementations and the schema only references the name):
convert(inbound): applied once before writing into the component on the three inbound channels —initialValuesbackfill, controlledvalues,setValues(). Typing, snapshot restore after a structure change and schemadefaultnever pass through it (otherwise values would be converted twice). Empty values are not passed to the hook. The hook may return a Promise (e.g. an exchange-rate lookup): the field keeps the host value until it resolves (documented stale window), late results are discarded by a per-path sequence guard, a user edit supersedes an in-flight conversion, and a rejection only logs a dev warning while keeping the host value.transformremains synchronous (an async transform is ignored with a dev warning).transform(outbound): applied togetValues()and to theoas-submit/oas-validate-fail/oas-values-changepayloads (detail.values/detail.valueare rewritten in place, bubbling continues,targetunchanged).- Signature
(value, fieldPath, wholeValues) => value; only leaf fields are eligible (declaring it on a container warns and is ignored); array rows use wildcard paths (users[].price). A throwing or unregistered hook produces a dev warning and falls back to identity — values are never silently rewritten. - Internal dirty state / snapshots / controlled write baseline always use the raw kernel values, so outbound transforms never change the "has it been edited" verdict.
- Register with
registerSchemaConverter(name, fn)/registerSchemaTransformer(name, fn)(separate registry — expression functions must not be able to call value transforms, and names cannot collide).
Value transforms: host passes yuan, the component collects cents (convert in / transform out)
Async conversion: convert returns a Promise (simulated exchange-rate call; the field keeps the host value until it lands)
Async options (options.source)
Options of option widgets (oas-select / oas-radio-group / oas-checkbox-group) can come from an async function:
options.source = '<name>': register it withregisterSchemaOptionSource(name, (values, path) => Promise<Option[]>);Optionis{ label, value, disabled?, description? }(same shape as the staticoptionschannel).options.sourceDeps = ['<path>']: declare value dependencies; when one of them changes the options reload automatically ("A changes → reload B"), otherwise no request is made.- Channel priority:
enum/const(data schema) >options.options(static list) >options.source; when several channels are declared the higher one wins with a one-time dev warning (the other channel is not silently dropped). - Races: a per-field request sequence guard discards stale responses, identical requests during a rebuild are de-duplicated, and responses landing after unmount are dropped. Failure shows a status block below the widget (message + retry button, i18n); an empty result shows an empty-state text; loading is carried by the widgets'
loadingstate (oas-selectreuses its existingloading,oas-radio-group/oas-checkbox-groupgained aloadingboolean attribute that renders a spinner).reloadOptions(path?)lets the host refresh manually. - When the default mapping would be a plain text input, a field declaring
options.sourceis upgraded tooas-select(an options channel needs an option widget). - The first SSR frame has no options: it renders the empty state (no skeleton), and data arrives after mount.
Async options: province → city (sourceDeps) + failure retry
Question widgets (matrix / rank) via uiSchema
Question widgets are part of the built-in widget table: set widget: 'oas-matrix' or 'oas-rank' and inject their data through the options channel — rows (array → JSON) for matrix sub-questions, columns (accepted only by matrix and custom widgets) for matrix columns, and an options array for the rank items. Values are still collected with the form core's string contract (JSON strings).
matrix / rank driven by plain JSON
Composing with Questionnaire
The component implements the duck-typed contract (getValues() / validate() and emits oas-values-change), so it can be used directly as questionnaire step content — the whole questionnaire is driven by JSON while the questionnaire only handles step navigation and cross-step aggregation.
A schema-form inside every questionnaire step
Empty states
A missing or invalid schema, a non-object root, or zero fields all render a placeholder (never an empty block). Compile error details are written to the placeholder title; empty arrays show a "no items" hint. Every uiSchema path must exist in the data schema (use users[].name wildcards for arrays); typos raise a dev warning.
Empty states (no schema / invalid schema / no fields)
API
oas-schema-form
Attributes
| Attribute | Description | Type | Default |
|---|---|---|---|
disabled | Disables the whole form through the kernel form chain (fields and array add/remove buttons). | — | — |
initial-values | Uncontrolled one-time baseline (nested object). Deep-merged over schema default with host values winning; the initial array length drives row creation. | Record<string, unknown> | string | — |
label-align | Forwarded to the inner oas-form label alignment (top / left / right). | — | — |
label-width | Forwarded to the inner oas-form label width. | — | — |
layout | Forwarded to the inner oas-form layout (with grid, fields occupy columns by layout.span). | — | — |
schema | Data schema (a JSON Schema subset). Dual channel: property (object, preferred) and attribute (JSON string); an attribute changed after the property invalidates the property (drift guard). | unknown | — |
size | Forwarded to the inner oas-form size. | — | — |
ui-schema | UI annotation layer (bare keys: widget / layout / options / reactions / keepValueOnHidden / convert / transform / column-level width / align / hidden). Dual channel; every path is verified against the data schema at compile time. | unknown | — |
validate-trigger | Forwarded to the inner oas-form field validation trigger (input / change / blur). | — | — |
values | Controlled values (V1b): object property plus JSON-string attribute channel. Acts as the baseline on mount, then each change is written as a leaf-level diff (no DOM rebuild, no focus loss); a node that exactly matches a rendered field name is written as a whole value (array-valued fields such as array of enum → oas-checkbox-group take ["a","b"] directly, while object-array container keys still descend to row fields); host writes never emit oas-values-change (no echo loop); wins over initialValues when both are provided. | Record<string, unknown> | string | — |
Methods
| Method | Signature | Description |
|---|---|---|
submit | submit(): void | Submit: evaluates reactions, runs kernel field validation, then array-level validation and injects its errors, and finally delegates to the kernel (design order: kernel first, array-level second; oas-submit / oas-validate-fail are dispatched by the kernel and bubble out, failure payload = field errors ∪ array-level errors). |
validate | validate(): Promise<boolean> | Validate: reactions → kernel field validation → array-level validation (union of errors); returns whether everything passes. |
getValues | getValues(): Record<string, unknown> | Current form values using the kernel string semantics (leaves are always strings, arrays are JSON strings); fields configured with transform are mapped back to host semantics. |
reloadOptions | reloadOptions(path?: string): void | Manually reload async options (options.source): omit the path to reload everything. Shares the race guards with automatic loading (sequence / de-duplication / drop after unmount); a manual call always starts a fresh request. |
setValues | setValues(patch: Record<string, unknown>): void | Controlled write channel (V1b): writes field values by nested path through the kernel oas-form.setValues and the control writer registry; a path that exactly matches a rendered field name is written as a whole value (array-valued fields are not split into index paths), container keys still descend; only rendered fields are written, no events are emitted and no DOM is rebuilt; unrendered paths are skipped (row count stays with form-list). |
setErrors | setErrors(list: FormError[]): void | Inject errors (for server validation). Path normalization and precedence are handled by the form kernel. |
clearErrors | clearErrors(paths?: string[]): void | Clear injected errors (omit paths to clear all); affected fields fall back to rule errors. |
reset | reset(): void | Reset: back to initial values, clear errors, array rows back to their initial length (no events). |