{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "multi-step-form",
  "title": "Multi-step Form",
  "description": "Wizard with numbered, progress-bar or vertical step headers, sync and async per-step validation that blocks Continue and focuses the first invalid field, optional steps with Skip, an auto review step with Edit links, async submit with loading, error retry and success, draft persistence, direction-aware slide or fade transitions and screen-reader step announcements, in card, outline, plain, glass and neo shells with tones and sizes.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/button.json",
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/core/multi-step-form.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion, type Transition } from \"motion/react\"\nimport { ArrowLeft } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { Button } from \"@/components/goodui/button\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\n/*\n * Multi-step form (wizard), independent layers: every axis combines with every other.\n *   variant     card, outline, plain, glass, neo           tone        accent for steps, bar and buttons\n *   header      numbered, progress, vertical, none          transition  slide (direction-aware), fade, none\n *   navigation  linear (only visited steps are clickable) or free         size, shadow\n * Each step renders your own fields (Core Input, Select, Checkbox…) through `content`, gets the shared values and\n * its errors, and can validate sync or async before Next. Invalid steps block Next, show the messages and focus the\n * first invalid field. Optional steps get a Skip button. `review` adds a summary step with Edit links. onSubmit may\n * be async (loading, error with retry, then success). onPersist receives a snapshot after every change, so drafts\n * can be saved and restored with defaultValues + defaultStep + defaultCompleted.\n * Screen readers hear \"Step 2 of 4: Contact\" on every step change, and focus moves to the new step's heading.\n */\n\nexport type MultiStepFormVariant = \"card\" | \"outline\" | \"plain\" | \"glass\" | \"neo\"\nexport type MultiStepFormTone = \"primary\" | \"neutral\" | \"success\" | \"warning\" | \"danger\" | \"info\"\nexport type MultiStepFormSize = \"sm\" | \"md\" | \"lg\"\nexport type MultiStepFormShadow = \"none\" | \"sm\" | \"md\" | \"lg\"\nexport type MultiStepFormHeader = \"numbered\" | \"progress\" | \"vertical\" | \"none\"\nexport type MultiStepFormTransition = \"slide\" | \"fade\" | \"none\"\nexport type MultiStepFormNavigation = \"linear\" | \"free\"\n\nexport type FormValues = Record<string, unknown>\n/** Field name → message. Empty or undefined messages count as valid. */\nexport type StepErrors = Record<string, string | undefined>\n/** What a validator returns: nothing when valid, a string for a step-level error, or field errors. */\nexport type StepValidation = string | StepErrors | null | undefined | void\n\nexport type StepContext<V extends FormValues> = {\n  values: V\n  setValue: <K extends keyof V>(key: K, value: V[K]) => void\n  /** Field errors of this step from the last validation; a field's error clears when its value changes. */\n  errors: StepErrors\n  /** Error message for one field, or undefined. */\n  error: (key: keyof V & string) => string | undefined\n  /** Index of this step. */\n  step: number\n  next: () => void\n  back: () => void\n  goTo: (step: number) => void\n}\n\nexport type FormStep<V extends FormValues> = {\n  /** Stable id, used in the persistence snapshot. */\n  id: string\n  title: string\n  description?: React.ReactNode\n  /** Shown in the step header instead of the number while the step is upcoming or current. */\n  icon?: React.ReactNode\n  /** Adds a Skip button; skipped steps are not validated on submit. */\n  optional?: boolean\n  /** Fields of this step, in order: used to focus the first invalid one and for the auto review summary. */\n  fields?: (keyof V & string)[]\n  /** Runs on Next (and again on submit). Return nothing when valid, a string, or { field: \"message\" }. May be async. */\n  validate?: (values: V) => StepValidation | Promise<StepValidation>\n  /** The step's fields. A function receives values, setValue and errors. */\n  content: React.ReactNode | ((ctx: StepContext<V>) => React.ReactNode)\n  /** Rows for the review step. Defaults to `fields` with fieldLabels. */\n  summary?: (values: V) => { label: string; value: React.ReactNode }[]\n}\n\nexport type MultiStepFormSnapshot<V extends FormValues> = { step: number; values: V; completed: string[]; skipped: string[] }\n\nexport type MultiStepFormLabels = {\n  next: string\n  back: string\n  skip: string\n  submit: string\n  backToReview: string\n  optional: string\n  reviewTitle: string\n  reviewDescription: string\n  edit: string\n  editStep: (stepTitle: string) => string\n  stepOf: (step: number, total: number) => string\n  announce: (step: number, total: number, title: string) => string\n  progress: string\n  complete: string\n  skipped: string\n  hasErrors: string\n  current: string\n  errorSummary: (count: number) => string\n  validating: string\n  submitting: string\n  submitError: string\n  successTitle: string\n  successText: string\n  startOver: string\n  yes: string\n  no: string\n  empty: string\n}\nconst DEFAULT_LABELS: MultiStepFormLabels = {\n  next: \"Continue\",\n  back: \"Back\",\n  skip: \"Skip\",\n  submit: \"Submit\",\n  backToReview: \"Back to review\",\n  optional: \"Optional\",\n  reviewTitle: \"Review\",\n  reviewDescription: \"Check your answers before you submit.\",\n  edit: \"Edit\",\n  editStep: (t) => `Edit ${t}`,\n  stepOf: (s, t) => `Step ${s} of ${t}`,\n  announce: (s, t, title) => `Step ${s} of ${t}: ${title}`,\n  progress: \"Progress\",\n  complete: \"completed\",\n  skipped: \"skipped\",\n  hasErrors: \"needs attention\",\n  current: \"current step\",\n  errorSummary: (n) => (n === 1 ? \"1 field needs attention.\" : `${n} fields need attention.`),\n  validating: \"Checking…\",\n  submitting: \"Submitting…\",\n  submitError: \"Something went wrong. Please try again.\",\n  successTitle: \"All done\",\n  successText: \"We received your details.\",\n  startOver: \"Start over\",\n  yes: \"Yes\",\n  no: \"No\",\n  empty: \"—\",\n}\n\nexport type MultiStepFormProps<V extends FormValues> = Omit<React.ComponentProps<\"form\">, \"onSubmit\" | \"children\" | \"defaultValue\"> & {\n  steps: FormStep<V>[]\n  /** Form values (controlled). */\n  values?: V\n  /** Initial values when uncontrolled; also what \"Start over\" resets to. Pass a saved draft here to restore it. */\n  defaultValues?: V\n  /** Called with all values after every change. */\n  onValuesChange?: (values: V) => void\n  /** Current step index (controlled). The review step is index steps.length. */\n  step?: number\n  /** Initial step when uncontrolled, e.g. from a saved draft. */\n  defaultStep?: number\n  onStepChange?: (step: number) => void\n  /** Step ids already completed or skipped, e.g. from a saved draft (marks them done in the header). */\n  defaultCompleted?: string[]\n  /** Adds a review step that summarizes every step with Edit links. */\n  review?: boolean\n  /** Labels for the auto review summary: { email: \"Email\" }. Unlisted names are humanized. */\n  fieldLabels?: Partial<Record<keyof V & string, string>>\n  /** Called with all values after every step passed. May be async; a thrown Error's message is shown with a retry. */\n  onSubmit?: (values: V) => void | Promise<void>\n  /** Shown after a successful submit. A function gets the values and a reset(). */\n  success?: React.ReactNode | ((ctx: { values: V; reset: () => void }) => React.ReactNode)\n  /** Called after every value or step change with a serializable snapshot, for saving drafts. */\n  onPersist?: (snapshot: MultiStepFormSnapshot<V>) => void\n  /** linear: steps ahead are clickable only once visited. free: any step is clickable (the current one still validates). */\n  navigation?: MultiStepFormNavigation\n  /** Step header: numbered circles with connecting lines, a progress bar, a vertical list beside the form, or none. */\n  header?: MultiStepFormHeader\n  /** Panel transition between steps: slide follows the direction (and flips in RTL), fade, or none. */\n  transition?: MultiStepFormTransition\n  /** Shell: card (default), outline, plain (no box), glass or neo. */\n  variant?: MultiStepFormVariant\n  /** Accent of the step header, bar and primary button. */\n  tone?: MultiStepFormTone\n  size?: MultiStepFormSize\n  /** Shell shadow. Ignored by neo, which has its own offset shadow. */\n  shadow?: MultiStepFormShadow\n  /** Heading element for step titles. */\n  headingAs?: \"h2\" | \"h3\" | \"h4\"\n  /** Text for buttons, header and screen readers; pass translations here. */\n  labels?: Partial<MultiStepFormLabels>\n}\n\nconst tones = (c: string) => `\n.${c}{--pc-c:var(--primary);--pc-fg:var(--primary-foreground)}\n.${c}[data-tone=neutral]{--pc-c:var(--foreground);--pc-fg:var(--background)}\n.${c}[data-tone=success]{--pc-c:oklch(0.53 0.13 155);--pc-fg:#fff}\n.${c}[data-tone=warning]{--pc-c:oklch(0.75 0.16 70);--pc-fg:oklch(0.25 0.05 70)}\n.${c}[data-tone=danger]{--pc-c:oklch(0.56 0.21 27);--pc-fg:#fff}\n.${c}[data-tone=info]{--pc-c:oklch(0.55 0.17 250);--pc-fg:#fff}\n.dark .${c}[data-tone=success]{--pc-c:oklch(0.7 0.16 155);--pc-fg:oklch(0.2 0.05 155)}\n.dark .${c}[data-tone=danger]{--pc-c:oklch(0.68 0.2 25);--pc-fg:oklch(0.2 0.05 25)}\n.dark .${c}[data-tone=info]{--pc-c:oklch(0.7 0.15 245);--pc-fg:oklch(0.2 0.05 245)}\n.${c}{--pc-tint:color-mix(in oklab,var(--pc-c) 14%,transparent);--pc-ink:color-mix(in oklab,var(--pc-c) 82%,var(--foreground))}\n.${c}[data-tone=warning]{--pc-ink:color-mix(in oklab,var(--pc-c) 62%,var(--foreground))}\n`\n\nconst R = \".pc-msf\"\nconst D = \".pc-msf-dot\"\nconst CSS = `${tones(\"pc-msf\")}\n${R}{--pc-muted:color-mix(in oklab,var(--muted-foreground) 82%,var(--foreground));--pc-bad:oklch(0.56 0.21 27);box-shadow:var(--pc-mv,0 0 #0000),var(--pc-msh,0 0 #0000)}\n.dark ${R}{--pc-bad:oklch(0.68 0.2 25)}\n${R}[data-variant=card]{background:var(--card);color:var(--card-foreground);border:1px solid color-mix(in oklab,var(--foreground) 8%,transparent);--pc-mv:0 1px 2px rgb(0 0 0/.05),0 4px 14px -6px rgb(0 0 0/.12)}\n.dark ${R}[data-variant=card]{--pc-mv:0 1px 2px rgb(0 0 0/.4),0 6px 18px -6px rgb(0 0 0/.6)}\n${R}[data-variant=outline]{background:var(--card);color:var(--card-foreground);border:1px solid var(--border)}\n${R}[data-variant=glass]{background:color-mix(in oklab,var(--card) 50%,transparent);border:1px solid color-mix(in oklab,var(--foreground) 13%,transparent);-webkit-backdrop-filter:blur(16px) saturate(1.6);backdrop-filter:blur(16px) saturate(1.6);--pc-mv:inset 0 1px 0 color-mix(in oklab,white 35%,transparent)}\n${R}[data-variant=neo]{background:var(--card);color:var(--card-foreground);border:2px solid var(--foreground);--pc-mv:6px 6px 0 var(--foreground)}\n${R}[data-shadow=sm]{--pc-msh:0 1px 3px rgb(0 0 0/.08),0 1px 2px rgb(0 0 0/.05)}\n${R}[data-shadow=md]{--pc-msh:0 8px 20px -8px rgb(0 0 0/.2)}\n${R}[data-shadow=lg]{--pc-msh:0 18px 40px -14px rgb(0 0 0/.28)}\n.pc-msf-muted{color:var(--pc-muted)}\n.pc-msf-sep{border-color:color-mix(in oklab,var(--foreground) 9%,transparent)}\n${R}[data-variant=neo] .pc-msf-sep{border-color:var(--foreground)}\n\n${D}{background:var(--background);border:1.5px solid color-mix(in oklab,var(--foreground) 18%,transparent);color:var(--pc-muted);transition:background-color .25s,border-color .25s,color .25s,box-shadow .25s}\n${D}[data-status=current]{border-color:var(--pc-c);color:var(--pc-ink);box-shadow:0 0 0 4px var(--pc-tint)}\n${D}[data-status=complete]{background:var(--pc-c);border-color:var(--pc-c);color:var(--pc-fg)}\n${D}[data-status=error]{border-color:var(--pc-bad);color:var(--pc-bad);background:color-mix(in oklab,var(--pc-bad) 10%,var(--background));box-shadow:0 0 0 4px color-mix(in oklab,var(--pc-bad) 14%,transparent)}\n${D}[data-status=skipped]{border-style:dashed}\n${R}[data-variant=neo] ${D}{border:2px solid var(--foreground)}\n${R}[data-variant=neo] ${D}[data-status=current]{box-shadow:2px 2px 0 var(--foreground)}\n.pc-msf-step{-webkit-tap-highlight-color:transparent}\n.pc-msf-step:not(:disabled):hover .pc-msf-name{color:var(--pc-ink)}\n.pc-msf-step:not(:disabled):hover ${D}:not([data-status=complete]){border-color:var(--pc-c)}\n.pc-msf-name{color:var(--pc-muted);transition:color .2s}\n.pc-msf-step[aria-current=step] .pc-msf-name{color:var(--foreground)}\n.pc-msf-line{background:color-mix(in oklab,var(--foreground) 12%,transparent)}\n.pc-msf-line>span{display:block;width:100%;height:100%;background:var(--pc-c);transform:scaleX(0);transform-origin:left center;transition:transform .4s var(--pc-ease-out)}\n.pc-msf-line>span:dir(rtl){transform-origin:right center}\n.pc-msf-line[data-axis=y]>span{transform:scaleY(0);transform-origin:center top}\n.pc-msf-line>span[data-done]{transform:none}\n.pc-msf-bar{background:color-mix(in oklab,var(--foreground) 10%,transparent)}\n.pc-msf-bar>span{background:var(--pc-c);transform-origin:left center;transition:transform .45s var(--pc-ease-out)}\n.pc-msf-bar>span:dir(rtl){transform-origin:right center}\n.pc-msf-alert{background:color-mix(in oklab,var(--pc-bad) 9%,transparent);color:color-mix(in oklab,var(--pc-bad) 80%,var(--foreground));border:1px solid color-mix(in oklab,var(--pc-bad) 28%,transparent)}\n.pc-msf-tag{background:color-mix(in oklab,var(--foreground) 7%,transparent);color:var(--pc-muted)}\n.pc-msf-ok{background:var(--pc-tint);color:var(--pc-ink)}\n.pc-msf-ok path{stroke-dasharray:24;stroke-dashoffset:0;animation:pc-msf-draw .5s .12s var(--pc-ease-out) backwards}\n@keyframes pc-msf-draw{from{stroke-dashoffset:24}}\n.pc-msf-edit{color:var(--pc-ink)}\n.pc-msf-edit:hover{text-decoration:underline;text-underline-offset:3px}\n@media (prefers-reduced-motion:reduce){\n  ${R} *{transition:none!important;animation:none!important}\n}\n`\n\nconst SZ = {\n  sm: { pad: \"p-4\", gap: \"gap-4\", dot: \"size-6 text-[11px] [&_svg]:size-3\", dotPx: 24, title: \"text-base\", text: \"text-xs\", btn: \"sm\" },\n  md: { pad: \"p-5 sm:p-6\", gap: \"gap-5\", dot: \"size-8 text-xs [&_svg]:size-3.5\", dotPx: 32, title: \"text-lg\", text: \"text-sm\", btn: \"md\" },\n  lg: { pad: \"p-6 sm:p-8\", gap: \"gap-6\", dot: \"size-10 text-sm [&_svg]:size-4\", dotPx: 40, title: \"text-xl\", text: \"text-sm\", btn: \"lg\" },\n} as const\n\ntype Status = \"upcoming\" | \"current\" | \"complete\" | \"skipped\" | \"error\"\ntype Normalized = { ok: boolean; fields: StepErrors; message: string | null }\nconst OK: Normalized = { ok: true, fields: {}, message: null }\n\nfunction normalize(r: StepValidation): Normalized {\n  if (!r) return OK\n  if (typeof r === \"string\") return { ok: false, fields: {}, message: r }\n  const fields: StepErrors = {}\n  for (const [k, m] of Object.entries(r)) if (m) fields[k] = m\n  return Object.keys(fields).length ? { ok: false, fields, message: null } : OK\n}\nconst isThenable = (x: unknown): x is PromiseLike<StepValidation> => !!x && typeof (x as { then?: unknown }).then === \"function\"\nconst humanize = (s: string) => {\n  const t = s\n    .replace(/([a-z\\d])([A-Z])/g, \"$1 $2\")\n    .replace(/[_-]+/g, \" \")\n    .toLowerCase()\n  return t.charAt(0).toUpperCase() + t.slice(1)\n}\nconst FOCUSABLE = 'input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),[tabindex]:not([tabindex=\"-1\"])'\n\nconst Check = () => (\n  <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n    <path d=\"M3.5 8.5 6.5 11.5 12.5 4.5\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n  </svg>\n)\n\n/** Runs `run` once when mounted: the new step panel uses it to take focus after the transition. */\nfunction OnMount({ run }: { run: () => void }) {\n  const ref = React.useRef(run)\n  React.useEffect(() => ref.current(), [])\n  return null\n}\n\nexport function MultiStepForm<V extends FormValues = FormValues>({\n  steps,\n  values: valuesProp,\n  defaultValues,\n  onValuesChange,\n  step: stepProp,\n  defaultStep = 0,\n  onStepChange,\n  defaultCompleted,\n  review = false,\n  fieldLabels,\n  onSubmit,\n  success,\n  onPersist,\n  navigation = \"linear\",\n  header = \"numbered\",\n  transition = \"slide\",\n  variant = \"card\",\n  tone = \"primary\",\n  size = \"md\",\n  shadow = \"none\",\n  headingAs: Heading = \"h3\",\n  labels,\n  className,\n  ...props\n}: MultiStepFormProps<V>) {\n  const l = useLabels(\"multi-step-form\", DEFAULT_LABELS, labels)\n  const prefersReduced = useReducedMotion()\n  // Gate reduced motion behind mount so server and first client render match.\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  const reduce = mounted && !!prefersReduced\n  const uid = React.useId()\n  const s = SZ[size]\n  const total = steps.length + (review ? 1 : 0)\n  const reviewIndex = review ? steps.length : -1\n\n  const [innerValues, setInnerValues] = React.useState<V>(() => defaultValues ?? ({} as V))\n  const values = valuesProp ?? innerValues\n  const valuesRef = React.useRef(values)\n  valuesRef.current = values\n  const setValues = (next: V) => {\n    valuesRef.current = next\n    if (valuesProp === undefined) setInnerValues(next)\n    onValuesChange?.(next)\n  }\n\n  const clampStep = (i: number) => Math.max(0, Math.min(total - 1, i))\n  const [innerStep, setInnerStep] = React.useState(() => clampStep(defaultStep))\n  const index = clampStep(stepProp ?? innerStep)\n  const setStep = (i: number) => {\n    if (stepProp === undefined) setInnerStep(i)\n    onStepChange?.(i)\n  }\n\n  const initialDone = () => Object.fromEntries((defaultCompleted ?? []).map((id) => [id, \"complete\" as const])) as Record<string, \"complete\" | \"skipped\">\n  const [done, setDone] = React.useState<Record<string, \"complete\" | \"skipped\">>(initialDone)\n  const doneRef = React.useRef(done)\n  doneRef.current = done\n  const [errorIds, setErrorIds] = React.useState<Record<string, true>>({})\n  const [furthest, setFurthest] = React.useState(() => clampStep(defaultStep))\n  const [errors, setErrors] = React.useState<StepErrors>({})\n  const [stepError, setStepError] = React.useState<string | null>(null)\n  const [submitError, setSubmitError] = React.useState<string | null>(null)\n  const [busy, setBusy] = React.useState<null | \"validating\" | \"submitting\">(null)\n  const busyRef = React.useRef(false)\n  const [finished, setFinished] = React.useState(false)\n  const [dir, setDir] = React.useState<1 | -1>(1)\n  const [rtl, setRtl] = React.useState(false)\n  const [returnToReview, setReturnToReview] = React.useState(false)\n  const [announcement, setAnnouncement] = React.useState(\"\")\n  const root = React.useRef<HTMLFormElement>(null)\n  const panel = React.useRef<HTMLDivElement>(null)\n  const heading = React.useRef<HTMLElement | null>(null)\n  const setHeading = (el: HTMLElement | null) => {\n    heading.current = el\n  }\n  const pendingFocus = React.useRef<null | \"heading\" | { field: string }>(null)\n\n  React.useLayoutEffect(() => {\n    if (root.current) setRtl(getComputedStyle(root.current).direction === \"rtl\")\n  }, [])\n\n  // Persistence: a snapshot after every change of values, step or completion (not on mount).\n  const persistRef = React.useRef(onPersist)\n  persistRef.current = onPersist\n  const firstPersist = React.useRef(true)\n  React.useEffect(() => {\n    if (firstPersist.current) {\n      firstPersist.current = false\n      return\n    }\n    const ids = Object.keys(done)\n    persistRef.current?.({ step: index, values, completed: ids.filter((id) => done[id] === \"complete\"), skipped: ids.filter((id) => done[id] === \"skipped\") })\n  }, [values, index, done])\n\n  const focusField = (key: string) => {\n    const scope = panel.current\n    if (!scope) return\n    const esc = window.CSS?.escape ? window.CSS.escape(key) : key\n    const el = scope.querySelector<HTMLElement>(`[data-field=\"${esc}\"]`) ?? scope.querySelector<HTMLElement>(`[name=\"${esc}\"]`) ?? scope.querySelector<HTMLElement>(`#${esc}`)\n    if (!el) return\n    const target = el.matches(FOCUSABLE) ? el : (el.querySelector<HTMLElement>(FOCUSABLE) ?? el.parentElement?.querySelector<HTMLElement>(FOCUSABLE))\n    target?.focus()\n  }\n  const runPendingFocus = () => {\n    const p = pendingFocus.current\n    pendingFocus.current = null\n    if (p === \"heading\") heading.current?.focus({ preventScroll: true })\n    else if (p) focusField(p.field)\n  }\n\n  const titleOf = (i: number) => (i === reviewIndex ? l.reviewTitle : (steps[i]?.title ?? \"\"))\n\n  const move = (i: number, focus: \"heading\" | { field: string } = \"heading\") => {\n    const target = clampStep(i)\n    setDir(target >= index ? 1 : -1)\n    setErrors({})\n    setStepError(null)\n    setSubmitError(null)\n    if (target === reviewIndex) setReturnToReview(false)\n    setFurthest((f) => Math.max(f, target))\n    pendingFocus.current = focus\n    setAnnouncement(l.announce(target + 1, total, titleOf(target)))\n    if (target === index) {\n      requestAnimationFrame(runPendingFocus)\n      return\n    }\n    setStep(target)\n  }\n\n  const resolve = async (i: number): Promise<Normalized> => {\n    const st = steps[i]\n    if (!st?.validate) return OK\n    let r: StepValidation | PromiseLike<StepValidation>\n    try {\n      r = st.validate(valuesRef.current)\n    } catch (e) {\n      return { ok: false, fields: {}, message: e instanceof Error && e.message ? e.message : l.submitError }\n    }\n    if (!isThenable(r)) return normalize(r)\n    setBusy(\"validating\")\n    setAnnouncement(l.validating)\n    try {\n      return normalize(await r)\n    } catch (e) {\n      return { ok: false, fields: {}, message: e instanceof Error && e.message ? e.message : l.submitError }\n    } finally {\n      setBusy(null)\n    }\n  }\n\n  const showErrors = (i: number, r: Normalized) => {\n    const st = steps[i]\n    if (!st) return\n    const keys = Object.keys(r.fields)\n    const ordered = [...(st.fields ?? []).filter((f) => keys.includes(f)), ...keys.filter((k) => !(st.fields ?? []).includes(k as keyof V & string))]\n    setErrorIds((e) => ({ ...e, [st.id]: true }))\n    const focus = ordered[0] ? { field: ordered[0] } : (\"heading\" as const)\n    if (i !== index) move(i, focus)\n    else {\n      pendingFocus.current = focus\n      requestAnimationFrame(runPendingFocus)\n    }\n    setErrors(r.fields)\n    setStepError(r.message)\n    setAnnouncement(r.message ?? l.errorSummary(keys.length))\n  }\n\n  const markDone = (i: number, how: \"complete\" | \"skipped\") => {\n    const id = steps[i]?.id\n    if (!id) return\n    setDone((d) => ({ ...d, [id]: how }))\n    setErrorIds((e) => {\n      if (!e[id]) return e\n      const rest = { ...e }\n      delete rest[id]\n      return rest\n    })\n  }\n\n  const exclusive = async (fn: () => Promise<void>) => {\n    if (busyRef.current || finished) return\n    busyRef.current = true\n    try {\n      await fn()\n    } finally {\n      busyRef.current = false\n    }\n  }\n\n  const submit = async () => {\n    for (let i = 0; i < steps.length; i++) {\n      const st = steps[i]!\n      if (doneRef.current[st.id] === \"skipped\") continue\n      const r = await resolve(i)\n      if (!r.ok) return showErrors(i, r)\n      markDone(i, \"complete\")\n    }\n    setBusy(\"submitting\")\n    setSubmitError(null)\n    setAnnouncement(l.submitting)\n    try {\n      await onSubmit?.(valuesRef.current)\n      setDir(1)\n      pendingFocus.current = \"heading\"\n      setFinished(true)\n      setAnnouncement(l.successTitle)\n    } catch (e) {\n      const msg = e instanceof Error && e.message ? e.message : l.submitError\n      setSubmitError(msg)\n      setAnnouncement(msg)\n    } finally {\n      setBusy(null)\n    }\n  }\n\n  const next = () =>\n    exclusive(async () => {\n      if (index === reviewIndex) return submit()\n      if (index === steps.length - 1 && !review) return submit()\n      const r = await resolve(index)\n      if (!r.ok) return showErrors(index, r)\n      markDone(index, \"complete\")\n      move(returnToReview && review ? reviewIndex : index + 1)\n    })\n\n  const skip = () =>\n    exclusive(async () => {\n      if (!steps[index]?.optional) return\n      markDone(index, \"skipped\")\n      if (index === steps.length - 1 && !review) return submit()\n      move(returnToReview && review ? reviewIndex : index + 1)\n    })\n\n  const back = () => {\n    if (busyRef.current || finished || index === 0) return\n    move(index - 1)\n  }\n\n  const reachable = (i: number) => !finished && !busy && i !== index && (i < index || navigation === \"free\" || i <= furthest)\n  const jump = (i: number, fromReview = false) =>\n    exclusive(async () => {\n      if (!reachable(i)) return\n      if (fromReview) setReturnToReview(true)\n      if (i < index) return move(i)\n      if (index !== reviewIndex) {\n        const r = await resolve(index)\n        if (!r.ok) return showErrors(index, r)\n        markDone(index, \"complete\")\n      }\n      move(i)\n    })\n\n  const reset = () => {\n    const v = defaultValues ?? ({} as V)\n    setValues(v)\n    setDone({})\n    setErrorIds({})\n    setFurthest(0)\n    setErrors({})\n    setStepError(null)\n    setSubmitError(null)\n    setReturnToReview(false)\n    setFinished(false)\n    setDir(-1)\n    pendingFocus.current = \"heading\"\n    setStep(0)\n    setAnnouncement(l.announce(1, total, titleOf(0)))\n  }\n\n  const setValue = <K extends keyof V>(key: K, v: V[K]) => {\n    setValues({ ...valuesRef.current, [key]: v })\n    const k = String(key)\n    if (errors[k])\n      setErrors((e) => {\n        const rest = { ...e }\n        delete rest[k]\n        return rest\n      })\n  }\n\n  const statusOf = (i: number): Status => {\n    const id = i === reviewIndex ? \"\" : (steps[i]?.id ?? \"\")\n    if (finished) return done[id] === \"skipped\" ? \"skipped\" : \"complete\"\n    if (i === index) return errorIds[id] ? \"error\" : \"current\"\n    if (errorIds[id]) return \"error\"\n    if (done[id]) return done[id]\n    return \"upcoming\"\n  }\n  const statusText = (st: Status) => (st === \"complete\" ? l.complete : st === \"skipped\" ? l.skipped : st === \"error\" ? l.hasErrors : st === \"current\" ? l.current : \"\")\n\n  const dot = (i: number) => {\n    const st = statusOf(i)\n    const ic = i === reviewIndex ? null : steps[i]?.icon\n    return (\n      <span data-status={st} className={cn(\"pc-msf-dot grid shrink-0 place-items-center rounded-full font-semibold tabular-nums\", s.dot)} aria-hidden=\"true\">\n        {st === \"complete\" ? <Check /> : st === \"error\" ? \"!\" : st === \"skipped\" ? \"–\" : (ic ?? i + 1)}\n      </span>\n    )\n  }\n\n  const all = Array.from({ length: total }, (_, i) => ({ i, title: titleOf(i), optional: i === reviewIndex ? false : !!steps[i]?.optional }))\n  const vertical = header === \"vertical\"\n\n  const stepButton = (i: number, title: string, optional: boolean, inline: boolean) => (\n    <button\n      type=\"button\"\n      disabled={!reachable(i)}\n      aria-current={i === index && !finished ? \"step\" : undefined}\n      onClick={() => jump(i)}\n      className={cn(\n        \"pc-press pc-msf-step flex min-w-0 items-center gap-2.5 rounded-md text-start outline-none focus-visible:ring-3 focus-visible:ring-[color-mix(in_oklab,var(--pc-c)_40%,transparent)] enabled:cursor-pointer\",\n        s.text,\n      )}\n    >\n      {dot(i)}\n      <span className={cn(\"min-w-0\", inline && \"max-sm:sr-only\")}>\n        <span className={cn(\"pc-msf-name block font-medium\", inline ? \"max-w-[10rem] truncate\" : \"\")}>{title}</span>\n        {optional && <span className=\"pc-msf-muted block text-[11px] leading-tight font-normal\">{l.optional}</span>}\n      </span>\n      {statusText(statusOf(i)) && <span className=\"sr-only\">, {statusText(statusOf(i))}</span>}\n    </button>\n  )\n\n  const headerNode =\n    header === \"numbered\" ? (\n      <nav aria-label={l.progress} data-slot=\"msf-header\">\n        <ol className=\"flex items-center gap-2\">\n          {all.map(({ i, title, optional }) => (\n            <li key={i} className={cn(\"flex min-w-0 items-center gap-2\", i < total - 1 ? \"flex-1\" : \"shrink-0\")}>\n              {stepButton(i, title, optional, true)}\n              {i < total - 1 && (\n                <span className=\"pc-msf-line h-0.5 min-w-3 flex-1 overflow-hidden rounded-full\" aria-hidden=\"true\">\n                  <span data-done={statusOf(i) === \"complete\" || statusOf(i) === \"skipped\" ? \"\" : undefined} />\n                </span>\n              )}\n            </li>\n          ))}\n        </ol>\n      </nav>\n    ) : header === \"progress\" ? (\n      <div data-slot=\"msf-header\" className=\"flex flex-col gap-2\">\n        <div className={cn(\"flex items-baseline justify-between gap-3\", s.text)}>\n          <span className=\"min-w-0 truncate font-medium\">{finished ? l.successTitle : titleOf(index)}</span>\n          <span className=\"pc-msf-muted shrink-0 tabular-nums\">{l.stepOf(finished ? total : index + 1, total)}</span>\n        </div>\n        <div className=\"pc-msf-bar h-1.5 overflow-hidden rounded-full\" aria-hidden=\"true\">\n          <span className=\"block h-full w-full rounded-full\" style={{ transform: `scaleX(${finished ? 1 : (index + 1) / total})` }} />\n        </div>\n      </div>\n    ) : vertical ? (\n      <nav aria-label={l.progress} data-slot=\"msf-header\" className=\"pc-msf-sep sm:border-e sm:pe-5\">\n        <ol className=\"flex flex-col gap-1\">\n          {all.map(({ i, title, optional }) => (\n            <li key={i} className=\"relative pb-3 last:pb-0\">\n              {i < total - 1 && (\n                <span\n                  className=\"pc-msf-line absolute w-0.5 overflow-hidden rounded-full\"\n                  data-axis=\"y\"\n                  aria-hidden=\"true\"\n                  style={{ insetInlineStart: s.dotPx / 2 - 1, top: s.dotPx + 4, bottom: 0 }}\n                >\n                  <span data-done={statusOf(i) === \"complete\" || statusOf(i) === \"skipped\" ? \"\" : undefined} />\n                </span>\n              )}\n              {stepButton(i, title, optional, false)}\n            </li>\n          ))}\n        </ol>\n      </nav>\n    ) : null\n\n  const dirX = (rtl ? -1 : 1) * 28\n  const t: Transition = reduce || transition === \"none\" ? { duration: 0 } : spring.ui\n  const variants = {\n    enter: (d: 1 | -1) => (transition === \"slide\" && !reduce ? { opacity: 0, x: d * dirX } : transition === \"fade\" && !reduce ? { opacity: 0, y: 6 } : { opacity: 1 }),\n    center: { opacity: 1, x: 0, y: 0 },\n    exit: (d: 1 | -1) =>\n      transition === \"slide\" && !reduce\n        ? { opacity: 0, x: -d * dirX, transition: { duration: 0.14 } }\n        : transition === \"fade\" && !reduce\n          ? { opacity: 0, transition: { duration: 0.12 } }\n          : { opacity: 1, transition: { duration: 0 } },\n  }\n\n  const currentStep = index === reviewIndex ? null : steps[index]\n  const ctx: StepContext<V> = {\n    values,\n    setValue,\n    errors,\n    error: (k) => errors[k],\n    step: index,\n    next: () => void next(),\n    back,\n    goTo: (i) => void jump(i),\n  }\n  const isFinal = index === reviewIndex || (!review && index === steps.length - 1)\n  const fmt = (v: unknown): React.ReactNode => {\n    if (v == null || v === \"\" || (Array.isArray(v) && v.length === 0)) return <span className=\"pc-msf-muted\">{l.empty}</span>\n    if (typeof v === \"boolean\") return v ? l.yes : l.no\n    if (Array.isArray(v)) return v.join(\", \")\n    if (typeof v === \"object\") return React.isValidElement(v) ? v : JSON.stringify(v)\n    return String(v)\n  }\n  const btnVariant = variant === \"neo\" ? \"neo\" : \"solid\"\n\n  const body = finished ? (\n    <div className=\"flex flex-col items-center gap-3 py-6 text-center\">\n      {typeof success === \"function\" ? (\n        <div ref={setHeading} tabIndex={-1} className=\"w-full outline-none\">\n          {success({ values, reset })}\n        </div>\n      ) : success ? (\n        <div ref={setHeading} tabIndex={-1} className=\"w-full outline-none\">\n          {success}\n        </div>\n      ) : (\n        <>\n          <motion.span\n            initial={reduce ? false : { scale: 0.6, opacity: 0 }}\n            animate={{ scale: 1, opacity: 1 }}\n            transition={reduce ? { duration: 0 } : spring.play}\n            className=\"pc-msf-ok grid size-14 place-items-center rounded-full [&_svg]:size-7\"\n          >\n            <Check />\n          </motion.span>\n          <Heading ref={setHeading} tabIndex={-1} id={`${uid}-title`} className={cn(\"font-semibold tracking-tight outline-none\", s.title)}>\n            {l.successTitle}\n          </Heading>\n          <p className={cn(\"pc-msf-muted max-w-sm\", s.text)}>{l.successText}</p>\n          <Button type=\"button\" variant=\"outline\" tone=\"neutral\" size={s.btn} onClick={reset} className=\"mt-2\">\n            {l.startOver}\n          </Button>\n        </>\n      )}\n    </div>\n  ) : (\n    <div className={cn(\"flex flex-col\", s.gap)}>\n      <div className=\"flex flex-col gap-1\">\n        {header !== \"progress\" && <p className=\"pc-msf-muted text-xs font-medium\">{l.stepOf(index + 1, total)}</p>}\n        <div className=\"flex flex-wrap items-center gap-2\">\n          <Heading ref={setHeading} tabIndex={-1} id={`${uid}-title`} className={cn(\"font-semibold tracking-tight outline-none\", s.title)}>\n            {titleOf(index)}\n          </Heading>\n          {currentStep?.optional && <span className=\"pc-msf-tag rounded-full px-2 py-0.5 text-[11px] font-medium\">{l.optional}</span>}\n        </div>\n        {(currentStep ? currentStep.description : l.reviewDescription) && (\n          <p className={cn(\"pc-msf-muted\", s.text)}>{currentStep ? currentStep.description : l.reviewDescription}</p>\n        )}\n      </div>\n      {stepError && (\n        <div role=\"alert\" className={cn(\"pc-msf-alert rounded-lg px-3 py-2 font-medium\", s.text)}>\n          {stepError}\n        </div>\n      )}\n      {currentStep ? (\n        <div data-slot=\"msf-fields\" className=\"flex flex-col gap-4\">\n          {typeof currentStep.content === \"function\" ? currentStep.content(ctx) : currentStep.content}\n        </div>\n      ) : (\n        <div data-slot=\"msf-review\" className=\"flex flex-col gap-3\">\n          {steps.map((st, i) => {\n            const rows = st.summary\n              ? st.summary(values)\n              : (st.fields ?? []).map((f) => ({ label: fieldLabels?.[f] ?? humanize(f), value: fmt(values[f]) }))\n            return (\n              <section key={st.id} aria-labelledby={`${uid}-rv-${i}`} className=\"pc-msf-sep rounded-lg border p-3 sm:p-4\">\n                <div className=\"flex items-center justify-between gap-3\">\n                  <h4 id={`${uid}-rv-${i}`} className={cn(\"font-semibold\", s.text)}>\n                    {st.title}\n                    {done[st.id] === \"skipped\" && <span className=\"pc-msf-muted ms-2 font-normal\">({l.skipped})</span>}\n                  </h4>\n                  <button\n                    type=\"button\"\n                    onClick={() => jump(i, true)}\n                    aria-label={l.editStep(st.title)}\n                    className=\"pc-press pc-msf-edit shrink-0 cursor-pointer rounded-sm text-xs font-medium outline-none focus-visible:ring-3 focus-visible:ring-[color-mix(in_oklab,var(--pc-c)_40%,transparent)]\"\n                  >\n                    {l.edit}\n                  </button>\n                </div>\n                {rows.length > 0 && done[st.id] !== \"skipped\" && (\n                  <dl className={cn(\"mt-2 grid grid-cols-[minmax(0,9rem)_1fr] gap-x-4 gap-y-1.5\", s.text)}>\n                    {rows.map((row) => (\n                      <React.Fragment key={row.label}>\n                        <dt className=\"pc-msf-muted truncate\">{row.label}</dt>\n                        <dd className=\"min-w-0 break-words\">{row.value}</dd>\n                      </React.Fragment>\n                    ))}\n                  </dl>\n                )}\n              </section>\n            )\n          })}\n        </div>\n      )}\n      {submitError && (\n        <div role=\"alert\" className={cn(\"pc-msf-alert rounded-lg px-3 py-2 font-medium\", s.text)}>\n          {submitError}\n        </div>\n      )}\n      <div data-slot=\"msf-actions\" className=\"pc-msf-sep flex flex-wrap items-center gap-2 border-t pt-4\">\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          tone=\"neutral\"\n          size={s.btn}\n          onClick={back}\n          disabled={!!busy}\n          className={cn(index === 0 && \"invisible\")}\n          iconLeft={<ArrowLeft className=\"rtl:rotate-180\" />}\n        >\n          {l.back}\n        </Button>\n        <span className=\"flex-1\" />\n        {currentStep?.optional && (\n          <Button type=\"button\" variant=\"ghost\" tone=\"neutral\" size={s.btn} onClick={() => void skip()} disabled={!!busy}>\n            {l.skip}\n          </Button>\n        )}\n        <Button type=\"submit\" variant={btnVariant} tone={tone} size={s.btn} loading={!!busy} animation=\"press\">\n          {busy === \"validating\" ? l.validating : busy === \"submitting\" ? l.submitting : isFinal ? l.submit : returnToReview && review ? l.backToReview : l.next}\n        </Button>\n      </div>\n    </div>\n  )\n\n  return (\n    <>\n      <GooduiTokens />\n      <style href=\"pc-multi-step-form\" precedence=\"default\">\n        {CSS}\n      </style>\n      <form\n        {...props}\n        ref={root}\n        noValidate\n        data-slot=\"multi-step-form\"\n        data-variant={variant}\n        data-tone={tone}\n        data-shadow={variant === \"neo\" ? \"none\" : shadow}\n        data-header={header}\n        aria-labelledby={props[\"aria-label\"] ? undefined : (props[\"aria-labelledby\"] ?? `${uid}-title`)}\n        onSubmit={(e) => {\n          e.preventDefault()\n          if (!finished) void next()\n        }}\n        className={cn(\n          \"pc-msf grid w-full max-w-2xl min-w-0 rounded-xl\",\n          variant === \"plain\" ? \"p-0\" : s.pad,\n          s.gap,\n          vertical && \"sm:grid-cols-[minmax(0,13rem)_minmax(0,1fr)] sm:items-start\",\n          className,\n        )}\n      >\n        {headerNode}\n        <div ref={panel} className=\"min-w-0 overflow-x-clip\">\n          <AnimatePresence mode=\"wait\" initial={false} custom={dir}>\n            <motion.div key={finished ? \"done\" : index} custom={dir} variants={variants} initial=\"enter\" animate=\"center\" exit=\"exit\" transition={t}>\n              <OnMount run={runPendingFocus} />\n              {body}\n            </motion.div>\n          </AnimatePresence>\n        </div>\n        <div aria-live=\"polite\" className=\"sr-only\">\n          {announcement}\n        </div>\n      </form>\n    </>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/multi-step-form.tsx"
    }
  ],
  "categories": [
    "components",
    "core"
  ],
  "type": "registry:component"
}
