Skip to content

Questionnaire Multi-step Form ​

A step-driven form flow orchestrator: step header + progress ("Step {current} of {total}") + per-step content panels + per-step validation gating. Ideal for wizards, surveys, and multi-step checkout. Validation reuses the oas-form kernel — place one <oas-form> inside each step panel; moving forward validates the current step and blocks on failure, while going back never validates and panels stay mounted (filled values are preserved).

Scope: linear gating + optional-step skip + host-defined jumps via oas-before-change + two conditional-branching channels (declarative steps[].when / goto, evaluated by the same restricted expression engine as oas-schema-form; host composition hidden bit + oas-values-change). The channels are orthogonal — an explicit host hidden always wins. Start/complete pages are not built in; implement draft persistence yourself via current + getValues().

Basic usage ​

Pass a steps array ({ key?, title, description?, optional?, hidden? }) and attach per-step content via named slots: slot="step-<key>" for keyed steps, slot="step-<index>" otherwise. The primary button becomes "Submit" on the last step; clicking it re-validates every participating step, then emits oas-submit (detail.values merged across steps). Values and validation share one scope — only participating steps (not hidden, not skipped) count; hosts needing the full data can read the inner oas-form of each panel directly.

Basic multi-step questionnaire

AlipayWeChat Pay

Click "Submit" when everything looks good.

Per-step validation gating ​

Before advancing, the current step's oas-form is validated (via its validate()); failure blocks navigation and emits oas-step-validate (detail: { index, key?, valid, errors }). Going back never validates. Set validation="false" for pure navigation.

Step content only needs an element that implements the getValues() / validate() contract (duck-typed) — not necessarily oas-form. Any compound form exposing the same contract works, such as oas-schema-form, so the whole questionnaire can be JSON-driven. See SchemaForm · Composing with Questionnaire.

Blocked until valid

You can only reach this step after validation passes.

Optional steps (skip) ​

A step with optional: true shows a "Skip this step" button: skipping bypasses validation and advances directly, emitting oas-skip (detail: { index, key? }). A skipped step leaves the participating set — its values drop out of getValues() / oas-submit and it no longer takes part in submit re-validation; revisiting the step (back / header click / goto()) restores participation, and reset() clears all skip records.

Optional step (Skip)

Final step.

Host interception (oas-before-change) ​

Before any jump (buttons / header clicks / next() / prev() / goto() / skip) a cancelable oas-before-change fires (detail: { index, key?, from }); calling preventDefault() vetoes the jump — also the hook for custom branch navigation. With linear="false", every header step becomes clickable.

preventDefault veto

Step 1 content

Step 2 content

Confirm page (blocked by the host in this demo)

Conditional branching (skip by answer) ​

Conditional branching has two orthogonal channels:

  1. Declarative (recommended): put a when expression on a steps entry — a failing condition hides the step automatically (see "Declarative conditions & jumps" below).
  2. Host composition: listen for oas-values-change to read the answer, then rewrite steps to flip the hidden bit. Hidden steps leave the header and progress, next() skips them automatically, and their values drop out of the values/validation scope. If the flipped step is the one the user is on, the component aligns current to the nearest visible step and emits oas-change (no manual jump needed). Use this channel when branch rules are very complex or decided by another system: rules stay testable and can be vetoed in oas-before-change.

The two channels are orthogonal: hidden: true always hides (host wins), and conditions only decide steps the host has not explicitly hidden.

The demo below deliberately turns the engine off with conditions="false" while the "Invoice details" step still carries a when: since the engine is off, that condition does nothing (the step always shows) and branching is driven purely by the host's hidden bit — the "host controls all branching" recipe. Remove the conditions attribute and answer again to compare both channels.

Hide/restore steps by answer (host composition, engine off)

Invoice neededNo invoice

Final step.

Declarative conditions & jumps (when / goto) ​

A steps entry can carry a condition expression, evaluated by the restricted expression engine shared with oas-schema-form (same frozen grammar: {field.path} values, == != > >= < <=, && || !, in / contains() plus the text and math function set; zero third-party dependencies):

  • when: a failing condition hides the step (header item, progress total, navigation, values and validation all follow the hidden scope, and next() skips it). Expressions read the cross-step merged answers (including hidden steps — panels stay mounted and keep their values); answer changes recompute only the conditions whose dependency paths are hit, so unrelated fields do not trigger a full re-render.
  • goto: jump on advance — { when, target } where target is a 0-based index or a step key, or the bare target shorthand (condition always true). When a hit actually moves the flow (not vetoed by oas-before-change), oas-goto is emitted (detail: { index, key?, from, target }); the jump still runs per-step validation and oas-before-change (vetoable). If the target is hidden by its own condition, the jump lands on the nearest visible step after it.
  • conditions="false": disables the engine — when / goto stop working and only the host hidden bit counts.
  • Orthogonality: hidden: true always hides (host wins); hidden: false / omitted lets when decide.
  • Fault tolerance: syntax errors / unknown functions produce one devWarn and downgrade that single clause (when no longer applies = step stays visible, goto does not jump); other steps are unaffected. If the host rewrites current / answers inside oas-change and forms a synchronous loop, the cascade is cut off after 8 rounds with a warning (no infinite loop).

Values coming from an embedded oas-schema-form drive when too — step content only needs the duck-typed contract (getValues() / validate() + oas-values-change).

when + goto (switch the answer and watch step count and jump)

Add warrantyNo warranty (Next jumps to Done)1 year2 years3 years

Invoice details (optional — Next jumps to Done).

Done.

Score aggregation (score-rules) ​

score-rules takes a rule list [{ when, score }]: whenever a condition holds, its score is added to the total. This is the only shape — a "field → per-option score" map is equivalent to several { when: "{field} == \"option\"", score: n } rules, so no second syntax exists.

  • Read-only property score: reading it sums the current cross-step answers (hidden steps included — panels stay mounted and keep their values); it is always up to date.
  • Event oas-score: emitted after answers change (detail: { score }), debounced by 80 ms so a burst of answers coalesces into one event; no event when the total did not change; changing score-rules stays silent (read the property yourself after rewriting rules).
  • The engine only computes, never renders: score display and question composition (oas-rate / oas-slider / option groups, etc.) stay in the host; no question type is built in.
  • Invalid rules (non-object / non-string when / non-numeric score / syntax errors) are skipped one by one with one devWarn each and never invalidate the other rules; an expression that throws (host function) counts as a non-matching rule.

Score aggregation (answer, then read the total and oas-score)

Very satisfiedSatisfiedNot satisfiedWould recommendNot now

Click "Done" to see the aggregated score.

Read score

Step transition (animated) ​

animated enables the step transition: the incoming panel slides in along the navigation direction (forward from the inline-end side, backward from the inline-start side) while fading in — transform/opacity only, compositor-friendly; users with prefers-reduced-motion: reduce automatically get no animation. Override the duration via the CSS variable --oas-questionnaire-anim-duration (defaults to --oas-transition-base); the slide direction mirrors automatically in RTL layouts.

animated transition (click Next/Previous to watch the slide direction)

Click "Next": this panel slides in along the navigation direction.

Forward and backward slide from opposite sides; use "Previous" to watch the return.

Final step.

reset()

Keyboard shortcuts ​

shortcuts enables keyboard step navigation: Alt+←/→ works anywhere inside the component (including inside inputs) and swallows the default action (preventing browser history navigation); bare ←/→ (no modifiers) only switches steps when focus is not inside an input/textarea/editable region (never hijacks the caret or control-specific keyboard handling) — clicking panel whitespace focuses the component container, where bare arrows also work. Triggers reuse the same gating chain as the buttons (a failing current step blocks advance); physical mapping (→ forward / ← back), not mirrored in RTL, matching the browser history-key convention.

shortcuts (click into the component, then try Alt+←/→)

With focus on panel whitespace, bare ←/→ also switch steps.

Final step.

Controlled current & methods ​

current is two-way: internal jumps write it back, external updates sync instantly. Imperative methods next() / prev() / goto(index) / validate() / submit() / getValues() / reset() cover all navigation and value scenarios.

Event naming note: events from fields inside step panels (oas-change / oas-input, etc.) bubble out through the questionnaire. A field's oas-change shares the name with the step-change oas-change — when listening for step changes, filter by detail.index (field events carry no index); for field value changes prefer oas-values-change (detail: { name, value, values }).

External control & values

prev()next()goto(2)validate()getValues()reset()

Progress variants ​

progress-variant: both (default, text + bar) / text / bar; progress="false" hides the region. The bar uses role="progressbar" + aria-valuenow/min/max for screen readers.

progress-variant & hidden

both (default)

Text + bar

C

text

Progress text only

C

bar

Progress bar only

C

Value retention & reset ​

Panels stay mounted (only hidden toggles): going forward then back keeps filled values. reset() restores every step to its initial values, clears errors, returns to step 0, and dispatches no events.

Values kept on back + reset()

Click "Previous" — your edit is still there.

reset()

Custom navigation (hide-header / hide-nav) ​

hide-header / hide-nav hide the built-in step header / nav region so the host can fully compose its own (progress and panels are still driven by the component).

hide-nav + external buttons

Built-in nav hidden

Driven by external buttons

PreviousNext

Pure navigation (validation / progress / hide-header) ​

validation="false" disables per-step gating (pure navigation — empty required fields still pass); progress="false" hides the progress region; hide-header hides the built-in step header. Each is independent, and they can be combined into a minimal flow (only panels and nav buttons remain).

Pure navigation: no gating / no progress / no header

You reach this step even with the field empty (gating is off).

API ​

oas-questionnaire ​

Attributes ​

AttributeDescriptionTypeDefault
animatedStep transition (opt-in, on when present and not "false"): the incoming panel slides in along the navigation direction while fading in (transform/opacity only); automatically disabled for prefers-reduced-motion: reduce; slide direction mirrors in RTLboolean—
conditionsStep condition engine switch (on by default; conditions="false" disables it): turning it off makes steps[].when / steps[].goto inert, leaving only the host hidden bitstringtrue
currentCurrent step index (0-based, two-way: internal jumps write back, external updates sync instantly); invalid values fall back to 0, out-of-range clampedstring0
finish-textLast-step primary button label (overrides the locale default "Submit")——
hide-headerHide the built-in step header (host composition)boolean—
hide-navHide the built-in nav region (host composition)boolean—
linearLinear mode (on by default, linear="false" disables): future steps are not clickable in the header; when disabled, any step is clickable (still intercepted by oas-before-change)stringtrue
next-text"Next" button label (overrides the locale default)——
prev-text"Previous" button label (overrides the locale default)——
progressProgress region visibility (progress="false" hides it)stringtrue
progress-variantProgress variant: both (default, text + bar) / text / bar; invalid values fall back to bothstringboth
score-rulesScoring rules JSON array [{ when, score }]: each matching condition adds its score to the total (expressions read the cross-step merged answers, hidden steps included); invalid rules are skipped one by one with a warning. Computes only — the host composes the question typesstring—
shortcutsKeyboard step navigation (opt-in, on when present and not "false"): Alt+←/→ switches steps anywhere inside the component (swallows the default to prevent browser history navigation); bare ←/→ only when focus is outside inputs/editable controls (never hijacks the caret)boolean—
sizeSize tier: xs/small/medium/large/xl (title font density; invalid values fall back to medium with a one-time warning (deduped by identical value))stringmedium
skip-text"Skip this step" button label (overrides the locale default)——
stepsStep data JSON [{ key?, title, description?, optional?, hidden? }]; invalid/empty falls back to []QuestionnaireStep[] | string[]
validationPer-step validation gating (on by default, validation="false" for pure navigation; submit() always re-validates regardless)stringtrue

Property (JS property; see each row for attribute reflection) ​

PropertyDescriptionTypeDefault
scoreCurrent total (read-only): reading it sums score-rules against the current cross-step answers (hidden steps included — panels stay mounted and keep their values), always up to date; the engine computes onlynumber—

Methods ​

MethodSignatureDescription
nextnext(): Promise<boolean>Next step: gated by single-step validation (blocked while the current step's oas-form has not passed; allowed with no form / validation="false")
prevprev(): booleanPrevious step: no validation (following the convention that going back is never blocked by validation)
gotogoto(index: number): booleanJump directly to any step: skips single-step gating (separate from next() semantics); out-of-range values are clamped and hidden steps are resolved backwards
skipStepskipStep(): booleanSkip the current optional step: advances without validation (before-change can still intercept)
validatevalidate(): Promise<boolean>Validate all participating steps (not hidden and not skipped; does not submit): dispatches oas-step-validate per step and returns whether all passed
submitsubmit(): Promise<boolean>Submit: re-validates all participating steps (including earlier ones) and dispatches oas-submit{values} only when everything passes (cross-step aggregation, participating steps only)
getValuesgetValues(): Record<string, unknown>Cross-step value aggregation (participating steps only, same criteria as validateAll): the values of each participating step (not hidden and not skipped)
resetreset(): voidReset: every step's form resets to its initial values (clearing error state), value tracking and skip records are cleared, and current returns to 0

Events ​

EventDescription
oas-before-changeFires before any jump (buttons / header clicks / next / prev / goto / skip), cancelable; detail: { index, key?, from } — preventDefault() vetoes the jump
oas-changeAfter a successful step switch; detail: { index, key? }
oas-gotoFired after a steps[].goto condition hits and the move actually happens (not vetoed by oas-before-change); detail: { index, key?, from, target } (target is the raw reference declared on the step)
oas-scoreFired after the score is recomputed (debounced 80ms after answer changes; no event when the total is unchanged); detail: { score }. Rule changes stay silent — read the read-only score property afterwards
oas-skipWhen an optional step is skipped; detail: { index, key? } (skipping never validates; the skipped step leaves the values/validation scope until revisited)
oas-step-validateAfter a per-step validation; detail: { index, key?, valid, errors }
oas-submitFinished on the last step (all participating steps validated); detail: { values } (merged across participating steps only — hidden / skipped steps excluded)
oas-values-changeNatural bubble-through of the inner oas-form value changes (detail: { name, value, values }, values is that step's snapshot); use getValues() for the merged view

Slots ​

NameDescription
step-<index>Step content panel (unkeyed steps associate by array index)
step-<key>Step content panel (keyed steps); place one <oas-form> inside to carry the step's fields and rules

CSS Variables ​

CSS VariableDescriptionDefault
--oas-questionnaire-anim-durationStep transition duration (applies when animated is on)var(--oas-transition-base, 180ms)
--oas-questionnaire-nav-gapNav region button gapvar(--oas-space-2)
--oas-questionnaire-progress-bar-bgProgress fill colorvar(--oas-color-primary)
--oas-questionnaire-progress-bgProgress track backgroundvar(--oas-color-bg-hover)

Released under the MIT OR Apache-2.0 License.