{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "wizard",
  "type": "registry:ui",
  "title": "Wizard",
  "description": "The shell of a guided task done one step at a time inside a card: a title with \"Step 2 of 5\", a rail of the steps, the current step, and Back, Skip and a main button named after what the step does.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/button",
    "@rivier-ui/cn",
    "@rivier-ui/steps",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/wizard.tsx",
      "type": "registry:ui",
      "target": "components/ui/wizard.tsx",
      "content": "\"use client\";\n/**\n * @name wizard\n * @category ui\n * @description The shell of a guided task done one step at a time inside a card: a title with \"Step 2 of 5\", a rail of the steps, the current step, and Back, Skip and a main button named after what the step does.\n * @when A task that is easier one question at a time and has a known order: a booking, a set-up, an application. It keeps where one is (controlled or not), moves focus to each new step's heading, and blocks the main button with a stated reason while a step is not answered. Where a server decides what comes next, control it: give `step`, and `onNext`, `onBack` and `onSkip` in place of the wizard's own moves, with `pending` while the answer is on its way; the step still slides in and its heading still takes focus when `step` changes. For a short form show all the fields at once (field); for the rail alone use steps; for unordered sections use tabs or accordion. What each step contains is yours: the wizard holds no answers.\n * @example\n * const [people, setPeople] = useState(0);\n * <Wizard\n *   steps={[\n *     { id: \"dates\", label: \"Dates\" },\n *     { id: \"people\", label: \"People\", canContinue: people > 0, blockedReason: \"Say how many people are coming.\" },\n *     { id: \"extras\", label: \"Extras\", optional: true },\n *     { id: \"review\", label: \"Review\" },\n *   ]}\n *   defaultStep=\"dates\"\n *   onComplete={book}\n * >\n *   <WizardHeader>Book a table</WizardHeader>\n *   <WizardRail />\n *   <WizardStep id=\"dates\" title=\"Which day?\">…</WizardStep>\n *   <WizardStep id=\"people\" title=\"How many people?\">…</WizardStep>\n *   <WizardStep id=\"extras\" title=\"Anything to add?\">…</WizardStep>\n *   <WizardStep id=\"review\" title=\"Check and confirm\">…</WizardStep>\n *   <WizardFooter>\n *     <WizardBack>Back</WizardBack>\n *     <WizardSkip>Skip</WizardSkip>\n *     <WizardNext>{step === \"review\" ? \"Confirm\" : \"Continue\"}</WizardNext>\n *   </WizardFooter>\n * </Wizard>\n *\n * // Driven from outside: the server says which step is next, and the rail's states are the project's\n * <Wizard\n *   steps={flow.steps.map((item) => ({ id: item.id, label: item.label, optional: item.optional, state: item.skipped ? \"skipped\" : undefined }))}\n *   step={flow.current}\n *   pending={saving}\n *   onNext={(current) => submit(current.id)}\n *   onBack={(current) => goBackFrom(current.id)}\n *   onSkip={(current) => skip(current.id)}\n * >…</Wizard>\n */\nimport { createContext, use, useEffect, useId, useRef, useState, type ComponentProps, type MouseEvent, type ReactNode } from \"react\";\nimport { Button, type ButtonProps } from \"@/components/ui/button\";\nimport { Step, Steps, StepsCount, type StepState, type StepsProps } from \"@/components/ui/steps\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\nexport type WizardStepInfo = {\n  /** Identifies the step: the `id` of its WizardStep. */\n  id: string;\n  /** The step's short name, for the rail. */\n  label: string;\n  /** The step may be skipped: WizardSkip shows on it. */\n  optional?: boolean;\n  /** False while the step is not answered well enough to go on. Default true. */\n  canContinue?: boolean;\n  /** Why it cannot go on yet, in words the person can act on. Shown by the footer and read out. */\n  blockedReason?: string;\n  /** Overrides the state the rail works out: \"assumed\" for a step filled in for the person, \"blocked\" for one that cannot be done. */\n  state?: StepState;\n  /** Said with the state: what was assumed, or what is in the way. */\n  note?: string;\n};\n\ntype WizardContextValue = {\n  steps: WizardStepInfo[];\n  step: string;\n  index: number;\n  total: number;\n  current: WizardStepInfo | undefined;\n  isFirst: boolean;\n  isLast: boolean;\n  canContinue: boolean;\n  /** The steps the person skipped. */\n  skipped: ReadonlySet<string>;\n  /** +1 after going forward, -1 after going back, 0 before the step has changed. */\n  travel: -1 | 0 | 1;\n  /** The move is being worked out elsewhere (`pending`): the buttons wait. */\n  pending: boolean;\n  /** Whether Back has somewhere to go: not on the first step, unless the project handles Back itself. */\n  canGoBack: boolean;\n  titleId: string;\n  reasonId: string;\n  countLabel: (current: number, total: number) => string;\n  /** True once after the step changes: the step that mounts next asks, and takes focus. */\n  takeFocus: () => boolean;\n  goTo: (id: string) => void;\n  next: () => void;\n  back: () => void;\n  skip: () => void;\n};\n\nconst WizardContext = createContext<WizardContextValue | null>(null);\n\n/** The wizard's state and moves, for a step's own controls (\"Edit\" on a review step, a choice that goes on by itself). */\nexport function useWizard(): WizardContextValue {\n  const context = use(WizardContext);\n  if (!context) throw new Error(\"Wizard parts must be used inside <Wizard>.\");\n  return context;\n}\n\nexport type WizardProps = Omit<ComponentProps<\"div\">, \"onChange\"> & {\n  /** The steps, in order. Pass a new array as answers change: `canContinue` and `blockedReason` are read from it. */\n  steps: WizardStepInfo[];\n  /**\n   * The current step's id, controlled. Whenever it changes, by the wizard's own buttons or because the\n   * project set it (a server answered), the new step arrives from the side it lies on in `steps` and its\n   * heading takes focus.\n   */\n  step?: string;\n  /** The step to start on when uncontrolled. Default: the first. */\n  defaultStep?: string;\n  /** Called with the step the wizard's own buttons and rail ask for. */\n  onStepChange?: (step: string) => void;\n  /** Called when the main button is pressed on the last step. */\n  onComplete?: () => void;\n  /**\n   * Takes over the main button. Given this, a press (on a step that can go on) calls it with the current\n   * step and the wizard does not move, nor call `onComplete`: set `step` when it is known what comes next.\n   */\n  onNext?: (current: WizardStepInfo) => void;\n  /** Takes over Back in the same way. With it, Back is available on the first step too (the project may have somewhere to go). */\n  onBack?: (current: WizardStepInfo) => void;\n  /** Takes over Skip in the same way. The wizard then does not mark the step skipped: say so with the step's `state`. */\n  onSkip?: (current: WizardStepInfo) => void;\n  /** A move is being worked out (a request is on its way): the buttons and the rail wait, the main button shows it is busy, and the card is `aria-busy`. */\n  pending?: boolean;\n  /** \"Step 2 of 5\". Translate it with the interface. */\n  countLabel?: (current: number, total: number) => string;\n};\n\n/**\n * A card that is a named group (by its WizardHeader). Only the current step is in the page. Moving follows\n * the person's act (a button), and then focus goes to the new step's heading, which is read out with its\n * count: nothing else needs announcing. That holds however the step changes: by the wizard's own buttons,\n * or by the project setting `step` after a server has answered.\n */\nexport function Wizard({\n  className,\n  steps,\n  step,\n  defaultStep,\n  onStepChange,\n  onComplete,\n  onNext,\n  onBack,\n  onSkip,\n  pending = false,\n  countLabel = (now, all) => `Step ${now} of ${all}`,\n  children,\n  ...props\n}: WizardProps) {\n  const [currentId, setCurrentId] = useControllableState({ value: step, defaultValue: defaultStep ?? steps[0]?.id ?? \"\", onChange: onStepChange });\n  const [skipped, setSkipped] = useState<ReadonlySet<string>>(new Set());\n  /** The step last seen, the way it was reached, and how many times the step has changed. */\n  const [arrival, setArrival] = useState<{ id: string; travel: -1 | 0 | 1; count: number }>({ id: currentId, travel: 0, count: 0 });\n  /** The change of step whose heading has already taken focus. */\n  const focused = useRef(0);\n  const titleId = useId();\n  const reasonId = useId();\n\n  // The step changed, whoever changed it: work out which way it lies, during this render, so the new step\n  // mounts already knowing where it came from.\n  if (arrival.id !== currentId) {\n    const from = steps.findIndex((item) => item.id === arrival.id);\n    const to = steps.findIndex((item) => item.id === currentId);\n    setArrival({ id: currentId, travel: from !== -1 && to < from ? -1 : 1, count: arrival.count + 1 });\n  }\n  const travel = arrival.id === currentId ? arrival.travel : 0;\n\n  const index = Math.max(\n    0,\n    steps.findIndex((item) => item.id === currentId),\n  );\n  const current = steps[index];\n  const canContinue = current?.canContinue !== false;\n\n  const move = (to: number, markSkipped?: boolean): void => {\n    const target = steps[to];\n    if (!target || !current || to === index) return;\n    setSkipped((before) => {\n      const after = new Set(before);\n      if (markSkipped) after.add(current.id);\n      else if (to > index) after.delete(current.id);\n      return after;\n    });\n    setCurrentId(target.id);\n  };\n  const atLast = index === steps.length - 1;\n\n  const value: WizardContextValue = {\n    steps,\n    step: current?.id ?? \"\",\n    index,\n    total: steps.length,\n    current,\n    isFirst: index === 0,\n    isLast: index === steps.length - 1,\n    canContinue,\n    skipped,\n    travel,\n    pending,\n    canGoBack: onBack !== undefined || index > 0,\n    titleId,\n    reasonId,\n    countLabel,\n    takeFocus: () => {\n      const due = focused.current !== arrival.count;\n      focused.current = arrival.count;\n      return due;\n    },\n    goTo: (id) => {\n      if (!pending) move(steps.findIndex((item) => item.id === id));\n    },\n    next: () => {\n      if (pending || !current) return;\n      if (!canContinue) {\n        if (current.blockedReason) announce(current.blockedReason, \"assertive\");\n        return;\n      }\n      if (onNext) onNext(current);\n      else if (atLast) onComplete?.();\n      else move(index + 1);\n    },\n    back: () => {\n      if (pending || !current) return;\n      if (onBack) onBack(current);\n      else move(index - 1);\n    },\n    skip: () => {\n      if (pending || !current?.optional) return;\n      if (onSkip) onSkip(current);\n      else if (atLast) onComplete?.();\n      else move(index + 1, true);\n    },\n  };\n\n  return (\n    <WizardContext value={value}>\n      <div data-slot=\"wizard\" role=\"group\" aria-labelledby={titleId} aria-busy={pending || undefined} data-pending={pending ? \"\" : undefined} className={cn(\"flex w-full min-w-0 flex-col rounded-surface border bg-card text-card-foreground\", className)} {...props}>\n        {children}\n      </div>\n    </WizardContext>\n  );\n}\n\nexport type WizardHeaderProps = ComponentProps<\"div\">;\n\n/** The task's name as a small heading line, with the count at the end. Its children name the whole wizard. */\nexport function WizardHeader({ className, children, ...props }: WizardHeaderProps) {\n  const { titleId, index, total, countLabel } = useWizard();\n  return (\n    <div data-slot=\"wizard-header\" className={cn(\"flex items-baseline justify-between gap-3 px-5 pt-5\", className)} {...props}>\n      <p id={titleId} data-slot=\"wizard-title\" className=\"min-w-0 text-xs font-medium tracking-wider text-muted-foreground uppercase\">\n        {children}\n      </p>\n      <StepsCount current={index + 1} total={total} label={countLabel} className=\"shrink-0\" />\n    </div>\n  );\n}\n\nexport type WizardRailProps = Omit<StepsProps, \"children\"> & {\n  /** Lets the person go back to a step already passed by pressing it on the rail. Default false. */\n  navigable?: boolean;\n};\n\n/** The rail: one mark per real step, in the state the wizard works out (done, current, not started, skipped) or the step states itself. */\nexport function WizardRail({ className, navigable = false, \"aria-label\": ariaLabel = \"Steps\", ...props }: WizardRailProps) {\n  const { steps, index, skipped, goTo, pending } = useWizard();\n  return (\n    <Steps data-slot=\"wizard-rail\" aria-label={ariaLabel} className={cn(\"px-5 pt-3\", className)} {...props}>\n      {steps.map((item, position) => {\n        const state: StepState = position === index ? \"current\" : (item.state ?? (skipped.has(item.id) ? \"skipped\" : position < index ? \"done\" : \"upcoming\"));\n        return (\n          <Step key={item.id} state={state} note={item.note} onClick={navigable && !pending && position < index ? () => goTo(item.id) : undefined}>\n            {item.label}\n          </Step>\n        );\n      })}\n    </Steps>\n  );\n}\n\nexport type WizardStepProps = Omit<ComponentProps<\"section\">, \"title\" | \"id\"> & {\n  /** The id of this step in the wizard's `steps`. */\n  id: string;\n  /** The step's heading: the question it asks. */\n  title: ReactNode;\n  /** The heading's level in the page. Default 3. */\n  headingLevel?: 2 | 3 | 4 | 5;\n};\n\n/**\n * One step's content. It is rendered only while it is the current step. When the person arrives, its\n * heading takes focus (it is not in the Tab order) and is read as \"Step 3 of 5: …\"; the content fades in\n * and moves 12px from the side it came from (the other side in right-to-left pages), or simply appears\n * under reduced motion. The card's height changes at once: only transform and opacity are animated.\n */\nexport function WizardStep({ className, id, title, headingLevel = 3, children, ...props }: WizardStepProps) {\n  const { step, index, total, travel, countLabel, takeFocus } = useWizard();\n  const headingId = useId();\n  const heading = useRef<HTMLHeadingElement>(null);\n  const active = step === id;\n\n  useEffect(() => {\n    if (active && takeFocus()) heading.current?.focus();\n    // Only a change of step moves focus: takeFocus is a new function on every render.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [active]);\n\n  if (!active) return null;\n  const Heading = `h${headingLevel}` as const;\n  return (\n    <section\n      data-slot=\"wizard-step\"\n      data-travel={travel === 0 ? undefined : travel === 1 ? \"forward\" : \"back\"}\n      aria-labelledby={headingId}\n      className={cn(\n        \"flex min-w-0 flex-col gap-4 p-5 ease-out animation-duration-(--duration-base) motion-reduce:animate-none!\",\n        // Forward arrives from the end side, back from the start side. The sides are spelled out with rtl:\n        // because the build turns tw-animate's own logical slides into a test of the page's language, not its direction.\n        \"data-[travel=forward]:animate-in data-[travel=forward]:fade-in-0 data-[travel=forward]:slide-in-from-right-3 rtl:data-[travel=forward]:slide-in-from-left-3\",\n        \"data-[travel=back]:animate-in data-[travel=back]:fade-in-0 data-[travel=back]:slide-in-from-left-3 rtl:data-[travel=back]:slide-in-from-right-3\",\n        className,\n      )}\n      {...props}\n    >\n      <Heading ref={heading} id={headingId} tabIndex={-1} data-slot=\"wizard-step-title\" className=\"rounded-control text-lg leading-tight font-medium\">\n        <span className=\"sr-only\">{countLabel(index + 1, total)}: </span>\n        {title}\n      </Heading>\n      {children}\n    </section>\n  );\n}\n\nexport type WizardFooterProps = ComponentProps<\"div\">;\n\n/** The buttons, with the reason the step cannot go on yet (when it has one) above them. Back sits at the start, the main button at the end. */\nexport function WizardFooter({ className, children, ...props }: WizardFooterProps) {\n  const { canContinue, current, reasonId } = useWizard();\n  return (\n    <div data-slot=\"wizard-footer\" className={cn(\"mt-auto flex flex-col gap-3 border-t p-5\", className)} {...props}>\n      {!canContinue && current?.blockedReason ? (\n        <p id={reasonId} data-slot=\"wizard-reason\" className=\"text-sm text-muted-foreground\">\n          {current.blockedReason}\n        </p>\n      ) : null}\n      <div className=\"flex flex-wrap items-center gap-2\">{children}</div>\n    </div>\n  );\n}\n\nconst pressed = (event: MouseEvent<HTMLButtonElement>, handler: ButtonProps[\"onClick\"], act: () => void): void => {\n  handler?.(event);\n  if (!event.defaultPrevented) act();\n};\n\n/** Goes to the step before. Disabled on the first step (unless the project handles Back itself with `onBack`), and while a move is `pending`. */\nexport function WizardBack({ onClick, variant = \"ghost\", ...props }: ButtonProps) {\n  const { back, canGoBack, pending } = useWizard();\n  return <Button data-slot=\"wizard-back\" variant={variant} disabled={!canGoBack || pending} onClick={(event) => pressed(event, onClick, back)} {...props} />;\n}\n\n/** Passes over the current step and marks it skipped on the rail. Rendered only on a step that is `optional`. */\nexport function WizardSkip({ onClick, variant = \"ghost\", ...props }: ButtonProps) {\n  const { skip, current, pending } = useWizard();\n  if (!current?.optional) return null;\n  return <Button data-slot=\"wizard-skip\" variant={variant} disabled={pending} onClick={(event) => pressed(event, onClick, skip)} {...props} />;\n}\n\n/**\n * The main button: goes on, or completes on the last step. Its children are the step's verb (\"Show what\n * fits\", \"Review\", \"Confirm\"). While the step cannot go on it stays focusable and says it is unavailable\n * (`aria-disabled`) with the reason as its description; pressing it then reads the reason out instead of moving.\n * While a move is `pending` it keeps focus too, says it is busy, and a press does nothing.\n */\nexport function WizardNext({ onClick, className, ...props }: ButtonProps) {\n  const { next, canContinue, current, reasonId, pending } = useWizard();\n  return (\n    <Button\n      data-slot=\"wizard-next\"\n      aria-disabled={canContinue && !pending ? undefined : true}\n      aria-busy={pending || undefined}\n      aria-describedby={!canContinue && current?.blockedReason ? reasonId : undefined}\n      className={cn(\"ms-auto aria-disabled:opacity-50\", className)}\n      onClick={(event) => pressed(event, onClick, next)}\n      {...props}\n    />\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "A task that is easier one question at a time and has a known order: a booking, a set-up, an application. It keeps where one is (controlled or not), moves focus to each new step's heading, and blocks the main button with a stated reason while a step is not answered. Where a server decides what comes next, control it: give `step`, and `onNext`, `onBack` and `onSkip` in place of the wizard's own moves, with `pending` while the answer is on its way; the step still slides in and its heading still takes focus when `step` changes. For a short form show all the fields at once (field); for the rail alone use steps; for unordered sections use tabs or accordion. What each step contains is yours: the wizard holds no answers.",
    "example": "const [people, setPeople] = useState(0);\n<Wizard\n  steps={[\n    { id: \"dates\", label: \"Dates\" },\n    { id: \"people\", label: \"People\", canContinue: people > 0, blockedReason: \"Say how many people are coming.\" },\n    { id: \"extras\", label: \"Extras\", optional: true },\n    { id: \"review\", label: \"Review\" },\n  ]}\n  defaultStep=\"dates\"\n  onComplete={book}\n>\n  <WizardHeader>Book a table</WizardHeader>\n  <WizardRail />\n  <WizardStep id=\"dates\" title=\"Which day?\">…</WizardStep>\n  <WizardStep id=\"people\" title=\"How many people?\">…</WizardStep>\n  <WizardStep id=\"extras\" title=\"Anything to add?\">…</WizardStep>\n  <WizardStep id=\"review\" title=\"Check and confirm\">…</WizardStep>\n  <WizardFooter>\n    <WizardBack>Back</WizardBack>\n    <WizardSkip>Skip</WizardSkip>\n    <WizardNext>{step === \"review\" ? \"Confirm\" : \"Continue\"}</WizardNext>\n  </WizardFooter>\n</Wizard>\n\n// Driven from outside: the server says which step is next, and the rail's states are the project's\n<Wizard\n  steps={flow.steps.map((item) => ({ id: item.id, label: item.label, optional: item.optional, state: item.skipped ? \"skipped\" : undefined }))}\n  step={flow.current}\n  pending={saving}\n  onNext={(current) => submit(current.id)}\n  onBack={(current) => goBackFrom(current.id)}\n  onSkip={(current) => skip(current.id)}\n>…</Wizard>",
    "client": true
  }
}
