# Questionnaire

A multi-step questionnaire with single-choice, multiple-choice, freeform, and skippable questions.

Source: https://webjs.dev/ui/docs/components/questionnaire

```ts
import { html } from '@webjsdev/core';

export default function QuestionnaireDemo() {
  return html`
    <ui-questionnaire class="mx-auto max-w-md" shortcuts="letters">
      <ui-questionnaire-progress></ui-questionnaire-progress>

      <ui-questionnaire-item name="direction" required>
        <ui-questionnaire-title>
          What should the agent build next?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose a direction or describe another task.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="tool-calls">
            <span class="font-medium">Tool call timeline</span>
            <span class="text-muted-foreground">
              Show what the agent ran and what came back.
            </span>
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="approvals">
            <span class="font-medium">Approval checkpoints</span>
            <span class="text-muted-foreground">
              Ask before sensitive or destructive actions.
            </span>
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="handoffs">
            <span class="font-medium">Sub-agent handoffs</span>
            <span class="text-muted-foreground">
              Make delegated work and results easier to follow.
            </span>
          </ui-questionnaire-choice>
          <ui-questionnaire-input
            aria-label="Another agent feature"
            placeholder="Describe another feature…"
          ></ui-questionnaire-input>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="signals" multiple>
        <ui-questionnaire-title>
          What should every progress update include?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Select all that apply, or skip this question.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="progress">Progress</ui-questionnaire-choice>
          <ui-questionnaire-choice value="decisions">Decisions</ui-questionnaire-choice>
          <ui-questionnaire-choice value="risks">Risks</ui-questionnaire-choice>
          <ui-questionnaire-choice value="next-step">Next step</ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="timing" required>
        <ui-questionnaire-title>When should work begin?</ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose when the agent should begin the work.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="now">Start now</ui-questionnaire-choice>
          <ui-questionnaire-choice value="next-cycle">
            Next development cycle
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="backlog">
            Add it to the backlog
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-skip></ui-questionnaire-skip>
        <ui-questionnaire-next>Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Save plan</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Installation

```bash
npx @webjsdev/ui add questionnaire
```

### Copy and paste the following code into your project.

````ts title="components/ui/questionnaire.ts"
/**
 * Questionnaire: a multi-step flow of questions over real form controls.
 * Tier-2. It is shadcn's Questionnaire (the headless primitive in
 * `@shadcn/react`, styled), built on a native `<form>`: each question is a
 * `<fieldset>`, each answer a real radio, checkbox or text input, and the
 * answers are read with `FormData` like any form.
 *
 * Without JavaScript every question shows at once and Submit posts the form,
 * with the browser's own `required` check. With JavaScript one question shows
 * at a time: Next validates it, Previous goes back, Skip leaves an optional
 * question unanswered, and Submit appears on the last one.
 *
 * shadcn parity:
 *   Questionnaire (shortcuts) → <ui-questionnaire shortcuts="letters" | "numbers" action method>
 *   Questionnaire item / defaultItem
 *                             → the `item` property and attribute (the active question,
 *                               settable from outside) / `default-item`
 *   Questionnaire render={<form action={…} />}
 *                             → <ui-questionnaire as-child> around your own <form>
 *   QuestionnaireProgress     → <ui-questionnaire-progress> ("Question 1 of 3")
 *   QuestionnaireItem (name, required, multiple, disabled)
 *                             → <ui-questionnaire-item name required multiple disabled>
 *   QuestionnaireTitle / Description
 *                             → <ui-questionnaire-title> / <ui-questionnaire-description>
 *   QuestionnaireChoices      → <ui-questionnaire-choices>
 *   QuestionnaireChoice value → <ui-questionnaire-choice value checked>
 *   QuestionnaireChoiceDescription
 *                             → <ui-questionnaire-choice-description>
 *   QuestionnaireInput        → <ui-questionnaire-input placeholder aria-label> (a freeform answer)
 *   QuestionnaireError        → <ui-questionnaire-error> (a default message when empty)
 *   QuestionnaireActions / Previous / Skip / Next / Submit (disabled)
 *                             → <ui-questionnaire-actions> / -previous / -skip / -next / -submit
 *                               (`variant` and `size` as on a button, and `disabled`)
 *   onActiveItemChange        → `ui-active-change` ({ detail: { name } })
 *
 * A question's answers share its `name`, so `FormData.get(name)` reads a
 * single answer and `getAll(name)` a `multiple` one. Typing a freeform answer
 * clears a single question's choices, and picking a choice clears the text.
 * A `disabled` question is left out of the flow (a conditional question).
 *
 * The active question is the `item` property (and attribute): set it from
 * outside to go to that question, and it follows the reader's own steps.
 * `default-item` names the question the flow opens on. A navigation button
 * written `disabled` cannot be pressed, and a disabled Next or Submit also
 * stops Enter from stepping on, as in shadcn.
 *
 * To bind a `'use server'` action, write the form yourself, the way a page
 * binds any action, and mark the questionnaire `as-child`:
 * `<ui-questionnaire as-child><form action=${saveAnswers} data-slot="questionnaire"
 * class=${questionnaireClass()}> ...questions and actions... </form></ui-questionnaire>`.
 * The element then renders no form of its own and drives yours, so the page's
 * binding (its hidden action field, `method="post"`) is served and kept, and
 * the form posts with JavaScript off. Without `as-child` the element renders
 * the form, with your `action` and `method` attributes as plain strings.
 *
 * Keyboard: Enter goes to the next question, and on the last one submits.
 * With `shortcuts`, a letter (A, B, C) or a number (1, 2, 3) picks the
 * matching answer, except while typing in a text field.
 *
 * A11y (handled by the element): each question is a `<fieldset>` named by its
 * title and described by its description, the progress is a
 * `role="progressbar"` with its value, a question left unanswered is marked
 * `aria-invalid` and its error announced with `role="alert"`, and a question
 * not on screen is `hidden` and `inert`.
 *
 * @example
 * ```html
 * <ui-questionnaire shortcuts="letters">
 *   <ui-questionnaire-progress></ui-questionnaire-progress>
 *   <ui-questionnaire-item name="direction" required>
 *     <ui-questionnaire-title>What should we prototype next?</ui-questionnaire-title>
 *     <ui-questionnaire-description>Choose a direction or write your own.</ui-questionnaire-description>
 *     <ui-questionnaire-choices>
 *       <ui-questionnaire-choice value="delegation">Delegation</ui-questionnaire-choice>
 *       <ui-questionnaire-choice value="questions">Question prompts</ui-questionnaire-choice>
 *       <ui-questionnaire-input aria-label="Another answer" placeholder="Type another answer"></ui-questionnaire-input>
 *     </ui-questionnaire-choices>
 *     <ui-questionnaire-error></ui-questionnaire-error>
 *   </ui-questionnaire-item>
 *   <ui-questionnaire-item name="detail">
 *     <ui-questionnaire-title>How much detail?</ui-questionnaire-title>
 *     <ui-questionnaire-choices>
 *       <ui-questionnaire-choice value="focused">Focused</ui-questionnaire-choice>
 *       <ui-questionnaire-choice value="complete">Complete flow</ui-questionnaire-choice>
 *     </ui-questionnaire-choices>
 *   </ui-questionnaire-item>
 *   <ui-questionnaire-actions>
 *     <ui-questionnaire-previous></ui-questionnaire-previous>
 *     <ui-questionnaire-skip></ui-questionnaire-skip>
 *     <ui-questionnaire-next></ui-questionnaire-next>
 *     <ui-questionnaire-submit></ui-questionnaire-submit>
 *   </ui-questionnaire-actions>
 * </ui-questionnaire>
 * ```
 */
import { WebComponent, html, prop, signal, nothing } from '@webjsdev/core';
import { cn, takeAuthoredClass } from '../lib/utils.ts';
import { buttonClass, type ButtonVariant, type ButtonSize } from './button.ts';

/** The form's classes (the element applies them). */
export const questionnaireClass = (): string => 'gap-4 flex w-full min-w-0 flex-col';
/** The progress line (the element applies them). */
export const questionnaireProgressClass = (): string =>
  'text-xs min-h-[1lh] w-fit min-w-[14ch] font-medium text-muted-foreground tabular-nums';
/** A question's fieldset (the element applies them). */
export const questionnaireItemClass = (): string => 'flex flex-col gap-4 min-w-0 border-0 p-0 outline-none';
/** A question's title (the element applies them). */
// The styles space the title from what follows only when no description is its
// following sibling. Here the title and the description sit in their own part
// hosts, so they are never siblings, and the question is asked of the item
// instead: an item holding a description takes the margin back.
export const questionnaireTitleClass = (): string =>
  'text-base leading-snug font-medium cn-font-heading text-pretty [[data-slot=questionnaire-item]:has([data-slot=questionnaire-description])_&]:mb-0';
/** A question's description (the element applies them). */
export const questionnaireDescriptionClass = (): string =>
  'text-sm text-muted-foreground text-pretty';
/** The answers' box (the element applies them). */
export const questionnaireChoicesClass = (): string =>
  'gap-2 group/questionnaire-choices grid min-w-0';
/** One answer (the element applies them). */
export const questionnaireChoiceClass = (): string =>
  'gap-2.5 rounded-md border border-input bg-transparent px-3 py-2.5 text-sm shadow-xs hover:bg-muted/50 data-[checked]:border-primary/40 data-[checked]:bg-muted has-[>input:focus-visible]:border-ring has-[>input:focus-visible]:ring-[3px] has-[>input:focus-visible]:ring-ring/50 dark:bg-input/20 dark:data-[checked]:bg-muted group/questionnaire-choice relative flex min-h-11 cursor-pointer items-start text-start transition-colors outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50';
/** An answer's description line. */
export const questionnaireChoiceDescriptionClass = (): string => 'text-muted-foreground';
/** The freeform answer (the element applies them). */
export const questionnaireInputClass = (): string =>
  'h-9 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 min-h-11 w-full min-w-0 transition-[color,box-shadow,background-color] outline-none disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-0 selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground';
/** The error line (the element applies them). */
export const questionnaireErrorClass = (): string => 'mt-2 text-sm text-destructive';
/** The actions row (the element applies them). */
export const questionnaireActionsClass = (): string =>
  'gap-2 sm:min-h-9 grid min-h-11 w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center';

const ROOT = 'ui-questionnaire';
const ITEM = 'ui-questionnaire-item';
let uid = 0;

function rootOf(el: Element): UiQuestionnaire | null {
  return (typeof el.closest === 'function' ? el.closest(ROOT) : null) as UiQuestionnaire | null;
}

function itemOf(el: Element): UiQuestionnaireItem | null {
  return (typeof el.closest === 'function' ? el.closest(ITEM) : null) as UiQuestionnaireItem | null;
}

// shadcn's className on each questionnaire part lands on the element that part
// renders, and no host draws a box of its own: the rendered elements are the
// flex and grid items the styles space (a hidden question's fieldset drops out
// of the form's gap, a button's column placement reaches the actions grid).
// No host hides itself, since every part hides its rendered element. The
// host's box is turned off through its style, which the server serves, unlike
// a class the element changes.
function takeAuthored(part: HTMLElement): string | null {
  if (!part.getAttribute?.('style')) part.setAttribute?.('style', 'display: contents');
  return takeAuthoredClass(part, null);
}

// A part connected after the root's first update asks it to push its state.
function announce(el: Element): void {
  const root = rootOf(el);
  if (root) root._partConnected();
}

function isTextEntry(target: EventTarget | null): boolean {
  const el = target as HTMLElement | null;
  if (!el || typeof el.matches !== 'function') return false;
  return el.matches('textarea, input:not([type=radio]):not([type=checkbox]):not([type=button]):not([type=submit])');
}

// --------------------------------------------------------------------------
// <ui-questionnaire>
// --------------------------------------------------------------------------

export class UiQuestionnaire extends WebComponent({
  action: String,
  method: String,
  shortcuts: prop<'' | 'letters' | 'numbers'>(String),
  // The active question, by name: set it to go there.
  item: String,
  // The question the flow opens on.
  defaultItem: prop(String, { attribute: 'default-item' }),
  // Drive the author's own <form> instead of rendering one.
  asChild: prop(Boolean, { attribute: 'as-child' }),
}) {
  readonly #enhanced = signal(false);
  readonly #active = signal('');
  _queued = false;

  constructor() {
    super();
    this.action = '';
    this.method = '';
    this.shortcuts = '';
    this.item = '';
    this.defaultItem = '';
    this.asChild = false;
  }

  // The listeners sit on the host, which every event from the form reaches,
  // so they serve the element's own form and an author's `as-child` one alike.
  connectedCallback(): void {
    super.connectedCallback?.();
    this.addEventListener('submit', this._onSubmit);
    this.addEventListener('keydown', this._onKeyDown);
    this.addEventListener('change', this._onChange);
    this.addEventListener('input', this._onChange);
    this._partConnected();
  }

  disconnectedCallback(): void {
    this.removeEventListener('submit', this._onSubmit);
    this.removeEventListener('keydown', this._onKeyDown);
    this.removeEventListener('change', this._onChange);
    this.removeEventListener('input', this._onChange);
    super.disconnectedCallback?.();
  }

  render() {
    if (this.asChild) {
      // The author's form is the questionnaire; this host only drives it.
      if (typeof this.getAttribute === 'function' && !this.getAttribute('style')) this.setAttribute('style', 'display: contents');
      return html`<slot></slot>`;
    }
    return html`<form
      data-slot="questionnaire"
      action=${this.action || nothing}
      method=${this.method || nothing}
      ?novalidate=${this.#enhanced.get()}
      data-shortcuts=${this.shortcuts || nothing}
      class=${cn(questionnaireClass(), takeAuthored(this))}
    ><slot></slot></form>`;
  }

  /** The form the questionnaire runs on: its own, or the author's under `as-child`. */
  form(): HTMLFormElement | null {
    if (typeof this.querySelector !== 'function') return null;
    return this.querySelector('form');
  }

  willUpdate(changedProperties: Map<string, unknown>): void {
    super.willUpdate?.(changedProperties);
    // The active question set from outside: go there, with no validation, as
    // a controlled shadcn Questionnaire does.
    if (changedProperties.has('item') && this.#enhanced.get() && this.item && this.item !== this.#active.get()) {
      const target = this.items().find((i) => i.name === this.item);
      if (target) queueMicrotask(() => this._go(target, { focus: false }));
    }
  }

  _partConnected(): void {
    if (this._queued) return;
    this._queued = true;
    queueMicrotask(() => {
      this._queued = false;
      this._enhance();
      this.sync();
    });
  }

  _enhance(): void {
    if (this.#enhanced.get()) return;
    const items = this.items();
    const wanted = this.item || this.defaultItem;
    const first = items.find((i) => i.name === wanted) ?? items[0];
    if (!first) return;
    this.#active.set(first.name);
    this.item = first.name;
    this.#enhanced.set(true);
    // An author's form validates per question from here, as the element's own does.
    if (this.asChild) {
      const form = this.form();
      if (form) {
        form.noValidate = true;
        if (this.shortcuts) form.setAttribute('data-shortcuts', this.shortcuts);
      }
    }
  }

  /** The questions in the flow, in order: every one not `disabled`. */
  items(): UiQuestionnaireItem[] {
    if (typeof this.querySelectorAll !== 'function') return [];
    return Array.from(this.querySelectorAll<UiQuestionnaireItem>(ITEM)).filter((i) => rootOf(i) === this && !i.disabled);
  }

  _activeItem(): UiQuestionnaireItem | null {
    const items = this.items();
    return items.find((i) => i.name === this.#active.get()) ?? items[0] ?? null;
  }

  /** Whether a question has an answer: a checked choice or a filled text field. */
  answered(item: UiQuestionnaireItem): boolean {
    return item.inputs().some((i) => (i.type === 'radio' || i.type === 'checkbox' ? i.checked : i.value.trim() !== ''));
  }

  /** Push the active question, its neighbours and every answer into the parts. */
  sync(): void {
    const items = this.items();
    const item = this._activeItem();
    const at = item ? items.indexOf(item) : -1;
    const last = at === items.length - 1;
    for (const i of this._all(ITEM) as UiQuestionnaireItem[]) {
      i.flow?.set({ enhanced: this.#enhanced.get(), active: i === item });
    }
    for (const c of this._all('ui-questionnaire-choice') as UiQuestionnaireChoice[]) c._syncChecked();
    for (const p of this._all('ui-questionnaire-progress') as UiQuestionnaireProgress[]) {
      p.progress?.set({ current: at + 1, total: items.length });
    }
    const show = (tag: string, visible: boolean) => {
      for (const b of this._all(tag) as UiQuestionnaireButton[]) b.visible?.set(visible);
    };
    if (!this.#enhanced.get()) {
      show('ui-questionnaire-previous', false);
      show('ui-questionnaire-skip', false);
      show('ui-questionnaire-next', false);
      show('ui-questionnaire-submit', true);
      return;
    }
    show('ui-questionnaire-previous', at > 0);
    show('ui-questionnaire-skip', !!item && !item.required);
    show('ui-questionnaire-next', items.length > 1 && !last);
    show('ui-questionnaire-submit', items.length > 0 && last);
  }

  _all(tag: string): Element[] {
    if (typeof this.querySelectorAll !== 'function') return [];
    return Array.from(this.querySelectorAll(tag)).filter((el) => rootOf(el) === this);
  }

  _go(item: UiQuestionnaireItem | undefined, opts: { focus?: boolean } = {}): void {
    if (!item) return;
    if (item.name !== this.#active.get()) {
      this.#active.set(item.name);
      this.item = item.name;
      this.dispatchEvent(new CustomEvent('ui-active-change', { bubbles: true, detail: { name: item.name } }));
    }
    this.sync();
    // Focus the new question's first answer once it is shown.
    if (opts.focus === false) return;
    this.updateComplete.then(() => requestAnimationFrame(() => item.inputs().find((i) => !i.disabled)?.focus()));
  }

  // Whether every button of a kind is written `disabled` (and there is one).
  _allDisabled(tag: string): boolean {
    const buttons = this._all(tag) as UiQuestionnaireButton[];
    return buttons.length > 0 && buttons.every((b) => b.disabled);
  }

  /** Check the active question; mark it and return false when it needs an answer. */
  validate(item = this._activeItem()): boolean {
    if (!item) return true;
    const ok = !item.required || this.answered(item);
    item.invalid?.set(!ok);
    if (!ok) item.inputs().find((i) => !i.disabled)?.focus();
    return ok;
  }

  /** Go to the next question, if the active one is answered or optional. */
  next(): void {
    const items = this.items();
    const item = this._activeItem();
    if (!item || !this.validate(item)) return;
    this._go(items[items.indexOf(item) + 1]);
  }

  /** Go back one question. */
  previous(): void {
    const items = this.items();
    const item = this._activeItem();
    if (!item) return;
    this._go(items[items.indexOf(item) - 1]);
  }

  /** Leave an optional question unanswered and go on. */
  skip(): void {
    const item = this._activeItem();
    if (!item || item.required) return;
    for (const i of item.inputs()) {
      if (i.type === 'radio' || i.type === 'checkbox') i.checked = false;
      else i.value = '';
    }
    item.invalid?.set(false);
    const items = this.items();
    const after = items[items.indexOf(item) + 1];
    if (after) this._go(after);
    else this.sync();
  }

  // Enter in the form, and the Submit button, both arrive here.
  _onSubmit = (e: Event): void => {
    if (!this.#enhanced.get() || (e.target as Element | null)?.closest?.(ROOT) !== this) return;
    const items = this.items();
    const item = this._activeItem();
    if (item && items.indexOf(item) < items.length - 1) {
      e.preventDefault();
      // Enter steps on only while Next can be pressed.
      if (!this._allDisabled('ui-questionnaire-next')) this.next();
      return;
    }
    // On the last question every required one must be answered.
    const missing = items.find((i) => i.required && !this.answered(i));
    if (missing) {
      e.preventDefault();
      if (missing !== item) this._go(missing);
      this.validate(missing);
    }
  };

  _onKeyDown = (e: KeyboardEvent): void => {
    if (!this.#enhanced.get() || !this.shortcuts || rootOf(e.target as Element) !== this || e.metaKey || e.ctrlKey || e.altKey || isTextEntry(e.target)) return;
    const item = this._activeItem();
    if (!item) return;
    const choices = item.choices();
    const k = e.key.toLowerCase();
    const index = this.shortcuts === 'numbers' ? Number(k) - 1 : k.length === 1 ? k.charCodeAt(0) - 97 : -1;
    const choice = Number.isInteger(index) && index >= 0 ? choices[index] : undefined;
    const input = choice?.input();
    if (!input || input.disabled) return;
    e.preventDefault();
    input.checked = input.type === 'checkbox' ? !input.checked : true;
    input.dispatchEvent(new Event('change', { bubbles: true }));
  };

  // A pick or a keystroke: keep a single question's choices and text apart,
  // clear its error once it is answered, and redraw.
  _onChange = (e: Event): void => {
    const target = e.target as HTMLInputElement;
    const item = itemOf(target);
    if (!item || rootOf(item) !== this) return;
    if (!item.multiple) {
      if (target.matches?.('[data-slot="questionnaire-input"]') && target.value.trim()) {
        for (const i of item.inputs()) if (i.type === 'radio') i.checked = false;
      } else if (target.type === 'radio' && target.checked) {
        for (const i of item.inputs()) if (i.matches('[data-slot="questionnaire-input"]')) i.value = '';
      }
    }
    if (item.invalid?.get() && this.answered(item)) item.invalid?.set(false);
    this.sync();
  };
}
UiQuestionnaire.register('ui-questionnaire');

// --------------------------------------------------------------------------
// <ui-questionnaire-progress>
// --------------------------------------------------------------------------

export class UiQuestionnaireProgress extends WebComponent {
  readonly progress = signal<{ current: number; total: number }>({ current: 0, total: 0 });
  constructor() {
    super();
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    const { current, total } = this.progress.get();
    const label = total ? `Question ${current} of ${total}` : '';
    return html`<div
      data-slot="questionnaire-progress"
      role="progressbar"
      aria-label="Questionnaire progress"
      aria-live="polite"
      aria-valuemin=${total ? '1' : nothing}
      aria-valuemax=${total ? String(total) : nothing}
      aria-valuenow=${total ? String(current) : nothing}
      aria-valuetext=${label || nothing}
      class=${cn(questionnaireProgressClass(), takeAuthored(this))}
    >${label}</div>`;
  }
}
UiQuestionnaireProgress.register('ui-questionnaire-progress');

// --------------------------------------------------------------------------
// <ui-questionnaire-item>
// --------------------------------------------------------------------------

export class UiQuestionnaireItem extends WebComponent({
  name: String,
  required: Boolean,
  multiple: Boolean,
  disabled: Boolean,
}) {
  readonly flow = signal<{ enhanced: boolean; active: boolean }>({ enhanced: false, active: false });
  // The item's error line reads this signal, so it redraws when it changes.
  readonly invalid = signal(false);
  _id = '';

  constructor() {
    super();
    this.name = '';
    this.required = false;
    this.multiple = false;
    this.disabled = false;
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    this._id ||= `ui-questionnaire-item-${++uid}`;
    announce(this);
  }

  get titleId(): string {
    return `${this._id}-title`;
  }

  get descriptionId(): string {
    return `${this._id}-description`;
  }

  get errorId(): string {
    return `${this._id}-error`;
  }

  /** The question's answer controls: its choices' inputs and its text field. */
  inputs(): HTMLInputElement[] {
    if (typeof this.querySelectorAll !== 'function') return [];
    return Array.from(this.querySelectorAll<HTMLInputElement>('input[data-slot="questionnaire-choice-input"], input[data-slot="questionnaire-input"]'))
      .filter((i) => itemOf(i) === this);
  }

  /** The question's choices, in order. */
  choices(): UiQuestionnaireChoice[] {
    if (typeof this.querySelectorAll !== 'function') return [];
    return Array.from(this.querySelectorAll<UiQuestionnaireChoice>('ui-questionnaire-choice')).filter((c) => itemOf(c) === this);
  }

  /** Whether the item holds a `tag` part, or false on the server, where there is no DOM to query. */
  _has(tag: string): boolean {
    return typeof this.querySelector === 'function' && !!this.querySelector(tag);
  }

  render() {
    const flow = this.flow.get();
    const hide = flow.enhanced && !flow.active;
    const hasTitle = this._has('ui-questionnaire-title');
    const hasDescription = this._has('ui-questionnaire-description');
    const described = [hasDescription ? this.descriptionId : '', this.invalid.get() ? this.errorId : ''].filter(Boolean).join(' ');
    return html`<fieldset
      data-slot="questionnaire-item"
      ?disabled=${this.disabled}
      ?data-active=${flow.active}
      ?hidden=${hide}
      ?inert=${hide}
      aria-labelledby=${hasTitle && this._id ? this.titleId : nothing}
      aria-describedby=${described || nothing}
      aria-invalid=${this.invalid.get() ? 'true' : nothing}
      class=${cn(questionnaireItemClass(), takeAuthored(this))}
    ><slot></slot></fieldset>`;
  }
}
UiQuestionnaireItem.register('ui-questionnaire-item');

// --------------------------------------------------------------------------
// <ui-questionnaire-title> and <ui-questionnaire-description>
// --------------------------------------------------------------------------

export class UiQuestionnaireTitle extends WebComponent {
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    const item = itemOf(this);
    return html`<legend data-slot="questionnaire-title" id=${item?._id ? item.titleId : nothing} class=${cn(questionnaireTitleClass(), takeAuthored(this))}><slot></slot></legend>`;
  }
}
UiQuestionnaireTitle.register('ui-questionnaire-title');

export class UiQuestionnaireDescription extends WebComponent {
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    const item = itemOf(this);
    return html`<p data-slot="questionnaire-description" id=${item?._id ? item.descriptionId : nothing} class=${cn(questionnaireDescriptionClass(), takeAuthored(this))}><slot></slot></p>`;
  }
}
UiQuestionnaireDescription.register('ui-questionnaire-description');

// --------------------------------------------------------------------------
// <ui-questionnaire-choices>, <ui-questionnaire-choice>, -choice-description
// --------------------------------------------------------------------------

export class UiQuestionnaireChoices extends WebComponent {
  render() {
    return html`<div data-slot="questionnaire-choices" class=${cn(questionnaireChoicesClass(), takeAuthored(this))}><slot></slot></div>`;
  }
}
UiQuestionnaireChoices.register('ui-questionnaire-choices');

export class UiQuestionnaireChoice extends WebComponent({
  value: String,
  checked: Boolean,
  disabled: Boolean,
}) {
  readonly #live = signal(false);
  #seeded = false;
  constructor() {
    super();
    this.value = '';
    this.checked = false;
    this.disabled = false;
  }

  // Seed the drawn state from `checked` here, not in connectedCallback: SSR
  // runs willUpdate but never connects, and a pre-checked choice has to be
  // drawn checked in the first paint and with JavaScript off.
  willUpdate(changedProperties: Map<string, unknown>): void {
    super.willUpdate?.(changedProperties);
    if (!this.#seeded || changedProperties.has('checked')) {
      this.#seeded = true;
      this.#live.set(this.checked);
    }
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  input(): HTMLInputElement | null {
    return this.querySelector?.('input[data-slot="questionnaire-choice-input"]') ?? null;
  }

  _syncChecked(): void {
    const on = !!this.input()?.checked;
    if (on !== this.#live.get()) this.#live.set(on);
    this.requestUpdate?.();
  }

  // This choice's shortcut key, from its place in the question.
  _shortcut(): string {
    const mode = rootOf(this)?.shortcuts;
    const item = itemOf(this);
    if (!mode || !item) return '';
    const i = item.choices().indexOf(this);
    if (i < 0) return '';
    if (mode === 'numbers') return i < 9 ? String(i + 1) : '';
    return i < 26 ? String.fromCharCode(97 + i) : '';
  }

  render() {
    const item = itemOf(this);
    const type = item?.multiple ? 'checkbox' : 'radio';
    const shortcut = this._shortcut();
    const disabled = this.disabled || !!item?.disabled;
    return html`<label
      data-slot="questionnaire-choice"
      data-type=${type}
      ?data-checked=${this.#live.get()}
      ?data-unchecked=${!this.#live.get()}
      ?data-disabled=${disabled}
      data-shortcut=${shortcut || nothing}
      class=${cn(questionnaireChoiceClass(), takeAuthored(this))}
    ><input
      data-slot="questionnaire-choice-input"
      type=${type}
      name=${item?.name || nothing}
      value=${this.value}
      ?checked=${this.checked}
      ?disabled=${disabled}
      ?required=${!!item?.required && type === 'radio'}
      aria-keyshortcuts=${shortcut ? shortcut.toUpperCase() : nothing}
      class="absolute inset-0 z-10 size-full cursor-pointer opacity-0"
    ><span aria-hidden="true" data-slot="questionnaire-choice-indicator"
      class="size-4 translate-y-[--spacing(0.45)] rounded-[4px] border-input shadow-xs group-data-[checked]/questionnaire-choice:border-primary group-data-[checked]/questionnaire-choice:bg-primary group-data-[checked]/questionnaire-choice:text-primary-foreground dark:bg-input/30 pointer-events-none relative flex shrink-0 items-center justify-center border group-data-[type=radio]/questionnaire-choice:rounded-full"
    ><span data-slot="questionnaire-choice-indicator-dot"
      class="size-2 bg-primary-foreground hidden rounded-full group-data-[type=checkbox]/questionnaire-choice:hidden group-data-[checked]/questionnaire-choice:block"
    ></span><svg data-slot="questionnaire-choice-indicator-check" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
      class="size-3.5 hidden group-data-[type=radio]/questionnaire-choice:hidden group-data-[checked]/questionnaire-choice:block"
    ><path d="M20 6 9 17l-5-5"></path></svg></span><span data-slot="questionnaire-choice-label"
      class="gap-0.5 flex min-w-0 flex-1 flex-col leading-snug"
    ><slot></slot></span><span data-slot="questionnaire-choice-shortcut" aria-hidden="true" ?hidden=${!shortcut}
      class="size-5 translate-y-[--spacing(0.45)] items-center justify-center rounded-md border border-input bg-background font-mono text-[0.625rem] leading-none font-medium text-muted-foreground pointer-events-none ms-auto hidden shrink-0 group-data-[shortcut]/questionnaire-choice:inline-flex"
    >${shortcut.toUpperCase()}</span></label>`;
  }
}
UiQuestionnaireChoice.register('ui-questionnaire-choice');

export class UiQuestionnaireChoiceDescription extends WebComponent {
  render() {
    return html`<span data-slot="questionnaire-choice-description" class=${cn(questionnaireChoiceDescriptionClass(), takeAuthored(this))}><slot></slot></span>`;
  }
}
UiQuestionnaireChoiceDescription.register('ui-questionnaire-choice-description');

// --------------------------------------------------------------------------
// <ui-questionnaire-input>
// --------------------------------------------------------------------------

export class UiQuestionnaireInput extends WebComponent({
  placeholder: String,
}) {
  constructor() {
    super();
    this.placeholder = '';
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    const item = itemOf(this);
    return html`<div data-slot="questionnaire-input-wrapper" class=${cn('w-full group/questionnaire-input relative min-w-0', takeAuthored(this))}><input
      data-slot="questionnaire-input"
      type="text"
      name=${item?.name || nothing}
      placeholder=${this.placeholder || nothing}
      aria-label=${this.getAttribute?.('aria-label') || nothing}
      ?disabled=${!!item?.disabled}
      class=${questionnaireInputClass()}
    ></div>`;
  }
}
UiQuestionnaireInput.register('ui-questionnaire-input');

// --------------------------------------------------------------------------
// <ui-questionnaire-error>
// --------------------------------------------------------------------------

export class UiQuestionnaireError extends WebComponent {
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    const item = itemOf(this);
    const invalid = !!item?.invalid?.get();
    const fallback = item?.required ? 'Choose an answer to continue.' : 'Choose an answer or skip this question.';
    return html`<p
      data-slot="questionnaire-error"
      id=${item?._id ? item.errorId : nothing}
      ?hidden=${!invalid}
      role=${invalid ? 'alert' : nothing}
      class=${cn(questionnaireErrorClass(), takeAuthored(this))}
    ><slot>${fallback}</slot></p>`;
  }
}
UiQuestionnaireError.register('ui-questionnaire-error');

// --------------------------------------------------------------------------
// <ui-questionnaire-actions> and the four buttons
// --------------------------------------------------------------------------

export class UiQuestionnaireActions extends WebComponent {
  render() {
    return html`<div data-slot="questionnaire-actions" class=${cn(questionnaireActionsClass(), takeAuthored(this))}><slot></slot></div>`;
  }
}
UiQuestionnaireActions.register('ui-questionnaire-actions');

/** What the four navigation buttons share. */
export class UiQuestionnaireButton extends WebComponent({
  variant: String,
  size: String,
  // Written by the author, as shadcn's `disabled` on a navigation button.
  disabled: Boolean,
}) {
  static part = '';
  static label = '';
  static place = '';
  static submits = false;
  static defaultVariant = 'outline';

  // Submit shows from the first paint; the others wait for the flow.
  readonly visible = signal((this.constructor as typeof UiQuestionnaireButton).submits);

  constructor() {
    super();
    const ctor = this.constructor as typeof UiQuestionnaireButton;
    this.variant = ctor.defaultVariant;
    this.size = 'default';
    this.disabled = false;
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    const ctor = this.constructor as typeof UiQuestionnaireButton;
    return html`<button
      type=${ctor.submits ? 'submit' : 'button'}
      data-slot=${`questionnaire-${ctor.part}`}
      data-size=${this.size}
      data-variant=${this.variant}
      ?hidden=${!this.visible.get()}
      ?disabled=${this.disabled}
      aria-hidden=${this.visible.get() ? nothing : 'true'}
      aria-keyshortcuts=${this.visible.get() && !this.disabled && (ctor.part === 'next' || ctor.part === 'submit') ? 'Enter' : nothing}
      class=${cn(buttonClass({ variant: this.variant as ButtonVariant, size: this.size as ButtonSize }), ctor.place, takeAuthored(this))}
      @click=${this._onClick}
    ><slot>${ctor.label}</slot></button>`;
  }

  _onClick = (): void => {};
}

export class UiQuestionnairePrevious extends UiQuestionnaireButton {
  static part = 'previous';
  static label = 'Previous';
  static place = 'col-start-1 row-start-1 min-h-11 justify-self-start sm:min-h-0';
  _onClick = (): void => rootOf(this)?.previous();
}
UiQuestionnairePrevious.register('ui-questionnaire-previous');

export class UiQuestionnaireSkip extends UiQuestionnaireButton {
  static part = 'skip';
  static label = 'Skip';
  static place = 'col-start-2 row-start-1 min-h-11 justify-self-end sm:min-h-0';
  _onClick = (): void => rootOf(this)?.skip();
}
UiQuestionnaireSkip.register('ui-questionnaire-skip');

export class UiQuestionnaireNext extends UiQuestionnaireButton {
  static part = 'next';
  static label = 'Next';
  static place = 'col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0';
  static defaultVariant = 'default';
  _onClick = (): void => rootOf(this)?.next();
}
UiQuestionnaireNext.register('ui-questionnaire-next');

export class UiQuestionnaireSubmit extends UiQuestionnaireButton {
  static part = 'submit';
  static label = 'Submit';
  static place = 'col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0';
  static submits = true;
  static defaultVariant = 'default';
}
UiQuestionnaireSubmit.register('ui-questionnaire-submit');
````

### Update the import paths to match your project setup.

## Usage

The questionnaire parts are custom elements. Importing the module registers them, and the page renders them by tag.

```ts
import '#components/ui/questionnaire.ts';
```

```ts
const items = [
  {
    name: 'direction',
    required: true,
    prompt: 'What should we prototype next?',
    description: 'Choose a direction or write your own.',
    choices: [
      {
        value: 'delegation',
        label: 'Delegation',
        description: 'Show how work moves to a specialist.',
      },
      {
        value: 'questions',
        label: 'Question prompts',
        description: 'Show choices while the interface waits.',
      },
      { value: 'both', label: 'Both together' },
    ],
    input: { label: 'Another answer', placeholder: 'Type another answer…' },
  },
  {
    name: 'detail',
    required: false,
    prompt: 'How much detail should it include?',
    description: 'Skip this if you are not sure yet.',
    choices: [
      { value: 'focused', label: 'Focused' },
      { value: 'complete', label: 'Complete flow' },
    ],
  },
] as const;
```

Define the collection once and map it into the parts. The page renders every question on the server, and the element takes over the progress, the actions and the shortcuts once it loads.

```ts
html`
  <ui-questionnaire>
    <ui-questionnaire-progress></ui-questionnaire-progress>
    ${items.map((question) => html`
      <ui-questionnaire-item name=${question.name} ?required=${question.required}>
        <ui-questionnaire-title>${question.prompt}</ui-questionnaire-title>
        <ui-questionnaire-description>
          ${question.description}
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          ${question.choices.map((choice) => html`
            <ui-questionnaire-choice value=${choice.value}>
              <span class="font-medium">${choice.label}</span>
              ${'description' in choice
                ? html`<span class="text-muted-foreground">${choice.description}</span>`
                : ''}
            </ui-questionnaire-choice>
          `)}
          ${'input' in question
            ? html`<ui-questionnaire-input
                aria-label=${question.input.label}
                placeholder=${question.input.placeholder}
              ></ui-questionnaire-input>`
            : ''}
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>
    `)}
    <ui-questionnaire-actions>
      <ui-questionnaire-previous></ui-questionnaire-previous>
      <ui-questionnaire-skip></ui-questionnaire-skip>
      <ui-questionnaire-next></ui-questionnaire-next>
      <ui-questionnaire-submit></ui-questionnaire-submit>
    </ui-questionnaire-actions>
  </ui-questionnaire>
`
```

The element renders a native `<form>`, so the answers are read with `FormData`. Its own submit handler runs first and cancels a submit that is not on the last question yet, so a listener checks `defaultPrevented`.

```ts
questionnaire.addEventListener('submit', (event) => {
  if (event.defaultPrevented) return;
  event.preventDefault();
  const answers = new FormData(event.target as HTMLFormElement);
  // answers.get('direction'), answers.getAll(...) for multiple items.
});
```

## Composition

```text
ui-questionnaire
├── ui-questionnaire-progress
├── ui-questionnaire-item
│   ├── ui-questionnaire-title
│   ├── ui-questionnaire-description
│   ├── ui-questionnaire-choices
│   │   ├── ui-questionnaire-choice
│   │   └── ui-questionnaire-input
│   └── ui-questionnaire-error
└── ui-questionnaire-actions
    ├── ui-questionnaire-previous
    ├── ui-questionnaire-skip
    ├── ui-questionnaire-next
    └── ui-questionnaire-submit
```

`<ui-questionnaire>` owns the ordered items, the active item, validation, progress, and navigation. The answers live in the form controls themselves. The containing page, card, dialog, or drawer owns close and cancellation behavior, persistence, transport, and branching.

## Server Rendering

Every part renders on the server. Without JavaScript every question shows at once, Submit is the only action, and it posts the form with the browser's own `required` check: set `action` and `method` on `<ui-questionnaire>` to choose where. Once the element loads it shows one question at a time and fills in the progress and the Previous, Skip and Next buttons.

## Multiple Selection

Use `multiple` for an item that accepts more than one fixed answer. Its choices render as checkboxes, read with `FormData.getAll()`.

```ts
import { html } from '@webjsdev/core';

export default function QuestionnaireMultiple() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md" shortcuts="letters">
      <ui-questionnaire-item name="context" multiple required>
        <ui-questionnaire-title>
          What context should the agent inspect?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Select every source that may affect the implementation.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="source">
            Relevant source files
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="tests">
            Existing tests
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="docs">
            Architecture documentation
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="history">
            Recent commit history
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-submit>Share context</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Freeform Answer

Compose `<ui-questionnaire-input>` with fixed choices when the user can provide another answer. On a single-answer item, typing clears the picked choice and picking a choice clears the text.

```ts
import { html } from '@webjsdev/core';

export default function QuestionnaireFreeform() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md" shortcuts="letters">
      <ui-questionnaire-item name="approach" required>
        <ui-questionnaire-title>
          How should the agent approach this refactor?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose a strategy or write a more specific instruction.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="incremental">
            Make the smallest safe change
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="module">
            Refactor one module at a time
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="rewrite">
            Replace the implementation completely
          </ui-questionnaire-choice>
          <ui-questionnaire-input
            aria-label="Another refactoring approach"
            placeholder="Describe another approach…"
          ></ui-questionnaire-input>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-submit>Use this approach</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Explicit Skip

Add `<ui-questionnaire-skip>` when an optional item may be intentionally left unanswered. It shows only on an item without `required`, clears that item's answers, and moves on.

```ts
import { html } from '@webjsdev/core';

export default function QuestionnaireSkipExample() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <ui-questionnaire-progress></ui-questionnaire-progress>

      <ui-questionnaire-item name="task" required>
        <ui-questionnaire-title>What kind of change is this?</ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose the category that best describes the work.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="feature">New feature</ui-questionnaire-choice>
          <ui-questionnaire-choice value="fix">Bug fix</ui-questionnaire-choice>
          <ui-questionnaire-choice value="refactor">Refactor</ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="constraints">
        <ui-questionnaire-title>
          Are there any implementation constraints?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Answer if needed, or intentionally skip this question.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="no-dependencies">
            Do not add dependencies
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="no-migrations">
            Do not change the database
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="preserve-api">
            Preserve the public API
          </ui-questionnaire-choice>
          <ui-questionnaire-input
            aria-label="Another implementation constraint"
            placeholder="Describe another constraint…"
          ></ui-questionnaire-input>
        </ui-questionnaire-choices>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="review" required>
        <ui-questionnaire-title>
          How should the work be reviewed?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose the checks the agent should complete before handoff.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="tests">
            Run the test suite
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="diff">
            Review the final diff
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="both">
            Tests and diff review
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-skip></ui-questionnaire-skip>
        <ui-questionnaire-next>Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Submit brief</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Shortcuts

Assign a letter or number key to each answer with `shortcuts="letters"` or `shortcuts="numbers"`. A key picks the matching answer, except while typing in a text field. Set the attribute in the markup, since the choices read it when they render.

```ts
import { html } from '@webjsdev/core';

export default function QuestionnaireShortcuts() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md" shortcuts="letters">
      <ui-questionnaire-item name="action" required>
        <ui-questionnaire-title>
          What should the agent do next?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Use the displayed shortcut or navigate with the keyboard.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="inspect">
            Inspect the implementation
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="tests">
            Run the relevant tests
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="patch">
            Prepare the patch
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-submit>Confirm action</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Custom Validation

The element checks `required` items itself. For a rule across answers, listen for `submit`, check the `FormData` against a schema such as Zod, call `preventDefault()` when it fails, and put the message in the item's `<ui-questionnaire-error>`. The demo below runs the built-in required check.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  cardClass, cardHeaderClass, cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';

// The schema check runs in your own submit listener: read the answers with
// FormData, and when the pair is rejected, call preventDefault() and put the
// message in that question's <ui-questionnaire-error>.
export default function QuestionnaireValidation() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'w-full')}>
        <ui-questionnaire-item name="detail" required>
          <div data-slot="card-header" class=${cardHeaderClass()}>
            <ui-questionnaire-title>
              How much detail should the answer include?
            </ui-questionnaire-title>
            <ui-questionnaire-description>
              Choose the response depth.
            </ui-questionnaire-description>
            <div data-slot="card-action" class=${cardActionClass()}>
              <ui-questionnaire-progress class="min-w-0"></ui-questionnaire-progress>
            </div>
          </div>
          <div data-slot="card-content" class=${cardContentClass()}>
            <ui-questionnaire-choices>
              <ui-questionnaire-choice value="summary">
                Concise summary
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="complete">
                Complete answer
              </ui-questionnaire-choice>
            </ui-questionnaire-choices>
            <ui-questionnaire-error></ui-questionnaire-error>
          </div>
        </ui-questionnaire-item>

        <ui-questionnaire-item name="audience" required>
          <div data-slot="card-header" class=${cardHeaderClass()}>
            <ui-questionnaire-title>Who will read the answer?</ui-questionnaire-title>
            <ui-questionnaire-description>
              Public answers require complete context.
            </ui-questionnaire-description>
            <div data-slot="card-action" class=${cardActionClass()}>
              <ui-questionnaire-progress class="min-w-0"></ui-questionnaire-progress>
            </div>
          </div>
          <div data-slot="card-content" class=${cardContentClass()}>
            <ui-questionnaire-choices>
              <ui-questionnaire-choice value="team">
                My team
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="public">
                Public audience
              </ui-questionnaire-choice>
            </ui-questionnaire-choices>
            <ui-questionnaire-error></ui-questionnaire-error>
          </div>
        </ui-questionnaire-item>

        <div data-slot="card-footer" class=${cardFooterClass()}>
          <ui-questionnaire-actions class="w-full">
            <ui-questionnaire-previous></ui-questionnaire-previous>
            <ui-questionnaire-next>Next</ui-questionnaire-next>
            <ui-questionnaire-submit>Validate answers</ui-questionnaire-submit>
          </ui-questionnaire-actions>
        </div>
      </div>
    </ui-questionnaire>
  `;
}
```

## Controlled

The element owns the active item and dispatches `ui-active-change` with `{ detail: { name } }` each time it moves, so host state can follow it. Update a status line like the one in this demo from that listener.

```ts
import { html } from '@webjsdev/core';

// The questionnaire owns the active question and announces each change with
// a ui-active-change event ({ detail: { name } }). A listener that writes
// the matching label into the status line keeps the host in step.
export default function QuestionnaireControlled() {
  return html`
    <div class="relative mx-auto flex h-full w-full max-w-md flex-col">
      <p class="absolute end-0 top-0 text-sm text-muted-foreground" role="status">
        Current checkpoint: Change scope
      </p>

      <ui-questionnaire class="mt-auto">
        <ui-questionnaire-progress></ui-questionnaire-progress>

        <ui-questionnaire-item name="scope" required>
          <ui-questionnaire-title>What may the agent change?</ui-questionnaire-title>
          <ui-questionnaire-description>
            The host stores the active checkpoint while Questionnaire navigates.
          </ui-questionnaire-description>
          <ui-questionnaire-choices>
            <ui-questionnaire-choice value="component">
              Only the target component
            </ui-questionnaire-choice>
            <ui-questionnaire-choice value="tests">
              Component and related tests
            </ui-questionnaire-choice>
            <ui-questionnaire-choice value="feature">
              The complete feature area
            </ui-questionnaire-choice>
          </ui-questionnaire-choices>
          <ui-questionnaire-error></ui-questionnaire-error>
        </ui-questionnaire-item>

        <ui-questionnaire-item name="checks" required>
          <ui-questionnaire-title>
            Which verification level should it use?
          </ui-questionnaire-title>
          <ui-questionnaire-choices>
            <ui-questionnaire-choice value="targeted">
              Targeted tests
            </ui-questionnaire-choice>
            <ui-questionnaire-choice value="package">
              Package tests and typecheck
            </ui-questionnaire-choice>
            <ui-questionnaire-choice value="full">
              Full workspace verification
            </ui-questionnaire-choice>
          </ui-questionnaire-choices>
          <ui-questionnaire-error></ui-questionnaire-error>
        </ui-questionnaire-item>

        <ui-questionnaire-item name="output" required>
          <ui-questionnaire-title>
            What should the agent return when finished?
          </ui-questionnaire-title>
          <ui-questionnaire-choices>
            <ui-questionnaire-choice value="summary">
              Concise summary
            </ui-questionnaire-choice>
            <ui-questionnaire-choice value="diff">
              Summary with changed files
            </ui-questionnaire-choice>
            <ui-questionnaire-choice value="handoff">
              Detailed implementation handoff
            </ui-questionnaire-choice>
          </ui-questionnaire-choices>
          <ui-questionnaire-error></ui-questionnaire-error>
        </ui-questionnaire-item>

        <ui-questionnaire-actions>
          <ui-questionnaire-previous></ui-questionnaire-previous>
          <ui-questionnaire-next>Next</ui-questionnaire-next>
          <ui-questionnaire-submit>Save workflow</ui-questionnaire-submit>
        </ui-questionnaire-actions>
      </ui-questionnaire>
    </div>
  `;
}
```

## Resume

Restore saved answers with `checked` on the choices. The flow starts on the first item.

```ts
import { html } from '@webjsdev/core';

// The saved answers are the choices' checked attributes.
export default function QuestionnaireResume() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <ui-questionnaire-progress></ui-questionnaire-progress>

      <ui-questionnaire-item name="change" required>
        <ui-questionnaire-title>What kind of migration is this?</ui-questionnaire-title>
        <ui-questionnaire-description>
          This answer was saved during the previous session.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="incremental" checked>
            Incremental migration
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="cutover">
            Single cutover
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="verification" multiple required>
        <ui-questionnaire-title>
          How should the migration be verified?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          These checks were selected during the previous session.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="tests" checked>
            Run migration tests
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="typecheck" checked>
            Run the typecheck
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="manual">
            Perform a manual smoke test
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="notes">
        <ui-questionnaire-title>
          Anything else the agent should remember?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          This note was saved with the draft.
        </ui-questionnaire-description>
        <ui-questionnaire-input aria-label="Saved migration note"></ui-questionnaire-input>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-next>Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Update draft</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Conditional Items

Disable items that do not apply to the user's earlier answers. A `disabled` item is left out of the flow and the progress. To toggle one at runtime, set its `disabled` attribute from a change listener and call the questionnaire's `sync()`; in this demo the environment question stays disabled.

```ts
import { html } from '@webjsdev/core';

// A disabled question is left out of the flow. Toggle the environment
// question's disabled attribute from a change listener on the runtime
// answer, and the progress and actions follow.
export default function QuestionnaireConditional() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <ui-questionnaire-progress></ui-questionnaire-progress>

      <ui-questionnaire-item name="runtime" required>
        <ui-questionnaire-title>Where should the agent run?</ui-questionnaire-title>
        <ui-questionnaire-description>
          Cloud runs add an environment question to this flow.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="local" checked>
            Local workspace
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="cloud">
            Cloud workspace
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="environment" required disabled>
        <ui-questionnaire-title>
          Which cloud environment should it use?
        </ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="preview">Preview</ui-questionnaire-choice>
          <ui-questionnaire-choice value="staging">Staging</ui-questionnaire-choice>
          <ui-questionnaire-choice value="isolated">
            Isolated sandbox
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="approval" required>
        <ui-questionnaire-title>
          When should the agent request approval?
        </ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="writes">
            Before writing files
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="commands">
            Before running commands
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="sensitive">
            Only for sensitive actions
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-next>Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Save execution plan</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Navigation State

The kit exposes no per-item status, and its navigation buttons never disable. Next validates the active item instead: pressed with no answer, it stays put, marks the item invalid and shows its error. The buttons take `variant` and `size` as a button does.

```ts
import { html } from '@webjsdev/core';

// Next validates the active question itself: pressed with no answer, it
// stays put, marks the question invalid and shows its error.
export default function QuestionnaireNavigationState() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <ui-questionnaire-progress></ui-questionnaire-progress>

      <ui-questionnaire-item name="permission" required>
        <ui-questionnaire-title>What may the agent modify?</ui-questionnaire-title>
        <ui-questionnaire-description>
          Next stays on this question until an answer is selected.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="files">Project files</ui-questionnaire-choice>
          <ui-questionnaire-choice value="tests">
            Project files and tests
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="config">
            Files, tests, and configuration
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="verification" required>
        <ui-questionnaire-title>
          What must pass before completion?
        </ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="tests">Tests</ui-questionnaire-choice>
          <ui-questionnaire-choice value="types">
            Tests and types
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="all">
            Tests, types, and visual QA
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-next variant="secondary">Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Save permissions</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Custom Progress

`<ui-questionnaire-progress>` renders a "Question 1 of 4" line. Style the line with classes on the element.

```ts
import { html } from '@webjsdev/core';

// <ui-questionnaire-progress> renders a "Question 1 of 4" line. Style it
// with classes on the element; it takes no custom render.
export default function QuestionnaireProgressExample() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <ui-questionnaire-progress class="w-full"></ui-questionnaire-progress>

      <ui-questionnaire-item name="scope" required>
        <ui-questionnaire-title>How large is the change?</ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="small">Small patch</ui-questionnaire-choice>
          <ui-questionnaire-choice value="medium">
            Feature-sized change
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="large">
            Cross-package change
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="strategy" required>
        <ui-questionnaire-title>
          How should commits be organized?
        </ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="single">
            Single commit
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="logical">
            Logical commits
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="squash">
            Squash before review
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="tests" required>
        <ui-questionnaire-title>Which tests should run?</ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="targeted">
            Targeted tests
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="package">
            Package suite
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="workspace">
            Full workspace
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item name="delivery" required>
        <ui-questionnaire-title>
          How should the work be delivered?
        </ui-questionnaire-title>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="patch">Patch only</ui-questionnaire-choice>
          <ui-questionnaire-choice value="commit">
            Committed locally
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="branch">
            Push a review branch
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-next>Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Finish plan</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Animated Items

Animate the active item while keeping progress and navigation stationary. Each item moves its class onto the fieldset it renders, which carries `data-active` while it is shown, so the `data-active:` variant targets it directly.

```ts
import { html } from '@webjsdev/core';

// The element moves this class onto the fieldset it renders, which carries
// data-active while its question is on screen, so the variants key on the
// fieldset itself.
const itemClass =
  'data-active:animate-in data-active:fade-in-0 data-active:slide-in-from-bottom-2 data-active:duration-300 motion-reduce:animate-none';

export default function QuestionnaireAnimated() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md">
      <ui-questionnaire-progress></ui-questionnaire-progress>

      <ui-questionnaire-item class=${itemClass} name="task" required>
        <ui-questionnaire-title>What should the agent do?</ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose the task for this run.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="implement">
            Implement the requested change
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="debug">
            Debug the current behavior
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="review">
            Review the implementation
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item class=${itemClass} name="review" required>
        <ui-questionnaire-title>
          How should the work be reviewed?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Select the verification depth.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="targeted">
            Targeted checks
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="complete">
            Complete test suite
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="manual">
            Tests and manual QA
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-item class=${itemClass} name="delivery" required>
        <ui-questionnaire-title>
          How should the result be delivered?
        </ui-questionnaire-title>
        <ui-questionnaire-description>
          Choose the final handoff format.
        </ui-questionnaire-description>
        <ui-questionnaire-choices>
          <ui-questionnaire-choice value="summary">
            Concise summary
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="diff">
            Summary and changed files
          </ui-questionnaire-choice>
          <ui-questionnaire-choice value="handoff">
            Detailed review handoff
          </ui-questionnaire-choice>
        </ui-questionnaire-choices>
        <ui-questionnaire-error></ui-questionnaire-error>
      </ui-questionnaire-item>

      <ui-questionnaire-actions>
        <ui-questionnaire-previous></ui-questionnaire-previous>
        <ui-questionnaire-next>Next</ui-questionnaire-next>
        <ui-questionnaire-submit>Save workflow</ui-questionnaire-submit>
      </ui-questionnaire-actions>
    </ui-questionnaire>
  `;
}
```

## Card

Compose the questionnaire with the Card class helpers while keeping the question title and description semantic: put `cardTitleClass()` and `cardDescriptionClass()` on the title and description elements.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';

// The title and description keep their own legend and description roles,
// so the card's classes go on them rather than on a separate card title.
export default function QuestionnaireCard() {
  return html`
    <ui-questionnaire class="mx-auto w-full max-w-md" shortcuts="numbers">
      <div data-slot="card" data-size="default" class=${cardClass()}>
        <ui-questionnaire-item name="task" required>
          <div data-slot="card-header" class=${cardHeaderClass()}>
            <ui-questionnaire-title class=${cardTitleClass()}>
              What should the agent work on?
            </ui-questionnaire-title>
            <ui-questionnaire-description class=${cardDescriptionClass()}>
              Choose the task that should be handled next.
            </ui-questionnaire-description>
            <div data-slot="card-action" class=${cardActionClass()}>
              <ui-questionnaire-progress></ui-questionnaire-progress>
            </div>
          </div>
          <div data-slot="card-content" class=${cardContentClass()}>
            <ui-questionnaire-choices>
              <ui-questionnaire-choice value="fix">
                Fix the failing tests
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="refactor">
                Refactor the data layer
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="docs">
                Update the integration guide
              </ui-questionnaire-choice>
            </ui-questionnaire-choices>
            <ui-questionnaire-error></ui-questionnaire-error>
          </div>
        </ui-questionnaire-item>

        <ui-questionnaire-item name="output" required>
          <div data-slot="card-header" class=${cardHeaderClass()}>
            <ui-questionnaire-title class=${cardTitleClass()}>
              What should the final handoff include?
            </ui-questionnaire-title>
            <ui-questionnaire-description class=${cardDescriptionClass()}>
              Pick the level of detail needed for review.
            </ui-questionnaire-description>
            <div data-slot="card-action" class=${cardActionClass()}>
              <ui-questionnaire-progress></ui-questionnaire-progress>
            </div>
          </div>
          <div data-slot="card-content" class=${cardContentClass()}>
            <ui-questionnaire-choices>
              <ui-questionnaire-choice value="summary">
                Summary only
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="files">
                Summary and changed files
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="review">
                Full review handoff
              </ui-questionnaire-choice>
            </ui-questionnaire-choices>
            <ui-questionnaire-error></ui-questionnaire-error>
          </div>
        </ui-questionnaire-item>

        <div data-slot="card-footer" class=${cardFooterClass()}>
          <ui-questionnaire-actions class="w-full">
            <ui-questionnaire-previous></ui-questionnaire-previous>
            <ui-questionnaire-next>Next</ui-questionnaire-next>
            <ui-questionnaire-submit>Create task</ui-questionnaire-submit>
          </ui-questionnaire-actions>
        </div>
      </div>
    </ui-questionnaire>
  `;
}
```

## Dialog

Compose the questionnaire inside a Dialog while keeping cancellation and dismissal host-owned.

```ts
import { html } from '@webjsdev/core';
import { buttonClass } from '#components/ui/button.ts';
import {
  dialogHeaderClass, dialogTitleClass, dialogDescriptionClass, dialogFooterClass,
} from '#components/ui/dialog.ts';

// Cancel and dismissal belong to the dialog. Close it from a submit listener
// on the questionnaire once the answers are sent.
export default function QuestionnaireDialog() {
  return html`
    <ui-dialog>
      <ui-dialog-trigger>
        <button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Open clarification</button>
      </ui-dialog-trigger>
      <ui-dialog-content>
        <ui-questionnaire>
          <ui-questionnaire-item name="scope" required>
            <div data-slot="dialog-header" class=${dialogHeaderClass()}>
              <ui-questionnaire-progress></ui-questionnaire-progress>
              <ui-questionnaire-title class=${dialogTitleClass()}>
                Which files are in scope?
              </ui-questionnaire-title>
              <ui-questionnaire-description class=${dialogDescriptionClass()}>
                Choose how broadly the agent can update the workspace.
              </ui-questionnaire-description>
            </div>
            <ui-questionnaire-choices>
              <ui-questionnaire-choice value="component">
                Component only
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="feature">
                Complete feature directory
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="workspace">
                Any related workspace file
              </ui-questionnaire-choice>
            </ui-questionnaire-choices>
            <ui-questionnaire-error></ui-questionnaire-error>
          </ui-questionnaire-item>

          <ui-questionnaire-item name="tests" required>
            <div data-slot="dialog-header" class=${dialogHeaderClass()}>
              <ui-questionnaire-progress></ui-questionnaire-progress>
              <ui-questionnaire-title class=${dialogTitleClass()}>
                How much verification is needed?
              </ui-questionnaire-title>
              <ui-questionnaire-description class=${dialogDescriptionClass()}>
                Choose the checks the agent should run before handoff.
              </ui-questionnaire-description>
            </div>
            <ui-questionnaire-choices>
              <ui-questionnaire-choice value="targeted">
                Targeted tests
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="package">
                Package tests
              </ui-questionnaire-choice>
              <ui-questionnaire-choice value="full">
                Full workspace verification
              </ui-questionnaire-choice>
            </ui-questionnaire-choices>
            <ui-questionnaire-error></ui-questionnaire-error>
          </ui-questionnaire-item>

          <div data-slot="dialog-footer" class=${dialogFooterClass()}>
            <ui-dialog-close>
              <button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>
                Cancel
              </button>
            </ui-dialog-close>
            <ui-questionnaire-actions class="w-full">
              <ui-questionnaire-previous></ui-questionnaire-previous>
              <ui-questionnaire-next>Next</ui-questionnaire-next>
              <ui-questionnaire-submit>Send answer</ui-questionnaire-submit>
            </ui-questionnaire-actions>
          </div>
        </ui-questionnaire>
      </ui-dialog-content>
    </ui-dialog>
  `;
}
```

## Accessibility

`<ui-questionnaire-item>` renders a `fieldset`, and `<ui-questionnaire-title>` renders its `legend`, which also names the fieldset. Descriptions and active errors are associated with the current item, and an item left unanswered exposes `aria-invalid` with its error announced as an alert.

Fixed choices are native radios and checkboxes. Progress is exposed as a named progressbar, navigation uses real buttons, and inactive items are `hidden` and `inert`. Successful navigation focuses the newly active item's first answer, and failed validation focuses an available answer control. Enter goes to the next item, and on the last one submits.

Always give `<ui-questionnaire-input>` an accessible name with `aria-label`. A placeholder is not a label.

## Unstyled

The behavior lives in the `<ui-questionnaire-*>` elements, and the classes they apply are exported as helpers such as `questionnaireChoiceClass()`. Since `webjs ui add` copies the source into your project, change the markup or the classes there.

## API Reference

### ui-questionnaire

The root. It renders the `<form>` and owns the active item, validation, and navigation.

| Attribute | Type | Default |
| --- | --- | --- |
| `shortcuts` | `"letters" \| "numbers"` | - |
| `action` | `string` | - |
| `method` | `string` | - |

It dispatches `ui-active-change` with `{ detail: { name } }` after the active item changes. Its methods are `next()`, `previous()`, `skip()`, `validate(item?)` (marks the active item invalid and returns `false` when it needs an answer), `answered(item)`, `items()` (the items in the flow) and `sync()` (redraws the parts after host code changes an item).

### ui-questionnaire-item

One question, rendered as a `fieldset`. Its answers share its `name`.

| Attribute | Type | Default |
| --- | --- | --- |
| `name` | `string` | `""` |
| `required` | `boolean` | `false` |
| `multiple` | `boolean` | `false` |
| `disabled` | `boolean` | `false` |

### ui-questionnaire-choice

One fixed answer: a radio, or a checkbox in a `multiple` item, with its label. Put a `<ui-questionnaire-choice-description>` inside for a second line.

| Attribute | Type | Default |
| --- | --- | --- |
| `value` | `string` | `""` |
| `checked` | `boolean` | `false` |
| `disabled` | `boolean` | `false` |

### ui-questionnaire-input

A freeform answer, a text field named after its item.

| Attribute | Type | Default |
| --- | --- | --- |
| `placeholder` | `string` | `""` |
| `aria-label` | `string` | - |

### ui-questionnaire-error

The item's error line, hidden until the item is invalid. Its content replaces the default message, which is "Choose an answer to continue." on a required item and "Choose an answer or skip this question." otherwise.

### Navigation buttons

`<ui-questionnaire-previous>`, `<ui-questionnaire-skip>`, `<ui-questionnaire-next>` and `<ui-questionnaire-submit>` show only when they apply. Their content replaces the default label (Previous, Skip, Next, Submit).

| Attribute | Type | Default |
| --- | --- | --- |
| `variant` | `"default" \| "outline" \| "ghost" \| "destructive" \| "secondary" \| "link"` | `"outline"`, `"default"` on Next and Submit |
| `size` | `"default" \| "xs" \| "sm" \| "lg"` | `"default"` |

### Layout parts

`<ui-questionnaire-actions>` is a styled-only layout helper.
