{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stateful-button",
  "title": "Stateful button",
  "description": "Async button that morphs idle to spinner to drawn check or shaking error, with a spring width change between labels.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json",
    "https://goodui.dev/r/sounds.json"
  ],
  "files": [
    {
      "path": "registry/components/buttons/stateful-button.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport type { SoundName } from \"@/lib/goodui-sounds\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\nexport type StatefulButtonState = \"idle\" | \"loading\" | \"success\" | \"error\"\n\nexport type StatefulButtonLabels = {\n  /** Announced (sr-only) while loading. */\n  loading: string\n  /** Announced (sr-only) on success. */\n  success: string\n  /** Announced (sr-only) on failure. */\n  error: string\n  /** Default visible text after success (successText overrides it). */\n  successText: string\n  /** Default visible text after a failure (errorText overrides it). */\n  errorText: string\n}\nconst DEFAULT_LABELS: StatefulButtonLabels = {\n  loading: \"Working…\",\n  success: \"Done\",\n  error: \"Something went wrong\",\n  successText: \"Done\",\n  errorText: \"Try again\",\n}\n\nconst VARIANTS = {\n  default: \"bg-primary text-primary-foreground shadow-[var(--pc-e1)] hover:bg-primary/90\",\n  outline: \"border bg-background text-foreground shadow-xs hover:bg-muted dark:bg-input/30 dark:hover:bg-input/50\",\n  secondary: \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n} as const\n\nconst SIZES = {\n  sm: \"h-8 text-xs [&_svg]:size-3.5\",\n  md: \"h-10 text-sm [&_svg]:size-4\",\n  lg: \"h-12 text-base [&_svg]:size-5\",\n} as const\n\nconst PAD = { sm: \"px-3 gap-1.5\", md: \"px-5 gap-2\", lg: \"px-7 gap-2\" } as const\n\nexport type StatefulButtonProps = Omit<\n  React.ComponentProps<\"button\">,\n  \"onClick\" | \"onAnimationStart\" | \"onDrag\" | \"onDragStart\" | \"onDragEnd\"\n> & {\n  /** Return a promise to drive the states: pending → loading, resolved → success, rejected → error. */\n  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void | Promise<unknown>\n  /** Control the state yourself instead. */\n  state?: StatefulButtonState\n  /** Called on every state change, including the automatic return to idle. */\n  onStateChange?: (state: StatefulButtonState) => void\n  /** \"default\" | \"outline\" | \"secondary\": idle look; success turns emerald and error destructive in every variant. */\n  variant?: keyof typeof VARIANTS\n  /** \"sm\" | \"md\" | \"lg\": height, text size and padding. */\n  size?: keyof typeof SIZES\n  /** Shown next to the spinner while loading; empty by default (spinner only). */\n  loadingText?: React.ReactNode\n  /** Shown next to the drawn check after success. */\n  successText?: React.ReactNode\n  /** Shown next to the drawn cross after a failure; clicking again retries. */\n  errorText?: React.ReactNode\n  /** Milliseconds before success/error returns to idle; 0 keeps it. */\n  resetAfter?: number\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<StatefulButtonLabels>\n  /** Plays \"tap\" on click, then \"success\" or \"error\" with the result, when the visitor has sounds on (lib/goodui-sounds); a sound name replaces the tap. Off by default. */\n  sound?: boolean | SoundName\n}\n\n// Optional UI sound: the sound module is loaded only when `sound` is on, so silent apps pay nothing.\nfunction useCue(sound: boolean | SoundName | undefined) {\n  React.useEffect(() => {\n    if (sound) void import(\"@/lib/goodui-sounds\")\n  }, [sound])\n  return React.useCallback(\n    (fallback: SoundName, o?: { rate?: number; exact?: boolean }) => {\n      if (!sound) return\n      void import(\"@/lib/goodui-sounds\").then((m) => m.play(sound === true || o?.exact ? fallback : sound, { rate: o?.rate }))\n    },\n    [sound],\n  )\n}\n\nfunction Spinner() {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" className=\"animate-spin motion-reduce:animate-[spin_1.5s_linear_infinite]\" aria-hidden=\"true\">\n      <circle cx=\"12\" cy=\"12\" r=\"9\" stroke=\"currentColor\" strokeOpacity=\"0.25\" strokeWidth=\"3\" />\n      <path d=\"M21 12a9 9 0 0 0-9-9\" stroke=\"currentColor\" strokeWidth=\"3\" strokeLinecap=\"round\" />\n    </svg>\n  )\n}\n\nfunction DrawCheck({ reduce }: { reduce: boolean }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n      <motion.path\n        d=\"M5 12.5 10 17.5 19.5 7\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2.8\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        initial={reduce ? false : { pathLength: 0 }}\n        animate={{ pathLength: 1 }}\n        transition={{ duration: 0.3, delay: 0.08, ease: \"easeOut\" }}\n      />\n    </svg>\n  )\n}\n\nfunction DrawX({ reduce }: { reduce: boolean }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n      {[\"M7 7l10 10\", \"M17 7 7 17\"].map((d, i) => (\n        <motion.path\n          key={d}\n          d={d}\n          stroke=\"currentColor\"\n          strokeWidth=\"2.8\"\n          strokeLinecap=\"round\"\n          initial={reduce ? false : { pathLength: 0 }}\n          animate={{ pathLength: 1 }}\n          transition={{ duration: 0.18, delay: 0.06 + i * 0.1, ease: \"easeOut\" }}\n        />\n      ))}\n    </svg>\n  )\n}\n\n/** Button that morphs idle → loading → success or error, with a smooth width change and a shake on failure. */\nexport function StatefulButton({\n  onClick,\n  state: stateProp,\n  onStateChange,\n  variant = \"default\",\n  size = \"md\",\n  loadingText,\n  successText,\n  errorText,\n  resetAfter = 2200,\n  labels,\n  sound,\n  className,\n  children,\n  disabled,\n  ...props\n}: StatefulButtonProps) {\n  const l = useLabels(\"stateful-button\", DEFAULT_LABELS, labels)\n  const sr: Record<StatefulButtonState, string> = { idle: \"\", loading: l.loading, success: l.success, error: l.error }\n  const reduce = useReducedMotion() ?? false\n  const [inner, setInner] = React.useState<StatefulButtonState>(\"idle\")\n  const state = stateProp ?? inner\n  const cue = useCue(sound)\n  // The result sound follows the state, so it also plays when the parent controls `state`.\n  const prevState = React.useRef(state)\n  React.useEffect(() => {\n    if (prevState.current === state) return\n    prevState.current = state\n    if (state === \"success\" || state === \"error\") cue(state, { exact: true })\n  }, [state, cue])\n  const measureRef = React.useRef<HTMLSpanElement>(null)\n  const [width, setWidth] = React.useState<number | null>(null)\n  const alive = React.useRef(true)\n\n  React.useEffect(() => {\n    alive.current = true\n    return () => {\n      alive.current = false\n    }\n  }, [])\n\n  React.useEffect(() => {\n    const el = measureRef.current\n    if (!el) return\n    // Button width = content + the button's own borders (outline variant).\n    const ro = new ResizeObserver(() => {\n      const btn = el.parentElement\n      const border = btn ? btn.offsetWidth - btn.clientWidth : 0\n      setWidth(el.offsetWidth + border)\n    })\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [])\n\n  const set = React.useCallback(\n    (s: StatefulButtonState) => {\n      if (!alive.current) return\n      if (stateProp === undefined) setInner(s)\n      onStateChange?.(s)\n    },\n    [stateProp, onStateChange],\n  )\n\n  React.useEffect(() => {\n    if ((state !== \"success\" && state !== \"error\") || !resetAfter || stateProp !== undefined) return\n    const t = window.setTimeout(() => set(\"idle\"), resetAfter)\n    return () => window.clearTimeout(t)\n  }, [state, resetAfter, stateProp, set])\n\n  const busy = state === \"loading\" || state === \"success\"\n\n  const handle = (e: React.MouseEvent<HTMLButtonElement>) => {\n    if (busy) return\n    cue(\"tap\")\n    const r = onClick?.(e)\n    if (r && typeof (r as Promise<unknown>).then === \"function\") {\n      set(\"loading\")\n      ;(r as Promise<unknown>).then(\n        () => set(\"success\"),\n        () => set(\"error\"),\n      )\n    }\n  }\n\n  const content =\n    state === \"loading\" ? (\n      <>\n        <Spinner />\n        {loadingText}\n      </>\n    ) : state === \"success\" ? (\n      <>\n        <DrawCheck reduce={reduce} />\n        {successText ?? l.successText}\n      </>\n    ) : state === \"error\" ? (\n      <>\n        <DrawX reduce={reduce} />\n        {errorText ?? l.errorText}\n      </>\n    ) : (\n      children\n    )\n\n  return (\n    <>\n      <GooduiTokens />\n      <motion.button\n        data-slot=\"button\"\n        data-state={state}\n        aria-busy={state === \"loading\" || undefined}\n        aria-disabled={busy || undefined}\n        disabled={disabled}\n        onClick={handle}\n        initial={false}\n        animate={{\n          width: width ?? \"auto\",\n          x: state === \"error\" && !reduce ? [0, -8, 8, -5, 5, -2, 0] : 0,\n        }}\n        transition={{\n          width: reduce ? { duration: 0 } : spring.ui,\n          x: { duration: 0.42, ease: \"easeInOut\" },\n        }}\n        whileTap={busy || reduce ? undefined : { scale: 0.97 }}\n        className={cn(\n          \"relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-lg font-medium whitespace-nowrap transition-[background-color,color,box-shadow,border-color] duration-200 outline-none select-none focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:shrink-0\",\n          VARIANTS[variant],\n          // emerald-700 and a darkened destructive in dark mode keep white text at 4.5:1.\n          state === \"success\" && \"border-transparent bg-emerald-700 text-white hover:bg-emerald-700\",\n          state === \"error\" &&\n            \"border-transparent bg-destructive text-white hover:bg-destructive dark:bg-[color-mix(in_oklab,var(--destructive)_75%,black)] dark:hover:bg-[color-mix(in_oklab,var(--destructive)_75%,black)]\",\n          state === \"loading\" && \"cursor-progress\",\n          SIZES[size],\n          className,\n        )}\n        {...props}\n      >\n        <span ref={measureRef} className={cn(\"inline-flex items-center\", PAD[size])}>\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            <motion.span\n              key={state}\n              className=\"inline-flex items-center gap-[inherit]\"\n              initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: \"blur(3px)\" }}\n              animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n              exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: \"blur(3px)\" }}\n              transition={reduce ? { duration: 0.1 } : spring.snap}\n            >\n              {content}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n      </motion.button>\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {sr[state]}\n      </span>\n    </>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/stateful-button.tsx"
    }
  ],
  "categories": [
    "components",
    "buttons"
  ],
  "type": "registry:component"
}