# Questionnaire

A multi-step form that asks one question at a time, with single-choice, multiple-choice, freeform and skippable questions.

```tsx
"use client"

import type { FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoiceDescription,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireInput,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSkip,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { Text } from "@/components/ui/text"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  {
    name: "problem",
    required: true,
    title: "Which problem should the agent tackle first?",
    description: "Pick one, or write in a different problem.",
    choices: [
      {
        value: "flaky-tests",
        label: "Flaky tests",
        description: "Find the tests that fail at random and fix them.",
      },
      {
        value: "slow-build",
        label: "Slow builds",
        description: "Profile the build and cut its slowest steps.",
      },
      {
        value: "type-errors",
        label: "Type errors",
        description: "Clear the errors left over from the last upgrade.",
      },
    ],
    input: { label: "Another problem", placeholder: "Describe a different problem…" },
  },
  {
    name: "report",
    required: false,
    multiple: true,
    title: "What should the agent report back?",
    description: "Pick any number of these, or skip the question.",
    choices: [
      { value: "cause", label: "Root cause" },
      { value: "files", label: "Files changed" },
      { value: "tests", label: "Test results" },
      { value: "questions", label: "Open questions" },
    ],
  },
  {
    name: "urgency",
    required: true,
    title: "How soon is this needed?",
    description: "The agent schedules the work around your answer.",
    choices: [
      { value: "today", label: "Today" },
      { value: "this-week", label: "Some time this week" },
      { value: "later", label: "Whenever there is time" },
    ],
  },
] as const

export default function QuestionnaireDemo() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Request sent",
      description: `Problem: ${answers.get("problem") ?? "None"} · Report: ${
        answers.getAll("report").join(", ") || "None"
      } · Needed: ${answers.get("urgency") ?? "None"}`,
    })
  }

  return (
    <Questionnaire items={items} shortcuts="letters" onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireProgress />
      {items.map((question) => (
        <QuestionnaireItem
          key={question.name}
          name={question.name}
          required={question.required}
          multiple={"multiple" in question && question.multiple}
        >
          <QuestionnaireTitle>{question.title}</QuestionnaireTitle>
          <QuestionnaireDescription>{question.description}</QuestionnaireDescription>
          <QuestionnaireChoices>
            {question.choices.map((choice) => (
              <QuestionnaireChoice key={choice.value} value={choice.value}>
                {"description" in choice ? (
                  <>
                    <Text weight="medium">{choice.label}</Text>
                    <QuestionnaireChoiceDescription>
                      {choice.description}
                    </QuestionnaireChoiceDescription>
                  </>
                ) : (
                  choice.label
                )}
              </QuestionnaireChoice>
            ))}
            {"input" in question && (
              <QuestionnaireInput
                aria-label={question.input.label}
                placeholder={question.input.placeholder}
              />
            )}
          </QuestionnaireChoices>
          <QuestionnaireError />
        </QuestionnaireItem>
      ))}
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireSkip />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Send request</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

A questionnaire shows one question at a time and moves through them in order.
It fits anywhere a short series of questions has to be answered before
something can continue: an agent asking clarifying questions, onboarding, a
survey, an intake form, a setup flow.

It owns the ordered items, the active item, answer state, validation, progress
and navigation. The page, card, dialog or drawer around it owns closing and
cancelling, persistence, transport and branching. The behaviour comes from the
headless `@shadcn/react/questionnaire` package; this component draws its
answers as arene's choice cards and its actions as arene buttons.

## Installation

**Command**

```bash
npx shadcn@latest add @arene/questionnaire
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Button](https://www.arene.style/docs/components/button), [Checkbox](https://www.arene.style/docs/components/checkbox), [Field](https://www.arene.style/docs/components/field), [Input](https://www.arene.style/docs/components/input), [Kbd](https://www.arene.style/docs/components/kbd), [Label](https://www.arene.style/docs/components/label), [Radio Group](https://www.arene.style/docs/components/radio-group), [Separator](https://www.arene.style/docs/components/separator) and [Stack](https://www.arene.style/docs/components/stack).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @shadcn/react @stylexjs/stylex clsx @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` from the same page,
   which hides the native inputs and draws the focus ring and the disabled dim.
   It also needs `interop.css`, which sizes the checkmark, and the
   `lib/focus-visible.ts` helper, which tells a card whether its focus came from
   the keyboard.

3. Add [Button](https://www.arene.style/docs/components/button), [Checkbox](https://www.arene.style/docs/components/checkbox),
   [Radio Group](https://www.arene.style/docs/components/radio-group), [Field](https://www.arene.style/docs/components/field),
   [Input](https://www.arene.style/docs/components/input) and [Kbd](https://www.arene.style/docs/components/kbd). The actions
   render the button and the freeform answer renders the input. The rest reuse the
   exported style maps of the other four: the checkbox or radio box and its tick
   or dot, the field's choice card and error text, and the keycap of the shortcut.

4. Paste the focus-visible helper and the component into your project.

   ```ts title="lib/focus-visible.ts"
   "use client"

   import { useState, type FocusEvent } from "react"

   type FocusHandlers<Event> = {
     onFocus?: (event: Event) => void
     onBlur?: (event: Event) => void
   }

   export function useFocusVisible<Event extends FocusEvent<Element>>({
     onFocus,
     onBlur,
   }: FocusHandlers<Event> = {}) {
     const [focusVisible, setFocusVisible] = useState(false)
     const focusProps = {
       onFocus: (event: Event) => {
         onFocus?.(event)
         setFocusVisible(event.target.matches(":focus-visible"))
       },
       onBlur: (event: Event) => {
         onBlur?.(event)
         setFocusVisible(false)
       },
     }
     return { focusVisible, setFocusVisible, focusProps }
   }
   ```

   ```tsx title="components/ui/questionnaire.tsx"
   "use client"

   import {
     Children,
     createContext,
     isValidElement,
     use,
     type ComponentProps,
     type JSXElementConstructor,
   } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import {
     Questionnaire as QuestionnairePrimitive,
     type QuestionnaireChoiceDefinition,
     type QuestionnaireInputType,
     type QuestionnaireItemDefinition,
     type QuestionnaireItemStatus,
     type QuestionnaireShortcutMode,
   } from "@shadcn/react/questionnaire"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import { CheckIcon } from "@phosphor-icons/react/dist/csr/Check"

   import { Button, type ButtonSize, type ButtonVariant } from "@/components/ui/button"
   import { checkboxStyles } from "@/components/ui/checkbox"
   import { fieldStyles } from "@/components/ui/field"
   import { Input, inputStyles } from "@/components/ui/input"
   import { kbdStyles } from "@/components/ui/kbd"
   import { radioGroupStyles } from "@/components/ui/radio-group"
   import { useFocusVisible } from "@/lib/focus-visible"
   import { states } from "@/theme/states"
   import { color, leading, space, text } from "@/theme/tokens.stylex"

   const QuestionnaireItemContext = createContext<{ described: boolean }>({ described: false })

   const styles = stylex.create({
     root: {
       display: "flex",
       flexDirection: "column",
       gap: space.s4,
       width: "100%",
       minWidth: 0,
     },
     progress: {
       width: "fit-content",
       minHeight: "1lh",
       color: color.mutedForeground,
       fontSize: text.xs,
       lineHeight: leading.xs,
       fontWeight: 500,
     },
     item: {
       display: "flex",
       flexDirection: "column",
       gap: space.s4,
       minWidth: 0,
       outlineStyle: "none",
     },
     title: {
       color: color.foreground,
       fontSize: text.base,
       lineHeight: leading.base,
       fontWeight: 500,
       textWrap: "pretty",
     },
     titleAlone: { marginBlockEnd: space.s4 },
     titleDescribed: { marginBlockEnd: space.s1 },
     description: {
       color: color.mutedForeground,
       fontSize: text.sm,
       lineHeight: leading.sm,
       textWrap: "pretty",
     },
     choices: {
       display: "grid",
       gap: space.s2,
       minWidth: 0,
     },
     choice: {
       position: "relative",
       display: "flex",
       flexDirection: "row",
       alignItems: "flex-start",
       columnGap: space.s3,
       paddingInline: space.s3,
       color: color.foreground,
       textAlign: "start",
       userSelect: "none",
     },
     choiceBox: {
       marginBlock: space.s0_5,
       borderColor: "var(--arene-border-color)",
     },
     label: {
       display: "flex",
       flexDirection: "column",
       gap: space.s0_5,
       flexGrow: 1,
       minWidth: 0,
       fontSize: text.sm,
       lineHeight: leading.sm,
     },
     choiceDescription: { color: color.mutedForeground },
     actions: {
       display: "grid",
       gridTemplateColumns: "minmax(0, 1fr) auto auto",
       alignItems: "center",
       gap: space.s2,
       width: "100%",
     },
     previous: { gridColumnStart: "1", gridRowStart: "1", justifySelf: "start" },
     skip: { gridColumnStart: "2", gridRowStart: "1", justifySelf: "end" },
     next: { gridColumnStart: "3", gridRowStart: "1", justifySelf: "end" },
   })

   const questionnaireStyles = {
     root: styles.root,
     progress: styles.progress,
     item: styles.item,
     title: styles.title,
     description: styles.description,
     choices: styles.choices,
     choice: [fieldStyles.card, styles.choice],
     choiceChecked: fieldStyles.cardChecked,
     choiceFocused: fieldStyles.cardFocused,
     choiceLabel: styles.label,
     choiceDescription: styles.choiceDescription,
     input: inputStyles.base,
     error: fieldStyles.error,
     actions: styles.actions,
   }

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type PartState<Part> =
     Part extends JSXElementConstructor<infer Props>
       ? Props extends { render?: infer Render }
         ? Render extends (props: never, state: infer State) => unknown
           ? State
           : never
         : never
       : never

   type QuestionnaireChoiceState = PartState<typeof QuestionnairePrimitive.Choice>
   type QuestionnaireInputState = PartState<typeof QuestionnairePrimitive.Input>
   type QuestionnaireNavigationState = PartState<typeof QuestionnairePrimitive.Next>

   const choiceControls = {
     checkbox: { control: checkboxStyles, box: checkboxStyles.root, glyph: <CheckIcon /> },
     radio: { control: radioGroupStyles, box: radioGroupStyles.item, glyph: null },
   }

   function ChoiceHost({ render, ref, ...props }: useRender.ComponentProps<"label">) {
     return useRender({ defaultTagName: "label", render, ref, props })
   }

   function bindState<State>(
     render: useRender.RenderProp<State> | undefined,
     state: State,
   ): useRender.RenderProp<unknown> | undefined {
     return typeof render === "function" ? (props) => render(props, state) : render
   }

   type QuestionnaireProps = Omit<ComponentProps<typeof QuestionnairePrimitive.Root>, "className"> &
     Overrides

   function Questionnaire({ xstyle, className, style, ...props }: QuestionnaireProps) {
     const sx = stylex.props(styles.root, xstyle)
     return (
       <QuestionnairePrimitive.Root
         data-slot="questionnaire"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type QuestionnaireProgressProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Progress>,
     "className"
   > &
     Overrides

   function QuestionnaireProgress({ xstyle, className, style, ...props }: QuestionnaireProgressProps) {
     const sx = stylex.props(styles.progress, xstyle)
     return (
       <QuestionnairePrimitive.Progress
         data-slot="questionnaire-progress"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type QuestionnaireItemProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Item>,
     "className"
   > &
     Overrides

   function QuestionnaireItem({
     xstyle,
     className,
     style,
     children,
     ...props
   }: QuestionnaireItemProps) {
     const described = Children.toArray(children).some(
       (child) => isValidElement(child) && child.type === QuestionnaireDescription,
     )
     const sx = stylex.props(styles.item, xstyle)
     return (
       <QuestionnaireItemContext value={{ described }}>
         <QuestionnairePrimitive.Item
           data-slot="questionnaire-item"
           {...sx}
           {...props}
           className={clsx(sx.className, className)}
           style={{ ...sx.style, ...style }}
         >
           {children}
         </QuestionnairePrimitive.Item>
       </QuestionnaireItemContext>
     )
   }

   type QuestionnaireTitleProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Title>,
     "className"
   > &
     Overrides

   function QuestionnaireTitle({ xstyle, className, style, ...props }: QuestionnaireTitleProps) {
     const { described } = use(QuestionnaireItemContext)
     const sx = stylex.props(
       styles.title,
       described ? styles.titleDescribed : styles.titleAlone,
       xstyle,
     )
     return (
       <QuestionnairePrimitive.Title
         data-slot="questionnaire-title"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type QuestionnaireDescriptionProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Description>,
     "className"
   > &
     Overrides

   function QuestionnaireDescription({
     xstyle,
     className,
     style,
     ...props
   }: QuestionnaireDescriptionProps) {
     const sx = stylex.props(styles.description, xstyle)
     return (
       <QuestionnairePrimitive.Description
         data-slot="questionnaire-description"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type QuestionnaireChoicesProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Choices>,
     "className"
   > &
     Overrides

   function QuestionnaireChoices({ xstyle, className, style, ...props }: QuestionnaireChoicesProps) {
     const sx = stylex.props(styles.choices, xstyle)
     return (
       <QuestionnairePrimitive.Choices
         data-slot="questionnaire-choices"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type QuestionnaireChoiceProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Choice>,
     "className" | "render"
   > &
     Overrides & {
       render?: useRender.ComponentProps<"label", QuestionnaireChoiceState>["render"]
     }

   function QuestionnaireChoice({
     render,
     xstyle,
     className,
     style,
     children,
     onFocus,
     onBlur,
     ...props
   }: QuestionnaireChoiceProps) {
     const { focusVisible, focusProps } = useFocusVisible({ onFocus, onBlur })
     return (
       <QuestionnairePrimitive.Choice
         data-slot="questionnaire-choice"
         {...props}
         {...focusProps}
         render={(choiceProps, state) => {
           const sx = stylex.props(
             fieldStyles.card,
             styles.choice,
             state.checked && fieldStyles.cardChecked,
             focusVisible && fieldStyles.cardFocused,
             state.disabled && states.disabled,
             xstyle,
           )
           return (
             <ChoiceHost
               {...choiceProps}
               render={bindState(render, state)}
               className={clsx(sx.className, className)}
               style={{ ...sx.style, ...style }}
             />
           )
         }}
       >
         <QuestionnairePrimitive.ChoiceInput
           {...stylex.props(states.srOnly)}
           render={(inputProps, state) => (
             <>
               <input {...inputProps} />
               <ChoiceIndicator {...state} />
             </>
           )}
         />
         <QuestionnairePrimitive.ChoiceLabel {...stylex.props(styles.label)}>
           {children}
         </QuestionnairePrimitive.ChoiceLabel>
         <QuestionnairePrimitive.ChoiceShortcut {...stylex.props(kbdStyles.base)} />
       </QuestionnairePrimitive.Choice>
     )
   }

   function ChoiceIndicator({ type, checked, invalid }: QuestionnaireChoiceState) {
     const { control, box, glyph } = choiceControls[type]
     const sx = stylex.props(
       box,
       control.choice,
       styles.choiceBox,
       invalid && control.invalid,
       checked && control.checked,
     )
     return (
       <span aria-hidden="true" {...sx} className={clsx("arene-icons", sx.className)}>
         <span {...stylex.props(control.indicator, !checked && control.indicatorHidden)}>{glyph}</span>
       </span>
     )
   }

   type QuestionnaireChoiceDescriptionProps = useRender.ComponentProps<"span"> & Overrides

   function QuestionnaireChoiceDescription({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: QuestionnaireChoiceDescriptionProps) {
     const sx = stylex.props(styles.choiceDescription, xstyle)
     return useRender({
       defaultTagName: "span",
       render,
       ref,
       props: {
         "data-slot": "questionnaire-choice-description",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type QuestionnaireInputProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Input>,
     "className" | "render"
   > &
     Overrides & {
       render?: useRender.ComponentProps<"input", QuestionnaireInputState>["render"]
     }

   function QuestionnaireInput({ render, xstyle, ...props }: QuestionnaireInputProps) {
     return (
       <QuestionnairePrimitive.Input
         data-slot="questionnaire-input"
         {...props}
         render={(inputProps, state) => (
           <Input
             {...(inputProps as ComponentProps<typeof Input>)}
             data-slot="questionnaire-input"
             xstyle={xstyle}
             render={bindState(render, state)}
           />
         )}
       />
     )
   }

   type QuestionnaireErrorProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Error>,
     "className"
   > &
     Overrides

   function QuestionnaireError({ xstyle, className, style, ...props }: QuestionnaireErrorProps) {
     const sx = stylex.props(fieldStyles.error, xstyle)
     return (
       <QuestionnairePrimitive.Error
         data-slot="questionnaire-error"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type QuestionnaireActionsProps = useRender.ComponentProps<"div"> & Overrides

   function QuestionnaireActions({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: QuestionnaireActionsProps) {
     const sx = stylex.props(styles.actions, xstyle)
     return useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "questionnaire-actions",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type QuestionnaireNavigationProps = Omit<
     ComponentProps<typeof QuestionnairePrimitive.Next>,
     "className" | "render"
   > &
     Overrides & {
       render?: useRender.ComponentProps<"button", QuestionnaireNavigationState>["render"]
       variant?: ButtonVariant
       size?: ButtonSize
     }

   type NavigationPart =
     | typeof QuestionnairePrimitive.Previous
     | typeof QuestionnairePrimitive.Skip
     | typeof QuestionnairePrimitive.Next
     | typeof QuestionnairePrimitive.Submit

   function NavigationButton({
     primitive: Part,
     slotName,
     placement,
     render,
     variant = "default",
     size = "default",
     xstyle,
     className,
     ...props
   }: QuestionnaireNavigationProps & {
     primitive: NavigationPart
     slotName: string
     placement: StyleXStyles
   }) {
     return (
       <Part
         data-slot={slotName}
         {...props}
         render={(buttonProps, state) => (
           <Button
             {...(buttonProps as ComponentProps<typeof Button>)}
             data-slot={slotName}
             variant={variant}
             size={size}
             xstyle={[placement, xstyle]}
             className={className}
             render={bindState(render, state)}
           />
         )}
       />
     )
   }

   function QuestionnairePrevious({ variant = "outline", ...props }: QuestionnaireNavigationProps) {
     return (
       <NavigationButton
         primitive={QuestionnairePrimitive.Previous}
         slotName="questionnaire-previous"
         placement={styles.previous}
         variant={variant}
         {...props}
       />
     )
   }

   function QuestionnaireSkip({ variant = "outline", ...props }: QuestionnaireNavigationProps) {
     return (
       <NavigationButton
         primitive={QuestionnairePrimitive.Skip}
         slotName="questionnaire-skip"
         placement={styles.skip}
         variant={variant}
         {...props}
       />
     )
   }

   function QuestionnaireNext(props: QuestionnaireNavigationProps) {
     return (
       <NavigationButton
         primitive={QuestionnairePrimitive.Next}
         slotName="questionnaire-next"
         placement={styles.next}
         {...props}
       />
     )
   }

   function QuestionnaireSubmit(props: QuestionnaireNavigationProps) {
     return (
       <NavigationButton
         primitive={QuestionnairePrimitive.Submit}
         slotName="questionnaire-submit"
         placement={styles.next}
         {...props}
       />
     )
   }

   export {
     Questionnaire,
     QuestionnaireActions,
     QuestionnaireChoice,
     QuestionnaireChoiceDescription,
     QuestionnaireChoices,
     QuestionnaireDescription,
     QuestionnaireError,
     QuestionnaireInput,
     QuestionnaireItem,
     QuestionnaireNext,
     QuestionnairePrevious,
     QuestionnaireProgress,
     QuestionnaireSkip,
     QuestionnaireSubmit,
     QuestionnaireTitle,
     questionnaireStyles,
     type QuestionnaireChoiceDefinition,
     type QuestionnaireChoiceState,
     type QuestionnaireInputState,
     type QuestionnaireInputType,
     type QuestionnaireItemDefinition,
     type QuestionnaireItemStatus,
     type QuestionnaireNavigationState,
     type QuestionnaireShortcutMode,
   }
   ```

5. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireInput,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSkip,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
```

```tsx
const items = [
  {
    name: "area",
    required: true,
    title: "Which part of the app needs work?",
    choices: [
      { value: "search", label: "Search" },
      { value: "checkout", label: "Checkout" },
    ],
  },
  {
    name: "depth",
    title: "How closely should the agent look?",
    choices: [
      { value: "skim", label: "A quick pass" },
      { value: "thorough", label: "Line by line" },
    ],
  },
] as const
```

```tsx
<Questionnaire items={items} onSubmit={handleSubmit}>
  <QuestionnaireProgress />
  {items.map((question) => (
    <QuestionnaireItem key={question.name} name={question.name} required={question.required}>
      <QuestionnaireTitle>{question.title}</QuestionnaireTitle>
      <QuestionnaireChoices>
        {question.choices.map((choice) => (
          <QuestionnaireChoice key={choice.value} value={choice.value}>
            {choice.label}
          </QuestionnaireChoice>
        ))}
      </QuestionnaireChoices>
      <QuestionnaireError />
    </QuestionnaireItem>
  ))}
  <QuestionnaireActions>
    <QuestionnairePrevious />
    <QuestionnaireSkip />
    <QuestionnaireNext />
    <QuestionnaireSubmit />
  </QuestionnaireActions>
</Questionnaire>
```

`Questionnaire` renders a native form, so the answers are read with `FormData`.
Each item's `name` is the field name of its answers.

```tsx
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault()
  const answers = new FormData(event.currentTarget)
  answers.get("area")
}
```

## Composition

```text
Questionnaire
├── QuestionnaireProgress
├── QuestionnaireItem
│   ├── QuestionnaireTitle
│   ├── QuestionnaireDescription
│   ├── QuestionnaireChoices
│   │   ├── QuestionnaireChoice
│   │   │   └── QuestionnaireChoiceDescription
│   │   └── QuestionnaireInput
│   └── QuestionnaireError
└── QuestionnaireActions
    ├── QuestionnairePrevious
    ├── QuestionnaireSkip
    ├── QuestionnaireNext
    └── QuestionnaireSubmit
```

Every item stays mounted. The inactive ones are hidden and inert, and each
action shows only when it applies: Previous after the first item, Skip on an
optional item, Next before the last item and Submit on it.
`QuestionnaireActions` lays them out with Previous at the start and the rest at
the end.

Give `Questionnaire` the same `items` array that you render as items and
choices. With it, the item order, progress, the visible actions and the
answer shortcuts are in the server-rendered HTML. Without it, the questionnaire
reads them from the rendered parts after hydration.

## Multiple selection

`multiple` turns an item's choices into checkboxes. Read the answers with
`FormData.getAll()`.

```tsx
"use client"

import type { FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  {
    name: "reading",
    required: true,
    choices: [{ value: "issue" }, { value: "tests" }, { value: "decisions" }, { value: "blame" }],
  },
] as const

export default function QuestionnaireMultiple() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const reading = new FormData(event.currentTarget).getAll("reading")
    toast.add({ title: "Reading list set", description: reading.join(", ") || "None" })
  }

  return (
    <Questionnaire items={items} shortcuts="letters" onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireItem name="reading" multiple required>
        <QuestionnaireTitle>What should the agent read before it starts?</QuestionnaireTitle>
        <QuestionnaireDescription>
          Pick everything that bears on the change.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="issue">The original issue</QuestionnaireChoice>
          <QuestionnaireChoice value="tests">The failing tests</QuestionnaireChoice>
          <QuestionnaireChoice value="decisions">Past design decisions</QuestionnaireChoice>
          <QuestionnaireChoice value="blame">Git blame for the file</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnaireSubmit>Start reading</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Freeform answer

Put a `QuestionnaireInput` beside the choices when the reader can give another
answer. In a single-choice item, typing replaces the selected choice and
selecting a choice replaces the typed answer. Give the input an accessible name
with `aria-label` or a visible label; a placeholder is not one.

```tsx
"use client"

import type { FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireInput,
  QuestionnaireItem,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  {
    name: "plan",
    required: true,
    choices: [{ value: "deprecate" }, { value: "codemod" }, { value: "remove" }],
  },
] as const

export default function QuestionnaireFreeform() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const plan = new FormData(event.currentTarget).get("plan")
    toast.add({ title: "Plan chosen", description: String(plan ?? "None") })
  }

  return (
    <Questionnaire items={items} shortcuts="letters" onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireItem name="plan" required>
        <QuestionnaireTitle>How should the agent remove the old API?</QuestionnaireTitle>
        <QuestionnaireDescription>
          Pick a plan, or write the steps you want.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="deprecate">
            Deprecate it now, remove it later
          </QuestionnaireChoice>
          <QuestionnaireChoice value="codemod">
            Move every caller with a codemod
          </QuestionnaireChoice>
          <QuestionnaireChoice value="remove">Remove it in one change</QuestionnaireChoice>
          <QuestionnaireInput aria-label="Another plan" placeholder="Describe a different plan…" />
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnaireSubmit>Go with this plan</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Explicit skip

`QuestionnaireSkip` records that an optional item was left unanswered on
purpose. A skipped item is absent from `FormData`, so use `onStatusChange` on
the item when the host needs to tell a skip from a missing answer.

```tsx
"use client"

import { useState, type FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireInput,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSkip,
  QuestionnaireSubmit,
  QuestionnaireTitle,
  type QuestionnaireItemStatus,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  { name: "task", required: true },
  { name: "constraints" },
  { name: "review", required: true },
]

export default function QuestionnaireSkipDemo() {
  const [constraintStatus, setConstraintStatus] = useState<QuestionnaireItemStatus>("unanswered")

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    const constraints =
      constraintStatus === "skipped" ? "Skipped" : (answers.get("constraints") ?? "None")
    toast.add({
      title: "Brief sent",
      description: `Purpose: ${answers.get("task") ?? "None"} · Limits: ${constraints} · Before handoff: ${
        answers.get("review") ?? "None"
      }`,
    })
  }

  return (
    <Questionnaire items={items} onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireProgress />
      <QuestionnaireItem name="task" required>
        <QuestionnaireTitle>What is this change for?</QuestionnaireTitle>
        <QuestionnaireDescription>Pick the closest match.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="add">Adding something new</QuestionnaireChoice>
          <QuestionnaireChoice value="fix">Fixing something broken</QuestionnaireChoice>
          <QuestionnaireChoice value="cleanup">Cleaning up old code</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="constraints" onStatusChange={setConstraintStatus}>
        <QuestionnaireTitle>Is anything off limits?</QuestionnaireTitle>
        <QuestionnaireDescription>
          Answer if it matters, or press Skip to leave it out on purpose.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="no-packages">No new packages</QuestionnaireChoice>
          <QuestionnaireChoice value="no-schema">No schema changes</QuestionnaireChoice>
          <QuestionnaireChoice value="no-breaking">No breaking API changes</QuestionnaireChoice>
          <QuestionnaireInput aria-label="Another limit" placeholder="Describe another limit…" />
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="review" required>
        <QuestionnaireTitle>What should the agent do before handing off?</QuestionnaireTitle>
        <QuestionnaireDescription>Pick the check it finishes with.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="tests">Run every test</QuestionnaireChoice>
          <QuestionnaireChoice value="diff">Reread its own diff</QuestionnaireChoice>
          <QuestionnaireChoice value="both">Both of those</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireSkip />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Send brief</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Shortcuts

`shortcuts="letters"` gives each enabled choice a key from `A` to `Z`, and
`shortcuts="numbers"` from `1` to `9`. Pressing a key selects the answer
without moving to the next item.

```tsx
"use client"

import { useState, type FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireSubmit,
  QuestionnaireTitle,
  type QuestionnaireShortcutMode,
} from "@/components/ui/questionnaire"
import { VStack } from "@/components/ui/stack"
import { toast } from "@/components/ui/toast"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { widths } from "@/theme/widths"

const items = [
  {
    name: "action",
    required: true,
    choices: [{ value: "trace" }, { value: "rerun" }, { value: "fix" }],
  },
] as const

type Mode = QuestionnaireShortcutMode | "none"

export default function QuestionnaireShortcuts() {
  const [mode, setMode] = useState<Mode>("letters")

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const action = new FormData(event.currentTarget).get("action")
    toast.add({ title: "Step chosen", description: String(action ?? "None") })
  }

  return (
    <VStack gap={6} align="start" xstyle={widths.md}>
      <ToggleGroup
        aria-label="Key hints"
        size="sm"
        spacing={0}
        value={[mode]}
        onValueChange={(value) => value[0] && setMode(value[0] as Mode)}
      >
        <ToggleGroupItem value="none">None</ToggleGroupItem>
        <ToggleGroupItem value="letters">Letters</ToggleGroupItem>
        <ToggleGroupItem value="numbers">Numbers</ToggleGroupItem>
      </ToggleGroup>
      <Questionnaire
        items={items}
        shortcuts={mode === "none" ? undefined : mode}
        onSubmit={handleSubmit}
      >
        <QuestionnaireItem name="action" required>
          <QuestionnaireTitle>Which step should come next?</QuestionnaireTitle>
          <QuestionnaireDescription>
            Press an answer's key, or use the arrow keys to move between answers.
          </QuestionnaireDescription>
          <QuestionnaireChoices>
            <QuestionnaireChoice value="trace">Read the stack trace</QuestionnaireChoice>
            <QuestionnaireChoice value="rerun">Rerun the failing test</QuestionnaireChoice>
            <QuestionnaireChoice value="fix">Write a fix</QuestionnaireChoice>
          </QuestionnaireChoices>
          <QuestionnaireError />
        </QuestionnaireItem>
        <QuestionnaireActions>
          <QuestionnaireSubmit>Choose step</QuestionnaireSubmit>
        </QuestionnaireActions>
      </Questionnaire>
    </VStack>
  )
}
```

## Custom validation

The questionnaire validates the active item before it moves forward and every
enabled item on submit. A required item needs an answer, and an optional one
needs an answer or a skip. For a rule across items, set `invalid` on the item,
pass the message to `QuestionnaireError`, and move the controlled `item` back
to it.

```tsx
"use client"

import { useState, type FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  { name: "detail", required: true },
  { name: "audience", required: true },
]

type Errors = Partial<Record<"detail" | "audience", string>>

function validate(answers: FormData): Errors {
  if (answers.get("audience") === "customers" && answers.get("detail") === "short") {
    return { detail: "Notes for customers need more than a few lines. Pick the full write-up." }
  }
  return {}
}

export default function QuestionnaireValidation() {
  const [item, setItem] = useState("detail")
  const [errors, setErrors] = useState<Errors>({})

  function clearError(name: keyof Errors) {
    setErrors(({ [name]: _cleared, ...rest }) => rest)
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    const nextErrors = validate(answers)
    setErrors(nextErrors)
    const firstInvalid = items.find(({ name }) => name in nextErrors)
    if (firstInvalid) {
      setItem(firstInvalid.name)
      return
    }
    toast.add({
      title: "Release notes set up",
      description: `Length: ${answers.get("detail")} · Readers: ${answers.get("audience")}`,
    })
  }

  return (
    <Questionnaire
      item={item}
      items={items}
      onItemChange={setItem}
      onSubmit={handleSubmit}
      xstyle={widths.md}
    >
      <QuestionnaireProgress />
      <QuestionnaireItem name="detail" required invalid={Boolean(errors.detail)}>
        <QuestionnaireTitle>How long should the release notes be?</QuestionnaireTitle>
        <QuestionnaireDescription>Pick a length.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="short" onChange={() => clearError("detail")}>
            A few lines
          </QuestionnaireChoice>
          <QuestionnaireChoice value="full" onChange={() => clearError("detail")}>
            A full write-up
          </QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError>{errors.detail}</QuestionnaireError>
      </QuestionnaireItem>
      <QuestionnaireItem name="audience" required invalid={Boolean(errors.audience)}>
        <QuestionnaireTitle>Who are the notes for?</QuestionnaireTitle>
        <QuestionnaireDescription>
          Notes for customers need the full write-up.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="engineers" onChange={() => clearError("audience")}>
            Our engineers
          </QuestionnaireChoice>
          <QuestionnaireChoice value="customers" onChange={() => clearError("audience")}>
            Customers
          </QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError>{errors.audience}</QuestionnaireError>
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Check answers</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

> **Note**
>
> `required` adds no visible text. Say that a question is required in its title
> or description.

## Controlled

Pass `item` and `onItemChange` to keep the active item in host state.

```tsx
"use client"

import { useState, type FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { HStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  { name: "scope", required: true, label: "Files" },
  { name: "checks", required: true, label: "Checks" },
  { name: "output", required: true, label: "Report" },
]

export default function QuestionnaireControlled() {
  const [item, setItem] = useState("scope")

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Agent settings saved",
      description: `Files: ${answers.get("scope")} · Checks: ${answers.get("checks")} · Report: ${answers.get("output")}`,
    })
  }

  return (
    <Questionnaire
      item={item}
      items={items}
      onItemChange={setItem}
      onSubmit={handleSubmit}
      xstyle={widths.md}
    >
      <HStack justify="between" align="center" gap={2}>
        <QuestionnaireProgress />
        <Text size="sm" tone="muted" render={<output />}>
          {items.find(({ name }) => name === item)?.label}
        </Text>
      </HStack>
      <QuestionnaireItem name="scope" required>
        <QuestionnaireTitle>Which files can the agent edit?</QuestionnaireTitle>
        <QuestionnaireDescription>
          The active question lives in the host's state, shown above.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="file">The one file named in the issue</QuestionnaireChoice>
          <QuestionnaireChoice value="folder">Every file in its folder</QuestionnaireChoice>
          <QuestionnaireChoice value="package">Anything in the package</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="checks" required>
        <QuestionnaireTitle>Which checks have to pass?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="lint">Lint</QuestionnaireChoice>
          <QuestionnaireChoice value="tests">Lint and tests</QuestionnaireChoice>
          <QuestionnaireChoice value="build">Lint, tests and a build</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="output" required>
        <QuestionnaireTitle>How should the agent report back?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="note">A short note</QuestionnaireChoice>
          <QuestionnaireChoice value="list">A list of the changes</QuestionnaireChoice>
          <QuestionnaireChoice value="walkthrough">
            A walkthrough of each change
          </QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Apply settings</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Resume

Restore a saved draft with `defaultItem` on the root, `defaultChecked` on
choices and `defaultValue` on the input. A `type="reset"` button restores those
defaults, the starting item and the skip state.

```tsx
"use client"

import type { FormEvent } from "react"
import { Button } from "@/components/ui/button"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireInput,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  { name: "change", required: true },
  { name: "verification", required: true },
  { name: "notes" },
]

export default function QuestionnaireResume() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Draft saved",
      description: `Rollout: ${answers.get("change") ?? "None"} · Checks: ${
        answers.getAll("verification").join(", ") || "None"
      } · Note: ${answers.get("notes") || "None"}`,
    })
  }

  return (
    <Questionnaire
      defaultItem="verification"
      items={items}
      onReset={() => toast.add({ title: "Back to the saved draft" })}
      onSubmit={handleSubmit}
      xstyle={widths.md}
    >
      <QuestionnaireProgress />
      <QuestionnaireItem name="change" required>
        <QuestionnaireTitle>How should the rename roll out?</QuestionnaireTitle>
        <QuestionnaireDescription>You gave this answer last time.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="gradual" defaultChecked>
            Over several releases
          </QuestionnaireChoice>
          <QuestionnaireChoice value="once">All in one release</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="verification" multiple required>
        <QuestionnaireTitle>How should the agent confirm the rename works?</QuestionnaireTitle>
        <QuestionnaireDescription>You picked these checks last time.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="tests" defaultChecked>
            Run the unit tests
          </QuestionnaireChoice>
          <QuestionnaireChoice value="typecheck" defaultChecked>
            Run tsc --noEmit
          </QuestionnaireChoice>
          <QuestionnaireChoice value="manual">Click through the app by hand</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="notes">
        <QuestionnaireTitle>Anything else the agent should know?</QuestionnaireTitle>
        <QuestionnaireDescription>This note came from the saved draft.</QuestionnaireDescription>
        <QuestionnaireInput
          aria-label="Note from the draft"
          defaultValue="Leave the exported type names as they are."
        />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <Button type="reset" variant="ghost">
          Reset
        </Button>
        <QuestionnaireNext />
        <QuestionnaireSubmit>Save draft</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Conditional items

A `disabled` item leaves the flow: it is skipped by navigation and left out of
progress, validation and the submitted answers.

```tsx
"use client"

import { useMemo, useState, type FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

export default function QuestionnaireConditional() {
  const [runtime, setRuntime] = useState("local")
  const items = useMemo(
    () => [
      { name: "runtime", required: true },
      { name: "size", required: true, disabled: runtime !== "remote" },
      { name: "approval", required: true },
    ],
    [runtime],
  )

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Run setup saved",
      description: `Machine: ${answers.get("runtime")} · Size: ${
        answers.get("size") ?? "Not applicable"
      } · Pause: ${answers.get("approval")}`,
    })
  }

  return (
    <Questionnaire items={items} onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireProgress />
      <QuestionnaireItem name="runtime" required>
        <QuestionnaireTitle>Which machine should the agent use?</QuestionnaireTitle>
        <QuestionnaireDescription>
          Picking a remote machine adds a question about its size.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice
            value="local"
            checked={runtime === "local"}
            onChange={() => setRuntime("local")}
          >
            This computer
          </QuestionnaireChoice>
          <QuestionnaireChoice
            value="remote"
            checked={runtime === "remote"}
            onChange={() => setRuntime("remote")}
          >
            A remote machine
          </QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="size" required disabled={runtime !== "remote"}>
        <QuestionnaireTitle>How large should the machine be?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="small">2 cores, 4 GB</QuestionnaireChoice>
          <QuestionnaireChoice value="medium">4 cores, 16 GB</QuestionnaireChoice>
          <QuestionnaireChoice value="large">16 cores, 64 GB</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="approval" required>
        <QuestionnaireTitle>When should the agent stop and check with you?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="install">Before installing packages</QuestionnaireChoice>
          <QuestionnaireChoice value="push">Before pushing commits</QuestionnaireChoice>
          <QuestionnaireChoice value="never">Never, run to the end</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Save setup</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Navigation state

The actions stay enabled by default, so pressing Next on an unanswered item
shows its error. To disable one until the item is answered, track the status
with the item's `onStatusChange` and pass `disabled` to the action:

```tsx
const [status, setStatus] = useState<QuestionnaireItemStatus>("unanswered")

<QuestionnaireItem name="permission" required onStatusChange={setStatus}>
  …
</QuestionnaireItem>
<QuestionnaireActions>
  <QuestionnaireNext disabled={status === "unanswered"} />
</QuestionnaireActions>
```

Set `disabled` on the action, not on the element its `render` returns. The
action reads the prop to drop its `Enter` shortcut, so a button disabled only
in `render` keeps `aria-keyshortcuts="Enter"`.

```tsx
"use client"

import { useState, type FormEvent } from "react"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
  type QuestionnaireItemStatus,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  { name: "permission", required: true },
  { name: "verification", required: true },
]

export default function QuestionnaireNavigationState() {
  const [item, setItem] = useState("permission")
  const [statuses, setStatuses] = useState<Record<string, QuestionnaireItemStatus>>({})
  const unanswered = (statuses[item] ?? "unanswered") === "unanswered"

  function track(name: string) {
    return (status: QuestionnaireItemStatus) =>
      setStatuses((current) => ({ ...current, [name]: status }))
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Limits saved",
      description: `May change: ${answers.get("permission")} · Must pass: ${answers.get("verification")}`,
    })
  }

  return (
    <Questionnaire
      item={item}
      items={items}
      onItemChange={setItem}
      onSubmit={handleSubmit}
      xstyle={widths.md}
    >
      <QuestionnaireProgress />
      <QuestionnaireItem name="permission" required onStatusChange={track("permission")}>
        <QuestionnaireTitle>How much may the agent change?</QuestionnaireTitle>
        <QuestionnaireDescription>
          Next is disabled until you pick an answer.
        </QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="source">Source files</QuestionnaireChoice>
          <QuestionnaireChoice value="tests">Source and test files</QuestionnaireChoice>
          <QuestionnaireChoice value="config">Source, tests and config</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="verification" required onStatusChange={track("verification")}>
        <QuestionnaireTitle>What has to pass before the agent stops?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="tests">Unit tests</QuestionnaireChoice>
          <QuestionnaireChoice value="types">Unit tests and types</QuestionnaireChoice>
          <QuestionnaireChoice value="visual">
            Unit tests, types and a visual check
          </QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireNext disabled={unanswered} />
        <QuestionnaireSubmit disabled={unanswered}>Save limits</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Custom progress

`QuestionnaireProgress` reads `Question 1 of 3` by default. Pass `render` to
draw something else from `current` and `total`. It keeps its `progressbar`
role and values either way.

```tsx
"use client"

import type { FormEvent } from "react"
import * as stylex from "@stylexjs/stylex"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { HStack } from "@/components/ui/stack"
import { toast } from "@/components/ui/toast"
import { color, duration, ease, radius, shadow, space } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"

const styles = stylex.create({
  progress: {
    display: "flex",
    flexDirection: "column",
    gap: space.s2,
    width: "100%",
  },
  segment: {
    flexGrow: 1,
    height: space.s1_5,
    borderRadius: radius.full,
    backgroundColor: color.muted,
    boxShadow: shadow.groove,
    transitionProperty: "background-color",
    transitionDuration: duration.color,
    transitionTimingFunction: ease.standard,
  },
  segmentDone: { backgroundColor: color.primary },
})

const items = [
  { name: "scope", required: true },
  { name: "strategy", required: true },
  { name: "tests", required: true },
  { name: "delivery", required: true },
]

export default function QuestionnaireProgressDemo() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Plan ready",
      description: items.map(({ name }) => answers.get(name)).join(" · "),
    })
  }

  return (
    <Questionnaire items={items} onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireProgress
        xstyle={styles.progress}
        render={(props, state) => (
          <div {...props}>
            <HStack gap={1} aria-hidden="true">
              {Array.from({ length: state.total }, (_, index) => (
                <span
                  key={index}
                  {...stylex.props(styles.segment, index < state.current && styles.segmentDone)}
                />
              ))}
            </HStack>
            <span>
              Step {state.current} of {state.total}
            </span>
          </div>
        )}
      />
      <QuestionnaireItem name="scope" required>
        <QuestionnaireTitle>How big is the task?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="hours">A few hours</QuestionnaireChoice>
          <QuestionnaireChoice value="days">A few days</QuestionnaireChoice>
          <QuestionnaireChoice value="weeks">Several weeks</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="strategy" required>
        <QuestionnaireTitle>How should the history look?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="single">One commit</QuestionnaireChoice>
          <QuestionnaireChoice value="steps">One commit per step</QuestionnaireChoice>
          <QuestionnaireChoice value="squash">Squashed when it merges</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="tests" required>
        <QuestionnaireTitle>What should the agent test?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="changed">The changed code</QuestionnaireChoice>
          <QuestionnaireChoice value="package">The affected package</QuestionnaireChoice>
          <QuestionnaireChoice value="everything">Everything</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="delivery" required>
        <QuestionnaireTitle>How should it ship?</QuestionnaireTitle>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="diff">As a diff to review</QuestionnaireChoice>
          <QuestionnaireChoice value="commits">As local commits</QuestionnaireChoice>
          <QuestionnaireChoice value="branch">As a pushed branch</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Finish</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Animated items

An inactive item is `display: none`, so a keyframe animation on the item
replays each time it becomes active. Animate the entry only; the item leaving
is hidden at once.

```tsx
"use client"

import type { FormEvent } from "react"
import * as stylex from "@stylexjs/stylex"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireDescription,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { duration, ease, space } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"

const enter = stylex.keyframes({
  from: { opacity: 0, transform: `translateY(${space.s2})` },
  to: { opacity: 1, transform: "none" },
})

const styles = stylex.create({
  item: {
    animationName: enter,
    animationDuration: {
      default: duration.panel,
      "@media (prefers-reduced-motion: reduce)": "0s",
    },
    animationTimingFunction: ease.out,
  },
})

const items = [
  { name: "task", required: true },
  { name: "review", required: true },
  { name: "delivery", required: true },
]

export default function QuestionnaireAnimated() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Run settings saved",
      description: items.map(({ name }) => answers.get(name)).join(" · "),
    })
  }

  return (
    <Questionnaire items={items} onSubmit={handleSubmit} xstyle={widths.md}>
      <QuestionnaireProgress />
      <QuestionnaireItem name="task" required xstyle={styles.item}>
        <QuestionnaireTitle>Which job is this run for?</QuestionnaireTitle>
        <QuestionnaireDescription>Pick one job per run.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="investigate">Investigate a bug report</QuestionnaireChoice>
          <QuestionnaireChoice value="upgrade">Upgrade a dependency</QuestionnaireChoice>
          <QuestionnaireChoice value="document">Write the missing docs</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="review" required xstyle={styles.item}>
        <QuestionnaireTitle>How should the agent check its work?</QuestionnaireTitle>
        <QuestionnaireDescription>Pick how far the checks go.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="types">Type check only</QuestionnaireChoice>
          <QuestionnaireChoice value="unit">Type check and unit tests</QuestionnaireChoice>
          <QuestionnaireChoice value="e2e">Every test, end to end</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireItem name="delivery" required xstyle={styles.item}>
        <QuestionnaireTitle>Where should the result go?</QuestionnaireTitle>
        <QuestionnaireDescription>Pick where the agent hands off.</QuestionnaireDescription>
        <QuestionnaireChoices>
          <QuestionnaireChoice value="comment">A comment on the issue</QuestionnaireChoice>
          <QuestionnaireChoice value="branch">A pushed branch</QuestionnaireChoice>
          <QuestionnaireChoice value="draft">A draft pull request</QuestionnaireChoice>
        </QuestionnaireChoices>
        <QuestionnaireError />
      </QuestionnaireItem>
      <QuestionnaireActions>
        <QuestionnairePrevious />
        <QuestionnaireNext />
        <QuestionnaireSubmit>Save settings</QuestionnaireSubmit>
      </QuestionnaireActions>
    </Questionnaire>
  )
}
```

## Card

Wrap a [Card](https://www.arene.style/docs/components/card) in the questionnaire to give the flow a
header and a footer tray. The progress can sit in the header's action slot,
since it reads the questionnaire rather than an item.

```tsx
"use client"

import type { FormEvent } from "react"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Questionnaire,
  QuestionnaireActions,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"
import { widths } from "@/theme/widths"

const items = [
  {
    name: "task",
    required: true,
    choices: [{ value: "crash" }, { value: "timeout" }, { value: "links" }],
  },
  {
    name: "output",
    required: true,
    choices: [{ value: "notes" }, { value: "patch" }, { value: "pr" }],
  },
] as const

export default function QuestionnaireCard() {
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    toast.add({
      title: "Task assigned",
      description: `Issue: ${answers.get("task")} · Hand back: ${answers.get("output")}`,
    })
  }

  return (
    <Questionnaire items={items} shortcuts="numbers" onSubmit={handleSubmit} xstyle={widths.md}>
      <Card>
        <CardHeader>
          <CardTitle>Assign a task</CardTitle>
          <CardDescription>Answer two questions to brief the agent.</CardDescription>
          <CardAction>
            <QuestionnaireProgress />
          </CardAction>
        </CardHeader>
        <CardContent>
          <QuestionnaireItem name="task" required>
            <QuestionnaireTitle>Which issue should the agent pick up?</QuestionnaireTitle>
            <QuestionnaireChoices>
              <QuestionnaireChoice value="crash">The crash on sign-out</QuestionnaireChoice>
              <QuestionnaireChoice value="timeout">The CSV export timeout</QuestionnaireChoice>
              <QuestionnaireChoice value="links">The broken links in the docs</QuestionnaireChoice>
            </QuestionnaireChoices>
            <QuestionnaireError />
          </QuestionnaireItem>
          <QuestionnaireItem name="output" required>
            <QuestionnaireTitle>What should it hand back?</QuestionnaireTitle>
            <QuestionnaireChoices>
              <QuestionnaireChoice value="notes">Written findings</QuestionnaireChoice>
              <QuestionnaireChoice value="patch">A patch with tests</QuestionnaireChoice>
              <QuestionnaireChoice value="pr">A pull request</QuestionnaireChoice>
            </QuestionnaireChoices>
            <QuestionnaireError />
          </QuestionnaireItem>
        </CardContent>
        <CardFooter>
          <QuestionnaireActions>
            <QuestionnairePrevious />
            <QuestionnaireNext />
            <QuestionnaireSubmit>Assign task</QuestionnaireSubmit>
          </QuestionnaireActions>
        </CardFooter>
      </Card>
    </Questionnaire>
  )
}
```

## Dialog

Inside a [Dialog](https://www.arene.style/docs/components/dialog), closing cancels the whole flow and
belongs to the dialog, while Skip answers one item. Keep the two apart.

```tsx
"use client"

import { useState, type FormEvent } from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Questionnaire,
  QuestionnaireChoice,
  QuestionnaireChoices,
  QuestionnaireError,
  QuestionnaireItem,
  QuestionnaireNext,
  QuestionnairePrevious,
  QuestionnaireProgress,
  QuestionnaireSubmit,
  QuestionnaireTitle,
} from "@/components/ui/questionnaire"
import { toast } from "@/components/ui/toast"

const items = [
  { name: "reach", required: true },
  { name: "tests", required: true },
]

export default function QuestionnaireDialog() {
  const [open, setOpen] = useState(false)

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const answers = new FormData(event.currentTarget)
    setOpen(false)
    toast.add({
      title: "Answers sent",
      description: `Packages: ${answers.get("reach")} · Tests: ${answers.get("tests")}`,
    })
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger render={<Button variant="outline" />}>Answer the agent</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>The agent has two questions</DialogTitle>
          <DialogDescription>Your answers decide how far the run can reach.</DialogDescription>
        </DialogHeader>
        <Questionnaire items={items} onSubmit={handleSubmit}>
          <QuestionnaireProgress />
          <QuestionnaireItem name="reach" required>
            <QuestionnaireTitle>May the agent edit other packages?</QuestionnaireTitle>
            <QuestionnaireChoices>
              <QuestionnaireChoice value="none">No, stay in this package</QuestionnaireChoice>
              <QuestionnaireChoice value="shared">Only the shared utilities</QuestionnaireChoice>
              <QuestionnaireChoice value="any">Yes, any package</QuestionnaireChoice>
            </QuestionnaireChoices>
            <QuestionnaireError />
          </QuestionnaireItem>
          <QuestionnaireItem name="tests" required>
            <QuestionnaireTitle>Should the agent write new tests?</QuestionnaireTitle>
            <QuestionnaireChoices>
              <QuestionnaireChoice value="none">No new tests</QuestionnaireChoice>
              <QuestionnaireChoice value="unit">Unit tests</QuestionnaireChoice>
              <QuestionnaireChoice value="both">Unit and integration tests</QuestionnaireChoice>
            </QuestionnaireChoices>
            <QuestionnaireError />
          </QuestionnaireItem>
          <DialogFooter>
            <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
            <QuestionnairePrevious />
            <QuestionnaireNext />
            <QuestionnaireSubmit>Send answers</QuestionnaireSubmit>
          </DialogFooter>
        </Questionnaire>
      </DialogContent>
    </Dialog>
  )
}
```

## Accessibility

- Each item is a `fieldset` and `QuestionnaireTitle` is its `legend`. If you
  render the title as another element, give it an `id` and pass that to the
  item's `aria-labelledby`.
- The description and the active error are linked to the item with
  `aria-describedby`. An invalid item and its answers carry `aria-invalid`.
- Choices are native radios and checkboxes, visually hidden inside the card
  that draws them, so the whole card is the label.
- Progress is a named `progressbar` with its current, minimum and maximum
  values.
- Moving to an item focuses it, and a failed validation focuses its first
  answer.

| Key                      | Behaviour                                                                                         |
| ------------------------ | ------------------------------------------------------------------------------------------------- |
| `Tab`                    | Moves between the answers and the visible actions                                                 |
| `ArrowUp` / `ArrowDown`  | Moves between the answers. A radio is selected as it is reached                                   |
| `ArrowLeft`              | Goes to the previous item, outside a radio or a text field                                        |
| `ArrowRight`             | Goes to the next item once the active one is answered or skipped, outside a radio or a text field |
| `Space`                  | Selects a radio, toggles a checkbox or presses the focused action                                 |
| `Enter`                  | Continues from a selected choice or a filled input                                                |
| `Command/Ctrl` + `Enter` | Validates and continues from anywhere in the questionnaire, or submits the last item              |

Shortcut keys and arrow navigation pause while you type in a text field.
Calling `preventDefault()` in the root's `onKeyDown` turns the key handling off.

## API reference

Every part wraps the `@shadcn/react` part of the same name and accepts its
props; the [headless Questionnaire reference](https://ui.shadcn.com/docs/react/questionnaire#api-reference)
has the full list. Every part also takes `xstyle`, `className` and `style`.
Pass `render` to replace a part's element, except on `Questionnaire` and
`QuestionnaireItem`, which always render a `form` and a `fieldset`. A function
`render` receives the part's state as its second argument.

### Questionnaire

| Prop           | Type                                     | Default            |
| -------------- | ---------------------------------------- | ------------------ |
| `items`        | `readonly QuestionnaireItemDefinition[]` | —                  |
| `item`         | `string`                                 | —                  |
| `defaultItem`  | `string`                                 | first enabled item |
| `onItemChange` | `(item: string) => void`                 | —                  |
| `shortcuts`    | `"letters" \| "numbers"`                 | —                  |
| `noValidate`   | `boolean`                                | `true`             |

`noValidate` keeps the browser's own validation bubbles away, so errors come
from `QuestionnaireError`. A questionnaire cannot sit inside another form.

### QuestionnaireItem

| Prop             | Type                                        | Default  |
| ---------------- | ------------------------------------------- | -------- |
| `name`           | `string`                                    | required |
| `required`       | `boolean`                                   | `false`  |
| `multiple`       | `boolean`                                   | `false`  |
| `disabled`       | `boolean`                                   | `false`  |
| `invalid`        | `boolean`                                   | `false`  |
| `onStatusChange` | `(status: QuestionnaireItemStatus) => void` | —        |

The title's spacing depends on whether the item has a description, which the
item finds by looking for a `QuestionnaireDescription` among its direct
children.

### QuestionnaireChoice

| Prop             | Type                                   | Default  |
| ---------------- | -------------------------------------- | -------- |
| `value`          | `string`                               | required |
| `checked`        | `boolean`                              | —        |
| `defaultChecked` | `boolean`                              | `false`  |
| `disabled`       | `boolean`                              | `false`  |
| `onChange`       | `ChangeEventHandler<HTMLInputElement>` | —        |

Its children are the answer's label. Add a `QuestionnaireChoiceDescription`
after the label for a second, muted line. The card draws the radio or checkbox
and the shortcut key itself.

### QuestionnaireInput

| Prop           | Type                                   | Default  |
| -------------- | -------------------------------------- | -------- |
| `value`        | `string`                               | —        |
| `defaultValue` | `string`                               | —        |
| `type`         | `QuestionnaireInputType`               | `"text"` |
| `disabled`     | `boolean`                              | `false`  |
| `onChange`     | `ChangeEventHandler<HTMLInputElement>` | —        |

It renders an [Input](https://www.arene.style/docs/components/input), so it dims while disabled and
shows the invalid ring when its item fails validation.

### QuestionnaireError

Hidden until its item fails validation. Its children replace the default
message.

### Navigation actions

`QuestionnairePrevious`, `QuestionnaireSkip`, `QuestionnaireNext` and
`QuestionnaireSubmit` render a [Button](https://www.arene.style/docs/components/button) and take its
`variant` and `size`. `QuestionnaireSubmit` is `type="submit"`; the others are
`type="button"`. Children replace the default label.

| Prop      | Type            | Default                                             |
| --------- | --------------- | --------------------------------------------------- |
| `variant` | `ButtonVariant` | `"outline"` for Previous and Skip, else `"default"` |
| `size`    | `ButtonSize`    | `"default"`                                         |

The render state holds `visible`, `disabled`, `shortcut` and the active item's
`status`.

### questionnaireStyles

The style map behind the component, exported so you can apply the same styles
to other elements.

| Key                 | What it is                                                |
| ------------------- | --------------------------------------------------------- |
| `root`              | The form's column and gap                                 |
| `progress`          | The progress text                                         |
| `item`              | The item's column and gap                                 |
| `title`             | The question's type                                       |
| `description`       | The muted line under the question                         |
| `choices`           | The grid of answers                                       |
| `choice`            | The answer card, `fieldStyles.card` laid out as a row     |
| `choiceChecked`     | The card's selected edge, `fieldStyles.cardChecked`       |
| `choiceFocused`     | The card's keyboard-focus ring, `fieldStyles.cardFocused` |
| `choiceLabel`       | The column that holds an answer's label and description   |
| `choiceDescription` | An answer's second line                                   |
| `input`             | The freeform field, the same as `inputStyles.base`        |
| `error`             | The validation message, the same as `fieldStyles.error`   |
| `actions`           | The three-column grid of actions                          |

### Data attributes

The headless parts write their state as data attributes. A boolean is present
while it is true, and the others carry their value.

| Part             | State attributes                                                                                |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| the root         | `data-current`, `data-total`, `data-first`, `data-last`, `data-shortcuts`                       |
| the progress     | `data-current`, `data-total`, `data-first`, `data-last`                                         |
| each item        | `data-active`, `data-status`, `data-required`, `data-multiple`, `data-disabled`, `data-invalid` |
| the answer grid  | `data-shortcuts`                                                                                |
| each answer card | `data-type`, `data-checked`, `data-unchecked`, `data-disabled`, `data-invalid`, `data-shortcut` |
| the input        | `data-filled`, `data-empty`, `data-disabled`, `data-invalid`                                    |
| the error        | `data-invalid`                                                                                  |
| each action      | `data-visible`, `data-hidden`, `data-disabled`, `data-shortcut`, `data-status`                  |

`data-shortcuts` holds the `shortcuts` mode and a card's `data-shortcut` its
key. An action's `data-shortcut` is `Enter` on Next and Submit while they are
visible and enabled, and its `data-status` is the active item's status.

| Attribute                                      | On                       |
| ---------------------------------------------- | ------------------------ |
| `data-slot="questionnaire"`                    | the form                 |
| `data-slot="questionnaire-progress"`           | the progress             |
| `data-slot="questionnaire-item"`               | each item                |
| `data-slot="questionnaire-title"`              | the title                |
| `data-slot="questionnaire-description"`        | the description          |
| `data-slot="questionnaire-choices"`            | the answer grid          |
| `data-slot="questionnaire-choice"`             | each answer card         |
| `data-slot="questionnaire-choice-description"` | an answer's second line  |
| `data-slot="questionnaire-input"`              | the freeform input       |
| `data-slot="questionnaire-error"`              | the error                |
| `data-slot="questionnaire-actions"`            | the action row           |
| `data-slot="questionnaire-previous"`           | the Previous button      |
| `data-slot="questionnaire-skip"`               | the Skip button          |
| `data-slot="questionnaire-next"`               | the Next button          |
| `data-slot="questionnaire-submit"`             | the Submit button        |
| `data-variant`, `data-size`                    | each action, from Button |
