{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dialogue-stepper",
  "type": "registry:ui",
  "title": "Dialogue Stepper",
  "description": "A `Dialogue` the reader steps through: one step of turns at a time, each revealed by a choice (\"What do I say?\", \"They might ask…\"). A choice can branch to any step, the reader can go back, reset, or show the whole conversation at once. Use it for a…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "blog",
    "pattern"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/dialogue.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/dialogue-stepper.tsx",
      "target": "components/ui/patterns/dialogue-stepper.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/dialogue-stepper v2.1.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/dialogue-stepper\n// What changed since: https://ds.interlace.tools/c/dialogue-stepper#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — DialogueStepper\n *\n * A `Dialogue` the reader steps through: one step of turns at a time, each\n * revealed by a choice (\"What do I say?\", \"They might ask…\"). A choice can\n * branch to any step, the reader can go back, reset, or show the whole\n * conversation at once. Use it for a practice conversation, an onboarding\n * script, or a support flow written as a dialogue.\n *\n * ## Progressive enhancement\n *\n * The server renders every step. In the browser only the steps on the\n * reader's path show. Without JavaScript a `<noscript>` style shows every\n * step in document order and hides the choices and controls, so the page is\n * the whole conversation, read top to bottom. Server and client start from\n * the same state, so nothing shifts when the page hydrates.\n *\n * ## Path\n *\n * The path starts at `start`. A choice appends its `next` step; choosing a\n * step that is already on the path goes back to it instead of repeating it.\n * Steps show in path order, so a branch reads in the order it was taken.\n * Only the last step's choices are live: earlier ones are hidden once the\n * reader has moved on.\n *\n * ## Server components\n *\n * Steps, turns and choices are often written in a server component, so the\n * parts are flat (`DialogueStep`, `DialogueChoices`, `DialogueChoice`):\n * React cannot dot into a client module from a server component. Pass a\n * step's choices through its `choices` prop there, because a server\n * component holds only a reference to each client part and a\n * `DialogueChoices` child cannot be told apart from a turn. Choices written\n * as children still work when the whole tree renders on the client.\n *\n * ## Focus and announcements\n *\n * After a choice, focus moves to the first choice of the new step (or to\n * Back, when the step ends the talk), so a keyboard reader can keep going\n * without hunting. The new step's words are read out once through a polite\n * live region. Pending steps are hidden with a class, not the `hidden`\n * attribute, so the no-JS style can show them: a preflight rule for\n * `[hidden]` sits in a cascade layer, and its `!important` would beat it.\n * The step enters with a short fade and rise, behind\n * `motion-safe:`, so reduced motion shows it at once.\n *\n * ## Flow\n *\n * A flow (docs/philosophies/FLOW_PHILOSOPHY.md) with flat parts. The reader's\n * path is the state; it starts at `start`. Every phase, the part that shows\n * it, and what moves it on:\n *\n * | Phase  | Part                                          | Leaves by                                         |\n * | ------ | --------------------------------------------- | ------------------------------------------------- |\n * | step   | DialogueStep (current), DialogueChoices       | a DialogueChoice → its `next` step                |\n * | end    | a DialogueStep with no choices                | Back → the step before; Start over → `start`      |\n * | whole  | every DialogueStep, in order (`mode=\"all\"`)   | Step through → back to the path                   |\n * | no JS  | every DialogueStep, no choices or controls    | —                                                 |\n *\n * Back and Start over work from any step on the path.\n *\n * ## Anatomy\n *\n *   DialogueStepper                 (div — data-slot=\"dialogue-stepper\", data-mode)\n *     ├─ DialogueStep × n           (div role=group — data-step, data-state=current|past|pending)\n *     │   ├─ Dialogue               (ol — the step's turns, `Dialogue.Turn` children)\n *     │   └─ DialogueChoices        (div — choices for the next step)\n *     │       └─ DialogueChoice × n (button — `next` step id)\n *     ├─ controls                   (div — Back, Show the whole talk / Step through, Start over)\n *     ├─ live region                (div — polite, visually hidden)\n *     └─ noscript                   (style — every step, no choices, no controls)\n *\n * ## MIN_VIEWPORT — 320\n *\n * As `Dialogue`: bubbles cap at 85% of the column; choices and controls wrap.\n *\n * | Rule | Concept                 | Where in this file                                         |\n * | ---- | ----------------------- | ---------------------------------------------------------- |\n * | R4   | Extends native el       | `div` / `button` props                                     |\n * | R6   | data-slot per part      | dialogue-stepper / -step / -choices / -choice / -controls  |\n * | R7   | cn + ...rest            | `cn(…, className)` + `{...props}`                          |\n * | R8   | Enums, not booleans     | `mode`, `data-state`                                       |\n * | R14  | Declares min viewport   | `data-min-viewport` on the root + exported const           |\n * | R19  | Tokens only             | `--duration-base`, `ease-enter`, Dialogue's own tokens     |\n * | R25  | Client component        | Path state, focus and the live region need hooks           |\n * | R26  | A11y                    | Real buttons; polite live region; focus follows the reader |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Dialogue, DialogueSuggestions } from '@/components/ui/patterns/dialogue';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport type DialogueStepperMode = 'step' | 'all';\n\nexport interface DialogueStepperLabels {\n  back: string;\n  showAll: string;\n  stepThrough: string;\n  reset: string;\n}\n\nconst DEFAULT_LABELS: DialogueStepperLabels = {\n  back: 'Back',\n  showAll: 'Show the whole conversation',\n  stepThrough: 'Step through',\n  reset: 'Start over',\n};\n\ntype Ctx = {\n  mode: DialogueStepperMode;\n  path: string[];\n  speakers: 'above' | 'inside';\n  choose: (next: string) => void;\n};\n\nconst StepperContext = React.createContext<Ctx | null>(null);\ntype StepCtx = { id: string; state: StepState };\ntype StepState = 'current' | 'past' | 'pending';\nconst StepContext = React.createContext<StepCtx | null>(null);\n\nfunction useStepper(part: string): Ctx {\n  const ctx = React.useContext(StepperContext);\n  if (!ctx) throw new Error(`<${part}> must be inside <DialogueStepper>.`);\n  return ctx;\n}\n\ntype DialogueStepperProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** The id of the first step. */\n  start: string;\n  /** `DialogueStep` elements, each with a unique `id`. */\n  children: React.ReactNode;\n  /** Where each turn names its speaker, as on `Dialogue`. @default 'above' */\n  speakers?: 'above' | 'inside';\n  /** Open with every step shown. @default 'step' */\n  defaultMode?: DialogueStepperMode;\n  /** The control labels, for another language. */\n  labels?: Partial<DialogueStepperLabels>;\n};\n\nfunction stepId(node: React.ReactNode): string | null {\n  return React.isValidElement<{ id?: unknown }>(node) && typeof node.props.id === 'string'\n    ? node.props.id\n    : null;\n}\n\nconst text = (el: Element | null) => el?.textContent?.replace(/\\s+/g, ' ').trim() ?? '';\n\n/** A step's turns as one sentence each, \"Speaker: words.\", for the live region. */\nfunction spoken(step: HTMLElement): string {\n  return Array.from(step.querySelectorAll('[data-slot=\"dialogue-turn\"]'))\n    .map((turn) => {\n      const speaker = text(turn.querySelector('[data-slot=\"dialogue-speaker\"]'));\n      const words = text(turn.querySelector('[data-slot=\"dialogue-bubble\"]'));\n      return speaker ? `${speaker}: ${words}` : words;\n    })\n    .join(' ');\n}\n\nfunction DialogueStepper({\n  start,\n  children,\n  speakers = 'above',\n  defaultMode = 'step',\n  labels: labelsProp,\n  className,\n  ...props\n}: DialogueStepperProps) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp };\n  const [mode, setMode] = React.useState<DialogueStepperMode>(defaultMode);\n  const [path, setPath] = React.useState<string[]>([start]);\n  const [announcement, setAnnouncement] = React.useState('');\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const backRef = React.useRef<HTMLButtonElement>(null);\n  // Set by a choice, read once the new step is in the DOM.\n  const pendingFocus = React.useRef<string | null>(null);\n\n  const choose = React.useCallback((next: string) => {\n    setPath((current) => {\n      const at = current.indexOf(next);\n      // A step already on the path: go back to it rather than repeat it.\n      return at === -1 ? [...current, next] : current.slice(0, at + 1);\n    });\n    pendingFocus.current = next;\n  }, []);\n\n  React.useEffect(() => {\n    const next = pendingFocus.current;\n    if (!next || mode !== 'step') return;\n    pendingFocus.current = null;\n    const step = Array.from(\n      rootRef.current?.querySelectorAll<HTMLElement>('[data-slot=\"dialogue-step\"]') ?? [],\n    ).find((el) => el.dataset.step === next);\n    if (!step) return;\n    setAnnouncement(spoken(step));\n    const firstChoice = step.querySelector<HTMLElement>('[data-slot=\"dialogue-choice\"]');\n    (firstChoice ?? backRef.current)?.focus();\n  }, [path, mode]);\n\n  // Showing every step pushes the controls down; keep the one the reader is on in view.\n  React.useEffect(() => {\n    const active = document.activeElement;\n    if (active && rootRef.current?.contains(active)) active.scrollIntoView?.({ block: 'nearest' });\n  }, [mode]);\n\n  React.useEffect(() => {\n    // A DialogueChoices child of a server component cannot be recognised,\n    // so it lands in the step's list of turns.\n    if (rootRef.current?.querySelector('[data-slot=\"dialogue\"] [data-slot=\"dialogue-choices\"]')) {\n      console.warn(\n        '<DialogueChoices> is inside a list of turns. Pass it through <DialogueStep choices={…}> when a server component renders the step.',\n      );\n    }\n  }, []);\n\n  const items = React.Children.toArray(children);\n  const ordered =\n    mode === 'step'\n      ? [\n          ...path.map((id) => items.find((c) => stepId(c) === id)).filter(Boolean),\n          ...items.filter((c) => !path.includes(stepId(c) ?? '')),\n        ]\n      : items;\n\n  const ctx = React.useMemo<Ctx>(() => ({ mode, path, speakers, choose }), [mode, path, speakers, choose]);\n\n  const control =\n    'text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex min-h-control items-center rounded-full px-3 text-sm font-medium underline-offset-4 transition-[color,box-shadow] duration-(--duration-fast) focus-visible:outline-hidden hover:underline focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50';\n\n  return (\n    <StepperContext.Provider value={ctx}>\n      <div\n        ref={rootRef}\n        data-slot=\"dialogue-stepper\"\n        data-mode={mode}\n        data-min-viewport={String(MIN_VIEWPORT)}\n        className={cn('flex flex-col gap-4', className)}\n        {...props}\n      >\n        {ordered}\n        <div data-slot=\"dialogue-stepper-controls\" className=\"flex flex-wrap items-center gap-1 border-t pt-3\">\n          <button\n            ref={backRef}\n            type=\"button\"\n            className={control}\n            disabled={mode !== 'step' || path.length < 2}\n            onClick={() => {\n              // Back turns itself off on the first step: hand focus to that step's choice.\n              if (path.length === 2) pendingFocus.current = start;\n              setPath((current) => current.slice(0, -1));\n            }}\n          >\n            {labels.back}\n          </button>\n          <button\n            type=\"button\"\n            className={control}\n            aria-pressed={mode === 'all'}\n            onClick={() => setMode((m) => (m === 'all' ? 'step' : 'all'))}\n          >\n            {mode === 'all' ? labels.stepThrough : labels.showAll}\n          </button>\n          <button\n            type=\"button\"\n            className={control}\n            disabled={mode === 'step' && path.length < 2}\n            onClick={() => {\n              // Start over turns itself off: hand focus to the first step's choice.\n              pendingFocus.current = start;\n              setMode('step');\n              setPath([start]);\n            }}\n          >\n            {labels.reset}\n          </button>\n        </div>\n        <div role=\"status\" aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n          {announcement}\n        </div>\n        <noscript>\n          <style>{`[data-slot=\"dialogue-stepper\"] [data-slot=\"dialogue-step\"]{display:flex!important}[data-slot=\"dialogue-stepper\"] [data-slot=\"dialogue-choices\"],[data-slot=\"dialogue-stepper\"] [data-slot=\"dialogue-stepper-controls\"]{display:none!important}`}</style>\n        </noscript>\n      </div>\n    </StepperContext.Provider>\n  );\n}\n\ntype DialogueStepProps = Omit<React.ComponentProps<'div'>, 'id'> & {\n  /** Unique within the stepper; choices point at it with `next`. */\n  id: string;\n  /**\n   * The step's `DialogueChoices`. Use this, not a child, when a server\n   * component renders the step. Wins over a `DialogueChoices` child.\n   */\n  choices?: React.ReactNode;\n  /** An accessible name for the step, read when it is announced as a group. */\n  'aria-label'?: string;\n};\n\nfunction isChoices(node: React.ReactNode): boolean {\n  return React.isValidElement(node) && node.type === DialogueChoices;\n}\n\nfunction DialogueStep({ id, choices, className, children, ...props }: DialogueStepProps) {\n  const { mode, path, speakers } = useStepper('DialogueStep');\n  const at = path.indexOf(id);\n  const state: StepState =\n    mode === 'all' ? 'past' : at === -1 ? 'pending' : at === path.length - 1 ? 'current' : 'past';\n  const items = React.Children.toArray(children);\n  const turns = items.filter((c) => !isChoices(c));\n  const childChoices = items.filter(isChoices);\n  const step = React.useMemo<StepCtx>(() => ({ id, state }), [id, state]);\n  return (\n    <StepContext.Provider value={step}>\n      <div\n        role=\"group\"\n        data-slot=\"dialogue-step\"\n        data-step={id}\n        data-state={state}\n        className={cn(\n          'flex flex-col gap-3',\n          // A class, not the hidden attribute: the no-JS style must win.\n          state === 'pending' && 'hidden',\n          // A step the reader just revealed fades and rises in; never the first.\n          state === 'current' &&\n            at > 0 &&\n            'motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-2 motion-safe:duration-(--duration-base) motion-safe:ease-enter',\n          className,\n        )}\n        {...props}\n      >\n        <Dialogue speakers={speakers}>{turns}</Dialogue>\n        {/* The prop wins, so passing both never doubles the buttons. */}\n        {choices ?? childChoices}\n      </div>\n    </StepContext.Provider>\n  );\n}\n\ntype DialogueChoicesProps = React.ComponentProps<'div'>;\n\nfunction DialogueChoices({ className, ...props }: DialogueChoicesProps) {\n  const step = React.useContext(StepContext);\n  // Only the last step's choices are live; a past step drops them.\n  if (step?.state === 'past') return null;\n  return (\n    <DialogueSuggestions data-slot=\"dialogue-choices\" className={cn('justify-end', className)} {...props} />\n  );\n}\n\ntype DialogueChoiceProps = Omit<React.ComponentProps<'button'>, 'type'> & {\n  /** The id of the step this choice reveals. */\n  next: string;\n};\n\nconst CHOICE =\n  'border-primary text-primary hover:bg-primary/10 focus-visible:ring-ring inline-flex min-h-control items-center rounded-full border-2 px-4 py-1.5 text-sm font-semibold transition-[background-color,box-shadow,scale] duration-(--duration-fast) ease-enter focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background motion-safe:active:scale-[0.97]';\n\nfunction DialogueChoice({ next, className, onClick, ...props }: DialogueChoiceProps) {\n  const { choose } = useStepper('DialogueChoice');\n  const from = React.useContext(StepContext)?.id;\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"dialogue-choice\"\n      data-next={next}\n      data-from={from ?? undefined}\n      className={cn(CHOICE, className)}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) choose(next);\n      }}\n      {...props}\n    />\n  );\n}\n\nDialogueStepper.displayName = 'DialogueStepper';\nDialogueStep.displayName = 'DialogueStep';\nDialogueChoices.displayName = 'DialogueChoices';\nDialogueChoice.displayName = 'DialogueChoice';\n\nexport { DialogueStepper, DialogueStep, DialogueChoices, DialogueChoice };\nexport type { DialogueStepperProps, DialogueStepProps, DialogueChoicesProps, DialogueChoiceProps };\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "2.1.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/dialogue-stepper\n\nInstalled to `components/ui/patterns/dialogue-stepper.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/dialogue-stepper';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/dialogue-stepper\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
