← Components

Communication

Questionnaire

An agent asks the user to decide, one question at a time. Choices take letter shortcuts; questions slide in the direction of travel; on submit the answers collapse into one Marker.

Examples and variants

Three questions

Press A, B or C to choose.

x

How should it feel?

Example
function QuestionnaireSteps() {
  return (
    <Questionnaire
      questions={[
        { id: "tone", title: "How should it feel?", type: "single", choices: ["Calm", "Playful", "Serious"] },
        { id: "where", title: "Where will it live?", type: "multiple", choices: ["Web", "iOS", "Android"] },
        { id: "notes", title: "Anything else?", type: "text", optional: true },
      ]}
    />
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/questionnaire.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react class-variance-authority cn lucide-react
  2. Copy these 5 files to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/button.tsxbutton
      components/ui/button.tsx
      "use client"
      
      import { useRef, useState } from "react"
      import { Button as ButtonPrimitive } from "@base-ui/react/button"
      import { CheckIcon, XIcon } from "lucide-react"
      import { tokenMs } from "@/lib/motion/token-ms"
      import { cva, type VariantProps } from "class-variance-authority"
      import { cn } from "cn"
      
      // Minimal: no strokes on controls (DESIGN.md rule 11), token sizes, token focus ring,
      // liquid press squash instead of shadcn's translate-y nudge.
      // Every visual spec reads a component token (styles/tokens/components.css, --button-*).
      // Sizes: sm | md | lg (default = md). Variants: primary (default) | secondary | outline | ghost | link.
      const filled = {
        primary:
          "bg-(--button-primary-container) text-(--button-primary-label) hover:bg-(--button-primary-container-hover) active:bg-(--button-primary-container-pressed)",
        secondary:
          "bg-(--button-secondary-container) text-(--button-secondary-label) hover:bg-(--button-secondary-container-hover) active:bg-(--button-secondary-container-pressed) aria-expanded:bg-(--button-secondary-container-hover)",
      }
      
      const buttonVariants = cva(
        "liquid-press group/button relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-(--button-corner) border-solid border-(length:--button-stroke-width) border-(--stroke-color-default) bg-clip-padding text-(length:--button-label-size) [font-weight:var(--button-label-weight)] whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:bg-(--button-container-disabled) disabled:text-(--button-label-disabled) disabled:shadow-none aria-invalid:shadow-(--focus-ring-invalid) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--button-icon-size)",
        {
          variants: {
            variant: {
              primary: filled.primary,
              default: filled.primary,
              secondary: filled.secondary,
              outline:
                "bg-(--button-outline-container) text-(--button-secondary-label) shadow-(--button-outline-elevation) hover:bg-(--button-outline-container-hover) active:bg-(--button-outline-container-pressed) aria-expanded:bg-(--button-outline-container-hover)",
              ghost: "text-(--button-secondary-label) hover:bg-(--button-ghost-container-hover) active:bg-(--button-ghost-container-pressed) aria-expanded:bg-(--button-ghost-container-hover) disabled:bg-transparent",
              destructive: "",
              link: "text-(--button-link-label) underline-offset-4 hover:underline disabled:bg-transparent",
            },
            size: {
              xs: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-xs) gap-(--button-gap-sm) px-(--button-padding-x-xs) text-(length:--button-label-size-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              sm: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-sm) gap-(--button-gap-sm) px-(--button-padding-x-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              md: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)",
              default: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)",
              lg: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-lg) gap-(--button-gap) px-(--button-padding-x-lg) has-data-[icon=inline-end]:pe-(--button-padding-x-md) has-data-[icon=inline-start]:ps-(--button-padding-x-md) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)",
              icon: "size-(--icon-button-size-md) rounded-(--icon-button-corner)",
              "icon-xs": "size-(--button-height-xs) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              "icon-sm": "size-(--icon-button-size-sm) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              "icon-md": "size-(--icon-button-size-md) rounded-(--icon-button-corner)",
              "icon-lg": "size-(--icon-button-size-lg) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)",
            },
            tone: {
              neutral: "",
              danger: "",
              success: "",
            },
          },
          // tone: colour intent on any variant (component-model.md §7). destructive = tone danger.
          compoundVariants: [
            {
              tone: "danger",
              variant: ["primary", "default", "secondary", "outline", "destructive"],
              className:
                "bg-(--button-danger-container) text-(--button-danger-label) shadow-none hover:bg-(--button-danger-container-hover) active:bg-(--button-danger-container-pressed) [--focus-ring-color:var(--color-danger)]",
            },
            {
              tone: "danger",
              variant: ["ghost", "link"],
              className: "text-(--button-danger-label) hover:bg-(--button-danger-container) active:bg-(--button-danger-container-hover) [--focus-ring-color:var(--color-danger)]",
            },
            {
              tone: "success",
              variant: ["primary", "default", "secondary", "outline"],
              className: "bg-(--button-success-container) text-(--button-success-label) shadow-none hover:bg-(--button-success-container-hover) active:bg-(--button-success-container-pressed)",
            },
          ],
          defaultVariants: {
            variant: "primary",
            size: "md",
            tone: "neutral",
          },
        }
      )
      
      type Wash = { id: number; x: number; y: number }
      type Status = "idle" | "loading" | "success" | "error"
      type ButtonProps = ButtonPrimitive.Props &
        VariantProps<typeof buttonVariants> & {
          /**
           * The button shows its own result inside a fixed width: spinner, then a
           * check or a cross. Prefer this to a toast (component-model.md §5).
           */
          status?: Status
          /** "hold": the click only happens after holding for --duration-fill (pointer, Space or Enter). */
          confirm?: "hold"
          /** Screen reader text for the success and error states. */
          statusLabel?: { success?: string; error?: string }
          /** @deprecated use status="loading" */
          loading?: boolean
          /** @deprecated use status="success" */
          success?: boolean
        }
      
      function Button({
        className,
        variant = "primary",
        size = "md",
        tone = "neutral",
        status: statusProp,
        confirm,
        statusLabel,
        loading = false,
        success = false,
        children,
        onClick,
        onPointerUp,
        onPointerDown,
        onPointerLeave,
        onKeyDown,
        onKeyUp,
        ...props
      }: ButtonProps) {
        const status: Status = statusProp ?? (loading ? "loading" : success ? "success" : "idle")
        const busy = status === "loading"
        const [wash, setWash] = useState<Wash | null>(null)
        const [held, setHeld] = useState(false)
        const holdTimer = useRef(0)
        const allowClick = useRef(false)
        const self = useRef<HTMLElement | null>(null)
        const resolvedTone = variant === "destructive" ? "danger" : tone
      
        function startHold(element: HTMLElement) {
          if (confirm !== "hold" || busy) return
          self.current = element
          setHeld(true)
          window.clearTimeout(holdTimer.current)
          holdTimer.current = window.setTimeout(() => {
            setHeld(false)
            allowClick.current = true
            self.current?.click()
            allowClick.current = false
          }, tokenMs("--duration-fill", element))
        }
      
        function stopHold() {
          if (confirm !== "hold") return
          setHeld(false)
          window.clearTimeout(holdTimer.current)
        }
      
        function handleClick(event: Parameters<NonNullable<ButtonProps["onClick"]>>[0]) {
          if (busy || (confirm === "hold" && !allowClick.current)) {
            event.preventDefault()
            return
          }
          onClick?.(event)
        }
      
        function handlePointerUp(event: Parameters<NonNullable<ButtonProps["onPointerUp"]>>[0]) {
          onPointerUp?.(event)
          stopHold()
          if (event.defaultPrevented || busy || confirm === "hold") return
          if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
          const motion = event.currentTarget.closest<HTMLElement>("[data-motion]")?.dataset.motion
          if (motion === "calm" || motion === "still") return
          const rect = event.currentTarget.getBoundingClientRect()
          setWash({
            id: Date.now(),
            x: event.clientX - rect.left,
            y: event.clientY - rect.top,
          })
        }
      
        const showResult = status === "success" || status === "error"
      
        return (
          <ButtonPrimitive
            data-slot="button"
            data-icon={typeof size === "string" && size.startsWith("icon") ? "" : undefined}
            data-tone={resolvedTone}
            data-status={status}
            data-confirm={confirm}
            aria-busy={busy || undefined}
            aria-disabled={busy || undefined}
            {...props}
            className={cn(
              buttonVariants({ variant, size, tone: resolvedTone, className }),
              status === "error" && "animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)]"
            )}
            onClick={handleClick}
            onPointerUp={handlePointerUp}
            onPointerDown={(event) => {
              onPointerDown?.(event)
              if (event.button === 0) startHold(event.currentTarget)
            }}
            onPointerLeave={(event) => {
              onPointerLeave?.(event)
              stopHold()
            }}
            onKeyDown={(event) => {
              onKeyDown?.(event)
              if (confirm === "hold" && (event.key === " " || event.key === "Enter") && !event.repeat) {
                startHold(event.currentTarget)
              }
            }}
            onKeyUp={(event) => {
              onKeyUp?.(event)
              if (event.key === " " || event.key === "Enter") stopHold()
            }}
          >
            {confirm === "hold" ? (
              <span
                aria-hidden
                data-held={held ? "" : undefined}
                className="hold-fill pointer-events-none absolute inset-y-0 left-0 w-full bg-current opacity-20"
              />
            ) : null}
            <span
              className={cn(
                "button-label relative inline-flex items-center justify-center gap-[inherit]",
                (busy || showResult) &&
                  "opacity-0 blur-(--motion-blur-enter) transition-[opacity,filter] duration-(--duration-fast) ease-(--ease-out)"
              )}
            >
              {children}
              {confirm === "hold" ? <span className="sr-only">(hold to confirm)</span> : null}
            </span>
            {showResult ? (
              <span className="button-success absolute inset-0 inline-flex items-center justify-center" role="status">
                <span className="sr-only">
                  {status === "success" ? statusLabel?.success ?? "Done" : statusLabel?.error ?? "Failed"}
                </span>
                {status === "success" ? <CheckIcon aria-hidden /> : <XIcon aria-hidden />}
              </span>
            ) : null}
            {busy ? (
              <span className="absolute inset-0 inline-flex items-center justify-center gap-inline-xs">
                <span className="sr-only">Loading</span>
                {[0, 1, 2].map((dot) => (
                  <span
                    key={dot}
                    aria-hidden
                    className="size-inline-xs rounded-full bg-current animate-[isotope-pulse_var(--duration-pulse)_var(--ease-out)_infinite]"
                    style={{ animationDelay: `calc(var(--duration-stagger) * ${dot})` }}
                  />
                ))}
              </span>
            ) : null}
            {wash ? (
              <span
                key={wash.id}
                aria-hidden
                onAnimationEnd={() => setWash(null)}
                className="pointer-events-none absolute size-[calc(var(--size-control-lg)*4)] rounded-full bg-current animate-[isotope-wash_var(--duration-settle)_var(--ease-out)_both]"
                style={{ left: wash.x, top: wash.y }}
              />
            ) : null}
          </ButtonPrimitive>
        )
      }
      
      export { Button, buttonVariants }
      export type { ButtonProps }
      
    • components/ui/spinner.tsxspinner
      components/ui/spinner.tsx
      import * as React from "react"
      import { CheckIcon } from "lucide-react"
      import { cn } from "cn"
      
      /*
        Spinner: a short, unknown wait. Three buoyant dots (or a ring). When the
        work succeeds, set done: the dots gather into the centre and pop into a
        check. Sizes follow the icon tokens.
      */
      const sizes = { sm: "h-icon-sm", md: "h-icon-md", lg: "h-icon-lg" }
      
      function Spinner({
        className,
        size = "md",
        variant = "dots",
        done = false,
        label = "Loading",
        ...props
      }: React.ComponentProps<"span"> & {
        size?: keyof typeof sizes
        /** dots (default), ring, wave, orbit, morph, typing. All resolve into the same check. */
        variant?: "dots" | "ring" | "wave" | "orbit" | "morph" | "typing"
        done?: boolean
        label?: string
      }) {
        return (
          <span
            role="status"
            data-slot="spinner"
            data-done={done || undefined}
            className={cn("spinner relative inline-flex items-center justify-center", sizes[size], className)}
            {...props}
          >
            <span className="sr-only">{done ? "Done" : label}</span>
            {variant === "dots" || variant === "typing" ? (
              <span aria-hidden data-variant={variant} className="spinner-dots inline-flex h-full items-center gap-[0.2em]">
                {[0, 1, 2].map((dot) => (
                  <span key={dot} className="spinner-dot aspect-square h-[28%] rounded-full bg-current" style={{ "--dot": dot } as React.CSSProperties} />
                ))}
              </span>
            ) : variant === "wave" ? (
              <span aria-hidden className="spinner-dots inline-flex h-full items-center gap-[0.15em]">
                {[0, 1, 2, 3].map((bar) => (
                  <span key={bar} className="spinner-bar h-full w-[0.18em] rounded-full bg-current" style={{ "--dot": bar } as React.CSSProperties} />
                ))}
              </span>
            ) : variant === "orbit" ? (
              <span aria-hidden className="spinner-dots spinner-orbit relative aspect-square h-full">
                <span className="absolute top-0 left-1/2 aspect-square h-[30%] -translate-x-1/2 rounded-full bg-current" />
              </span>
            ) : variant === "morph" ? (
              <span aria-hidden className="spinner-dots spinner-morph aspect-square h-[70%] bg-current" />
            ) : (
              <span aria-hidden className="spinner-ring aspect-square h-full rounded-full" />
            )}
            <CheckIcon aria-hidden className="spinner-check absolute aspect-square h-full w-auto" strokeWidth={2.5} />
          </span>
        )
      }
      
      export { Spinner }
      
    • components/ui/marker.tsxmarker
      components/ui/marker.tsx
      "use client"
      
      import * as React from "react"
      import { CheckIcon, XIcon } from "lucide-react"
      import { cn } from "cn"
      import { Spinner } from "@/components/ui/spinner"
      
      /*
        Marker: an inline status or note in a conversation ("Thinking…",
        "Explored 4 files", "Conversation compacted"). While working, the text
        shimmers; when done, the spinner pops into its final icon and the text rolls
        to the past tense. variant="divider" centres a label between turns.
        (Thinking status is Marker status="working".)
      */
      function Marker({
        status = "idle",
        icon,
        children,
        done,
        variant = "inline",
        className,
      }: {
        status?: "idle" | "working" | "done" | "error"
        icon?: React.ReactNode
        /** Label while working, e.g. "Exploring files". */
        children: React.ReactNode
        /** Label once done, e.g. "Explored 4 files". Rolls in. */
        done?: React.ReactNode
        variant?: "inline" | "divider"
        className?: string
      }) {
        const finished = status === "done" || status === "error"
        const mark =
          status === "working" ? (
            <Spinner size="sm" label="Working" />
          ) : status === "done" ? (
            <CheckIcon className="marker-pop size-(--size-icon-sm) text-(--color-success-fg)" aria-hidden />
          ) : status === "error" ? (
            <XIcon className="marker-pop size-(--size-icon-sm) text-(--color-danger-fg)" aria-hidden />
          ) : (
            icon
          )
        return (
          <div
            role="status"
            data-slot="marker"
            data-status={status}
            data-variant={variant}
            className={cn(
              "flex items-center gap-2 text-sm text-(--marker-label)",
              variant === "divider" && "justify-center",
              className
            )}
          >
            <span className={cn("inline-flex items-center gap-2", variant === "divider" && "rounded-(--shape-full) bg-(--marker-divider) px-3 py-1 text-caption")}>
              {mark ? <span className="inline-flex shrink-0 [&_svg]:size-(--size-icon-sm)">{mark}</span> : null}
              <span className="relative inline-grid overflow-hidden">
                <span data-position={finished && done ? "above" : "at"} className={cn("label-roll col-start-1 row-start-1", status === "working" && "marker-shimmer")}>
                  {children}
                </span>
                {done ? (
                  <span data-position={finished ? "at" : "below"} aria-hidden={!finished} className="label-roll col-start-1 row-start-1">
                    {done}
                  </span>
                ) : null}
              </span>
            </span>
          </div>
        )
      }
      
      export { Marker }
      
    • components/ui/progress.tsxprogress
      components/ui/progress.tsx
      "use client"
      
      import * as React from "react"
      import { Progress as ProgressPrimitive } from "@base-ui/react/progress"
      import { cn } from "cn"
      
      /*
        Progress: how much of a task is done (component-model.md §3 merges meters
        into it). shape="bar" or "ring". The fill moves with a small overshoot and
        its leading edge is rounded like liquid. `thresholds` turns the fill
        warning and danger past those values (context meters, character limits).
        value={null} is indeterminate: a short blob slides across.
      */
      type Thresholds = { warning?: number; danger?: number }
      
      function toneFor(value: number | null, thresholds?: Thresholds) {
        if (value === null || !thresholds) return "neutral"
        if (thresholds.danger !== undefined && value >= thresholds.danger) return "danger"
        if (thresholds.warning !== undefined && value >= thresholds.warning) return "warning"
        return "neutral"
      }
      
      function Progress({
        className,
        value,
        shape = "bar",
        thresholds,
        label,
        showValue = false,
        size = 40,
        ...props
      }: Omit<ProgressPrimitive.Root.Props, "value"> & {
        value: number | null
        shape?: "bar" | "ring"
        thresholds?: Thresholds
        label?: React.ReactNode
        showValue?: boolean
        /** Ring diameter in px. */
        size?: number
      }) {
        const tone = toneFor(value, thresholds)
        const complete = value !== null && value >= 100
      
        if (shape === "ring") {
          const stroke = 4 // matches --progress-ring-stroke
          const r = (size - stroke) / 2
          const c = 2 * Math.PI * r
          const pct = value === null ? 25 : Math.max(0, Math.min(100, value))
          return (
            <ProgressPrimitive.Root
              value={value}
              data-slot="progress"
              data-shape="ring"
              data-tone={tone}
              data-complete={complete || undefined}
              className={cn("progress inline-flex items-center gap-inline-sm", className)}
              {...props}
            >
              <span className="relative inline-flex" style={{ width: size, height: size }}>
                <svg aria-hidden width={size} height={size} viewBox={`0 0 ${size} ${size}`} className={cn("-rotate-90", value === null && "progress-ring-spin")}>
                  <circle cx={size / 2} cy={size / 2} r={r} fill="none" strokeWidth={stroke} className="stroke-(--progress-track)" />
                  <circle
                    cx={size / 2}
                    cy={size / 2}
                    r={r}
                    fill="none"
                    strokeWidth={stroke}
                    strokeLinecap="round"
                    strokeDasharray={c}
                    strokeDashoffset={c * (1 - pct / 100)}
                    className="progress-ring-fill"
                  />
                </svg>
                {showValue && value !== null ? (
                  <span className="absolute inset-0 flex items-center justify-center text-[0.625rem] font-medium tabular-nums">
                    {Math.round(value)}
                  </span>
                ) : null}
              </span>
              {label ? <ProgressPrimitive.Label className="text-sm">{label}</ProgressPrimitive.Label> : null}
            </ProgressPrimitive.Root>
          )
        }
      
        return (
          <ProgressPrimitive.Root
            value={value}
            data-slot="progress"
            data-shape="bar"
            data-tone={tone}
            data-complete={complete || undefined}
            className={cn("progress flex w-full flex-col gap-stack-xs", className)}
            {...props}
          >
            {label || showValue ? (
              <div className="flex items-center justify-between text-sm">
                {label ? <ProgressPrimitive.Label>{label}</ProgressPrimitive.Label> : <span />}
                {showValue ? <ProgressPrimitive.Value className="text-muted-foreground tabular-nums" /> : null}
              </div>
            ) : null}
            <ProgressPrimitive.Track className="relative h-(--progress-track-height) overflow-hidden rounded-(--progress-corner) bg-(--progress-track)">
              <ProgressPrimitive.Indicator className="progress-bar-fill h-full rounded-(--progress-corner)" />
            </ProgressPrimitive.Track>
          </ProgressPrimitive.Root>
        )
      }
      
      export { Progress }
      
    • components/ui/questionnaire.tsxquestionnaire
      components/ui/questionnaire.tsx
      "use client"
      
      import * as React from "react"
      import { CheckIcon } from "lucide-react"
      import { cn } from "cn"
      import { Button } from "@/components/ui/button"
      import { Marker } from "@/components/ui/marker"
      import { Progress } from "@/components/ui/progress"
      
      /*
        Questionnaire: an agent asks the user to decide, one question at a time
        (single, multiple, free text, skippable). Questions slide in the direction
        of travel; choices take letter shortcuts (A, B, C). On submit, the answers
        collapse into one Marker so the chat stays tidy.
      */
      type Question = {
        id: string
        title: string
        description?: string
        type: "single" | "multiple" | "text"
        choices?: string[]
        optional?: boolean
      }
      
      function Questionnaire({
        questions,
        onSubmit,
        className,
      }: {
        questions: Question[]
        onSubmit?: (answers: Record<string, string | string[]>) => void
        className?: string
      }) {
        const [step, setStep] = React.useState(0)
        const [dir, setDir] = React.useState(1)
        const [answers, setAnswers] = React.useState<Record<string, string | string[]>>({})
        const [submitted, setSubmitted] = React.useState(false)
        const q = questions[step]
        const answer = answers[q?.id]
        const last = step === questions.length - 1
        const ready = q?.optional || (Array.isArray(answer) ? answer.length > 0 : !!answer)
      
        function choose(choice: string) {
          setAnswers((all) => {
            if (q.type === "multiple") {
              const current = (all[q.id] as string[] | undefined) ?? []
              return { ...all, [q.id]: current.includes(choice) ? current.filter((c) => c !== choice) : [...current, choice] }
            }
            return { ...all, [q.id]: choice }
          })
        }
      
        function go(delta: number) {
          if (delta > 0 && last) {
            setSubmitted(true)
            onSubmit?.(answers)
            return
          }
          setDir(delta)
          setStep((s) => s + delta)
        }
      
        if (submitted) {
          const count = Object.values(answers).filter((a) => (Array.isArray(a) ? a.length : a)).length
          return <Marker status="done" className="questionnaire-done">{`Answered ${count} question${count === 1 ? "" : "s"}`}</Marker>
        }
      
        return (
          <section
            data-slot="questionnaire"
            aria-label="Questions"
            className={cn("flex w-full max-w-md flex-col gap-stack-md rounded-(--shape-lg) bg-(--surface-container-low) p-4", className)}
            onKeyDown={(event) => {
              if (!q.choices || event.target instanceof HTMLTextAreaElement) return
              const index = event.key.toUpperCase().charCodeAt(0) - 65
              if (event.key.length === 1 && index >= 0 && index < q.choices.length) choose(q.choices[index])
            }}
          >
            <Progress value={((step + 1) / questions.length) * 100} aria-label={`Question ${step + 1} of ${questions.length}`} />
            <div key={q.id} data-dir={dir > 0 ? "next" : "prev"} className="question flex flex-col gap-stack-sm">
              <h3 className="text-title">{q.title}</h3>
              {q.description ? <p className="text-sm text-muted-foreground">{q.description}</p> : null}
              {q.type === "text" ? (
                <textarea
                  aria-label={q.title}
                  value={(answer as string) ?? ""}
                  onChange={(event) => setAnswers((all) => ({ ...all, [q.id]: event.target.value }))}
                  className="min-h-20 rounded-(--field-corner-multiline) bg-(--field-container) p-3 text-sm outline-none focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)"
                />
              ) : (
                <div role={q.type === "single" ? "radiogroup" : "group"} aria-label={q.title} className="flex flex-col gap-1.5">
                  {q.choices?.map((choice, index) => {
                    const picked = Array.isArray(answer) ? answer.includes(choice) : answer === choice
                    return (
                      <button
                        key={choice}
                        type="button"
                        role={q.type === "single" ? "radio" : "checkbox"}
                        aria-checked={picked}
                        onClick={() => choose(choice)}
                        className={cn(
                          "liquid-press flex items-center gap-3 rounded-(--question-choice-corner) px-3 py-2 text-start text-sm outline-none focus-visible:shadow-(--focus-ring)",
                          picked ? "bg-(--question-choice-selected)" : "bg-(--question-choice) hover:bg-(--question-choice-hover) active:bg-(--question-choice-pressed)"
                        )}
                      >
                        <kbd className="inline-flex size-6 shrink-0 items-center justify-center rounded-(--shape-xs) bg-(--surface-container-lowest) font-mono text-caption">
                          {String.fromCharCode(65 + index)}
                        </kbd>
                        <span className="flex-1">{choice}</span>
                        {picked ? <CheckIcon aria-hidden className="question-check size-(--size-icon-sm)" /> : null}
                      </button>
                    )
                  })}
                </div>
              )}
            </div>
            <div className="flex items-center justify-between">
              <Button size="sm" variant="ghost" disabled={step === 0} onClick={() => go(-1)}>
                Previous
              </Button>
              <div className="flex gap-2">
                {q.optional ? (
                  <Button size="sm" variant="ghost" onClick={() => go(1)}>
                    Skip
                  </Button>
                ) : null}
                <Button size="sm" disabled={!ready} onClick={() => go(1)}>
                  {last ? "Submit" : "Next"}
                </Button>
              </div>
            </div>
          </section>
        )
      }
      
      export { Questionnaire }
      export type { Question }
      

Imports

What the examples on this page import:

Imports
import { Attachment } from "@/components/ui/attachment"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Bubble, BubbleGroup, BubbleReactions } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import { CodeBlock } from "@/components/ui/code-block"
import { Marker } from "@/components/ui/marker"
import { Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader } from "@/components/ui/message"
import { MessageScroller } from "@/components/ui/message-scroller"
import { PromptInput } from "@/components/ui/prompt-input"
import { Questionnaire } from "@/components/ui/questionnaire"
import { StreamingText } from "@/components/ui/streaming-text"
import { Trace, TraceItem } from "@/components/ui/trace"
import { VoiceInput } from "@/components/ui/voice-input"
import { tokenMs } from "@/lib/motion/token-ms"

Anatomy

  1. 1Progress · Question n of m.
  2. 2Question · Title, description.
  3. 3Choices · --question-choice, --question-choice-selected, --question-choice-corner.
  4. 4Actions · Previous, Skip, Next / Submit.

Props

PropTypeDefaultDescription
questions{ id, title, description?, type, choices?, optional? }[]—type: single, multiple or text.
onSubmit(answers) => void—Called with every answer.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--question-choicevar(--surface-container)oklch(0.965 0.005 95)oklch(0.12 0 0)
--question-choice-selectedvar(--color-bg-selected)color-mix(in oklch, var(--ref-select) 12%, transparent)color-mix(in oklch, var(--ref-select) 16%, transparent)
--question-choice-hovercolor-mix(in oklch, var(--question-choice), var(--on-surface) var(--state-hover-mix))color-mix(in oklch, var(--question-choice), var(--on-surface) var(--state-hover-mix))same
--question-choice-pressedcolor-mix(in oklch, var(--question-choice), var(--on-surface) var(--state-pressed-mix))color-mix(in oklch, var(--question-choice), var(--on-surface) var(--state-pressed-mix))same
--question-choice-cornervar(--shape-md)14pxsame

Motion

TriggerWhat happensTokens
Next / previousThe question slides in from the side you're going.--duration-settle
SubmitCollapses into a Marker.--duration-settle

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • Single choice is a radiogroup; multiple a group of checkboxes.
  • Letter keys pick choices.

Usage

Do

  • Ask only what you need.

Don’t

  • Don't use for long forms.

Code

components/ui/questionnaire.tsx
"use client"

import * as React from "react"
import { CheckIcon } from "lucide-react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import { Marker } from "@/components/ui/marker"
import { Progress } from "@/components/ui/progress"

/*
  Questionnaire: an agent asks the user to decide, one question at a time
  (single, multiple, free text, skippable). Questions slide in the direction
  of travel; choices take letter shortcuts (A, B, C). On submit, the answers
  collapse into one Marker so the chat stays tidy.
*/
type Question = {
  id: string
  title: string
  description?: string
  type: "single" | "multiple" | "text"
  choices?: string[]
  optional?: boolean
}

function Questionnaire({
  questions,
  onSubmit,
  className,
}: {
  questions: Question[]
  onSubmit?: (answers: Record<string, string | string[]>) => void
  className?: string
}) {
  const [step, setStep] = React.useState(0)
  const [dir, setDir] = React.useState(1)
  const [answers, setAnswers] = React.useState<Record<string, string | string[]>>({})
  const [submitted, setSubmitted] = React.useState(false)
  const q = questions[step]
  const answer = answers[q?.id]
  const last = step === questions.length - 1
  const ready = q?.optional || (Array.isArray(answer) ? answer.length > 0 : !!answer)

  function choose(choice: string) {
    setAnswers((all) => {
      if (q.type === "multiple") {
        const current = (all[q.id] as string[] | undefined) ?? []
        return { ...all, [q.id]: current.includes(choice) ? current.filter((c) => c !== choice) : [...current, choice] }
      }
      return { ...all, [q.id]: choice }
    })
  }

  function go(delta: number) {
    if (delta > 0 && last) {
      setSubmitted(true)
      onSubmit?.(answers)
      return
    }
    setDir(delta)
    setStep((s) => s + delta)
  }

  if (submitted) {
    const count = Object.values(answers).filter((a) => (Array.isArray(a) ? a.length : a)).length
    return <Marker status="done" className="questionnaire-done">{`Answered ${count} question${count === 1 ? "" : "s"}`}</Marker>
  }

  return (
    <section
      data-slot="questionnaire"
      aria-label="Questions"
      className={cn("flex w-full max-w-md flex-col gap-stack-md rounded-(--shape-lg) bg-(--surface-container-low) p-4", className)}
      onKeyDown={(event) => {
        if (!q.choices || event.target instanceof HTMLTextAreaElement) return
        const index = event.key.toUpperCase().charCodeAt(0) - 65
        if (event.key.length === 1 && index >= 0 && index < q.choices.length) choose(q.choices[index])
      }}
    >
      <Progress value={((step + 1) / questions.length) * 100} aria-label={`Question ${step + 1} of ${questions.length}`} />
      <div key={q.id} data-dir={dir > 0 ? "next" : "prev"} className="question flex flex-col gap-stack-sm">
        <h3 className="text-title">{q.title}</h3>
        {q.description ? <p className="text-sm text-muted-foreground">{q.description}</p> : null}
        {q.type === "text" ? (
          <textarea
            aria-label={q.title}
            value={(answer as string) ?? ""}
            onChange={(event) => setAnswers((all) => ({ ...all, [q.id]: event.target.value }))}
            className="min-h-20 rounded-(--field-corner-multiline) bg-(--field-container) p-3 text-sm outline-none focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)"
          />
        ) : (
          <div role={q.type === "single" ? "radiogroup" : "group"} aria-label={q.title} className="flex flex-col gap-1.5">
            {q.choices?.map((choice, index) => {
              const picked = Array.isArray(answer) ? answer.includes(choice) : answer === choice
              return (
                <button
                  key={choice}
                  type="button"
                  role={q.type === "single" ? "radio" : "checkbox"}
                  aria-checked={picked}
                  onClick={() => choose(choice)}
                  className={cn(
                    "liquid-press flex items-center gap-3 rounded-(--question-choice-corner) px-3 py-2 text-start text-sm outline-none focus-visible:shadow-(--focus-ring)",
                    picked ? "bg-(--question-choice-selected)" : "bg-(--question-choice) hover:bg-(--question-choice-hover) active:bg-(--question-choice-pressed)"
                  )}
                >
                  <kbd className="inline-flex size-6 shrink-0 items-center justify-center rounded-(--shape-xs) bg-(--surface-container-lowest) font-mono text-caption">
                    {String.fromCharCode(65 + index)}
                  </kbd>
                  <span className="flex-1">{choice}</span>
                  {picked ? <CheckIcon aria-hidden className="question-check size-(--size-icon-sm)" /> : null}
                </button>
              )
            })}
          </div>
        )}
      </div>
      <div className="flex items-center justify-between">
        <Button size="sm" variant="ghost" disabled={step === 0} onClick={() => go(-1)}>
          Previous
        </Button>
        <div className="flex gap-2">
          {q.optional ? (
            <Button size="sm" variant="ghost" onClick={() => go(1)}>
              Skip
            </Button>
          ) : null}
          <Button size="sm" disabled={!ready} onClick={() => go(1)}>
            {last ? "Submit" : "Next"}
          </Button>
        </div>
      </div>
    </section>
  )
}

export { Questionnaire }
export type { Question }