{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cavemio-action-button",
  "title": "Action button",
  "description": "A button that runs a promise and shows it: the icon slot opens for a spinner, a check draws itself, failures shake, and the label morphs through each.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/components/action-button.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { TextMorph } from \"./text-morph\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  interactionIcon,\n  useInteractionReducedMotion,\n} from \"./imported-ui-interaction-motion\";\n\nexport type ActionStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport interface ActionButtonProps extends Omit<\n  React.ButtonHTMLAttributes<HTMLButtonElement>,\n  \"onClick\"\n> {\n  /** Async or sync action to execute on click. Automatically handles idle -> pending -> success/error. */\n  action?: () => Promise<unknown> | void;\n  /** Explicit click handler if action is not used. */\n  onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;\n  /** Controlled status state. If passed, overrides internal action state. */\n  status?: ActionStatus;\n  /** Custom labels for each status. */\n  labels?: Partial<Record<ActionStatus, string>>;\n  /** Default label in idle state if children is not provided. */\n  label?: string;\n  /** Leading icon shown in idle state. */\n  icon?: React.ReactNode;\n  /** Visual variant. Defaults to primary. */\n  variant?: \"primary\" | \"secondary\" | \"destructive\" | \"outline\" | \"ghost\";\n  /** Button sizing. Defaults to md (36px). */\n  size?: \"sm\" | \"md\" | \"lg\";\n  /** Duration in ms to show success or error state before auto-reverting to idle. Defaults to 2000ms. */\n  resetAfter?: number;\n  /** Callback fired when auto-reset triggers. */\n  onReset?: () => void;\n  /** Called with whatever `action` threw. */\n  onError?: (error: unknown) => void;\n}\n\nconst DEFAULT_LABELS: Record<ActionStatus, string> = {\n  idle: \"Save changes\",\n  pending: \"Saving\",\n  success: \"Saved\",\n  error: \"Try again\",\n};\n\nfunction SelfDrawingCheck({\n  drawn,\n  reduced,\n  size,\n}: {\n  drawn: boolean;\n  reduced: boolean;\n  size: number;\n}) {\n  return (\n    <svg\n      width={size}\n      height={size}\n      viewBox=\"0 0 16 16\"\n      fill=\"none\"\n      className=\"shrink-0\"\n    >\n      <path\n        d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        pathLength={1}\n        strokeDasharray={1}\n        style={{\n          strokeDashoffset: drawn ? 0 : 1,\n          transition:\n            drawn && !reduced\n              ? `stroke-dashoffset 420ms ${EASE_OUT} 120ms`\n              : \"none\",\n        }}\n      />\n    </svg>\n  );\n}\n\nfunction StatusAlert({ size }: { size: number }) {\n  return (\n    <svg\n      width={size}\n      height={size}\n      viewBox=\"0 0 16 16\"\n      fill=\"none\"\n      className=\"shrink-0\"\n    >\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path\n        d=\"M8 4.75v3.75\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.75\"\n        strokeLinecap=\"round\"\n      />\n      <circle cx=\"8\" cy=\"11\" r=\"1\" fill=\"currentColor\" />\n    </svg>\n  );\n}\n\nconst variantStyles = {\n  primary: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  secondary:\n    \"bg-card text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\",\n  outline:\n    \"bg-transparent text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\",\n  destructive:\n    \"bg-red-500/10 text-red-600 dark:text-red-400 shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-red-500)_30%,transparent)] hover:bg-red-500/15\",\n  ghost:\n    \"bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground\",\n};\n\nconst sizeStyles = {\n  sm: {\n    height: \"h-7 text-[12px] px-3\",\n    iconSize: 13,\n    spinnerSize: \"size-3\",\n  },\n  md: {\n    height: \"h-9 text-[13px] px-4\",\n    iconSize: 14,\n    spinnerSize: \"size-3.5\",\n  },\n  lg: {\n    height: \"h-10 text-[14px] px-5\",\n    iconSize: 16,\n    spinnerSize: \"size-4\",\n  },\n};\n\nexport function ActionButton({\n  action,\n  onClick,\n  status: controlledStatus,\n  labels,\n  label: defaultLabel,\n  icon,\n  variant = \"primary\",\n  size = \"md\",\n  resetAfter = 2000,\n  onReset,\n  onError,\n  children,\n  disabled = false,\n  className = \"\",\n  style,\n  ...props\n}: ActionButtonProps) {\n  const reduced = useInteractionReducedMotion();\n  const [internalStatus, setInternalStatus] =\n    React.useState<ActionStatus>(\"idle\");\n  const btnRef = React.useRef<HTMLButtonElement | null>(null);\n  const resetTimer = React.useRef<number>(0);\n\n  const status = controlledStatus ?? internalStatus;\n  const busy = status === \"pending\";\n  const s = sizeStyles[size];\n\n  // Resolve current label text\n  const initialText = typeof children === \"string\" ? children : defaultLabel;\n  const statusLabels = {\n    ...DEFAULT_LABELS,\n    idle: initialText || DEFAULT_LABELS.idle,\n    ...labels,\n  };\n  const currentLabel = statusLabels[status];\n\n  // Auto reset timer on success or error\n  React.useEffect(() => {\n    if (status !== \"success\" && status !== \"error\") return;\n    if (resetAfter <= 0) return;\n\n    window.clearTimeout(resetTimer.current);\n    resetTimer.current = window.setTimeout(() => {\n      if (controlledStatus === undefined) {\n        setInternalStatus(\"idle\");\n      }\n      onReset?.();\n    }, resetAfter);\n\n    return () => window.clearTimeout(resetTimer.current);\n  }, [status, resetAfter, controlledStatus, onReset]);\n\n  // Shake animation on error\n  React.useEffect(() => {\n    if (status !== \"error\" || reduced || !btnRef.current) return;\n    btnRef.current.animate(\n      [\n        { transform: \"none\" },\n        { transform: \"translateX(-4px)\" },\n        { transform: \"translateX(4px)\" },\n        { transform: \"translateX(-2px)\" },\n        { transform: \"translateX(2px)\" },\n        { transform: \"none\" },\n      ],\n      { duration: 380, easing: \"ease-out\" },\n    );\n  }, [status, reduced]);\n\n  // Click / execution handler\n  const handleClick = async (e: React.MouseEvent<HTMLButtonElement>) => {\n    if (busy || disabled) {\n      e.preventDefault();\n      return;\n    }\n\n    if (onClick) {\n      onClick(e);\n    }\n\n    if (action) {\n      e.preventDefault();\n      setInternalStatus(\"pending\");\n      try {\n        await action();\n        setInternalStatus(\"success\");\n      } catch (err) {\n        setInternalStatus(\"error\");\n        onError?.(err);\n      }\n    }\n  };\n\n  // Tone resolution for error/success overrides\n  const toneClass =\n    status === \"error\"\n      ? \"bg-red-500/10 text-red-600 shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-red-500)_30%,transparent)] dark:text-red-400\"\n      : status === \"success\" && variant === \"destructive\"\n        ? \"bg-emerald-500/10 text-emerald-600 shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-emerald-500)_30%,transparent)] dark:text-emerald-400\"\n        : variantStyles[variant];\n\n  // Current status icon\n  const showLeading = status !== \"idle\" || Boolean(icon);\n\n  const icons: Record<ActionStatus, React.ReactNode> = {\n    idle: icon,\n    // Spins only while pending, so a hidden spinner never keeps the page busy.\n    pending: (\n      <span\n        className={`inline-flex rounded-full border-[1.5px] border-current border-t-transparent ${s.spinnerSize} ${busy ? \"animate-spin\" : \"\"}`}\n      />\n    ),\n    success: (\n      <SelfDrawingCheck\n        drawn={status === \"success\"}\n        reduced={reduced}\n        size={s.iconSize}\n      />\n    ),\n    error: <StatusAlert size={s.iconSize} />,\n  };\n\n  return (\n    <>\n      <button\n        ref={btnRef}\n        type=\"button\"\n        disabled={disabled}\n        aria-disabled={busy || undefined}\n        aria-busy={busy || undefined}\n        onClick={handleClick}\n        style={style}\n        className={`relative inline-flex select-none items-center justify-center whitespace-nowrap rounded-full font-medium cursor-pointer disabled:cursor-default aria-disabled:cursor-default disabled:opacity-45 ${s.height} ${toneClass} ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${className}`}\n        {...props}\n      >\n        {/* The icon slot opens and closes; icons trade places through a blur. */}\n        <span\n          aria-hidden=\"true\"\n          className=\"relative flex shrink-0 items-center justify-center\"\n          style={{\n            width: showLeading ? s.iconSize : 0,\n            height: s.iconSize,\n            marginRight: showLeading ? (size === \"sm\" ? 6 : 8) : 0,\n            transition: reduced\n              ? \"none\"\n              : `width 380ms ${EASE_OUT}, margin-right 380ms ${EASE_OUT}`,\n          }}\n        >\n          {(Object.keys(icons) as ActionStatus[]).map((key) => (\n            <span\n              key={key}\n              className=\"absolute inset-0 flex items-center justify-center\"\n              style={interactionIcon(key === status, reduced)}\n            >\n              {icons[key]}\n            </span>\n          ))}\n        </span>\n        <TextMorph>{currentLabel}</TextMorph>\n      </button>\n      {/* Outside the button, so the announcement isn't read as part of its name. */}\n      <span role=\"status\" className=\"sr-only\">\n        {status === \"idle\" ? \"\" : currentLabel}\n      </span>\n    </>\n  );\n}\n\nexport default ActionButton;\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/text-morph.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * TEXT MORPH: text that changes the way it should\n *\n *   shared   letters both texts share stay alive and slide to\n *            their new place (\"Save\" → \"Saving\" keeps \"Sav\")\n *   new      letters that weren't there rise in out of a blur,\n *            one after another\n *   gone     letters that leave lift away and blur out where\n *            they stood\n *   width    the box eases to its new width, so a button or\n *            pill holding it resizes with it\n *\n * Texts with little in common crossfade as a whole instead of\n * flinging single letters across. The real text is always\n * there for screen readers.\n * ───────────────────────────────────────────────────────── */\n\nexport interface TextMorphProps extends Omit<\n  React.HTMLAttributes<HTMLSpanElement>,\n  \"children\"\n> {\n  children: string;\n  /** Morph time in ms. */\n  duration?: number;\n  /** Where new letters come from: below (\"up\") or above (\"down\"). */\n  direction?: \"up\" | \"down\";\n  /** Ease the box's width too; turn off for text that wraps. */\n  animateWidth?: boolean;\n}\n\ntype Glyph = { key: number; char: string };\ntype Leaving = Glyph & { x: number; y: number };\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(\n    subscribeReduced,\n    () => window.matchMedia(reducedQuery).matches,\n    () => false,\n  );\n\n/** Keep the letters two texts share (longest common subsequence); everything else is new. */\nfunction morph(\n  previous: Glyph[],\n  text: string,\n  nextKey: () => number,\n): Glyph[] {\n  const a = previous.map((g) => g.char);\n  const b = Array.from(text);\n  const fresh = () => b.map((char) => ({ key: nextKey(), char }));\n  if (!a.length || !b.length) return fresh();\n\n  const dp = Array.from(\n    { length: a.length + 1 },\n    () => new Uint16Array(b.length + 1),\n  );\n  for (let i = a.length - 1; i >= 0; i--)\n    for (let j = b.length - 1; j >= 0; j--)\n      dp[i][j] =\n        a[i] === b[j]\n          ? dp[i + 1][j + 1] + 1\n          : Math.max(dp[i + 1][j], dp[i][j + 1]);\n\n  // Too little in common reads as two different words: crossfade them instead.\n  if (dp[0][0] < Math.min(a.length, b.length) * 0.5) return fresh();\n\n  const out: Glyph[] = [];\n  let i = 0;\n  let j = 0;\n  while (j < b.length) {\n    if (i < a.length && a[i] === b[j]) {\n      out.push(previous[i++]);\n      j++;\n    } else if (i < a.length && dp[i + 1][j] >= dp[i][j + 1]) i++;\n    else out.push({ key: nextKey(), char: b[j++] });\n  }\n  return out;\n}\n\nfunction LeavingGlyph({\n  glyph,\n  lift,\n  duration,\n  onDone,\n}: {\n  glyph: Leaving;\n  lift: number;\n  duration: number;\n  onDone: (key: number) => void;\n}) {\n  const ref = React.useRef<HTMLSpanElement>(null);\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const animation = el.animate(\n      [\n        { opacity: 1, filter: \"blur(0px)\", transform: \"none\" },\n        { opacity: 0, filter: \"blur(4px)\", transform: `translateY(${lift}em)` },\n      ],\n      { duration: duration * 0.6, easing: EASE, fill: \"forwards\" },\n    );\n    animation.onfinish = () => onDone(glyph.key);\n    return () => animation.cancel();\n  }, [glyph.key, lift, duration, onDone]);\n  return (\n    <span\n      ref={ref}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute whitespace-pre\"\n      style={{ left: glyph.x, top: glyph.y }}\n    >\n      {glyph.char}\n    </span>\n  );\n}\n\nexport function TextMorph({\n  children: text,\n  duration = 460,\n  direction = \"up\",\n  animateWidth = true,\n  className = \"\",\n  ...props\n}: TextMorphProps) {\n  const reduced = useReducedMotion();\n  const counter = React.useRef(text.length);\n  const nextKey = React.useCallback(() => ++counter.current, []);\n  const [glyphs, setGlyphs] = React.useState<Glyph[]>(() =>\n    Array.from(text).map((char, i) => ({ key: i + 1, char })),\n  );\n  const [leaving, setLeaving] = React.useState<Leaving[]>([]);\n  const rootRef = React.useRef<HTMLSpanElement>(null);\n  const els = React.useRef(new Map<number, HTMLSpanElement>());\n  const before = React.useRef<{\n    at: Map<number, { x: number; y: number }>;\n    width: number;\n  } | null>(null);\n  const rise = direction === \"up\" ? 0.35 : -0.35;\n\n  // A preference change must also finish an in-flight morph whose target text\n  // already matches the glyphs (including the empty label in a folded receipt).\n  React.useLayoutEffect(() => {\n    if (!reduced) return;\n    before.current = null;\n    const root = rootRef.current;\n    root\n      ?.getAnimations({ subtree: true })\n      .forEach((animation) => animation.cancel());\n    if (root) root.style.whiteSpace = \"\";\n    setLeaving((previous) => (previous.length ? [] : previous));\n  }, [reduced]);\n\n  // 1. The text changed: note where every letter stands, then work out which letters stay.\n  React.useLayoutEffect(() => {\n    if (text === glyphs.map((g) => g.char).join(\"\")) return;\n    const root = rootRef.current;\n    if (!root || reduced) {\n      setLeaving([]);\n      setGlyphs(Array.from(text).map((char) => ({ key: nextKey(), char })));\n      return;\n    }\n    const box = root.getBoundingClientRect();\n    const at = new Map<number, { x: number; y: number }>();\n    els.current.forEach((el, key) => {\n      const r = el.getBoundingClientRect();\n      at.set(key, { x: r.left - box.left, y: r.top - box.top });\n    });\n    before.current = { at, width: box.width };\n    const next = morph(glyphs, text, nextKey);\n    const kept = new Set(next.map((g) => g.key));\n    setLeaving((l) => [\n      ...l,\n      ...glyphs\n        .filter((g) => !kept.has(g.key))\n        .map((g) => ({ ...g, ...(at.get(g.key) ?? { x: 0, y: 0 }) })),\n    ]);\n    setGlyphs(next);\n  }, [text, reduced]);\n\n  // 2. The new letters are in place: glide the ones that stayed, raise the new ones, ease the width.\n  React.useLayoutEffect(() => {\n    const prev = before.current;\n    const root = rootRef.current;\n    if (!prev || !root) return;\n    before.current = null;\n    const box = root.getBoundingClientRect();\n    let order = 0;\n    for (const g of glyphs) {\n      const el = els.current.get(g.key);\n      if (!el) continue;\n      const from = prev.at.get(g.key);\n      if (from) {\n        const r = el.getBoundingClientRect();\n        const dx = from.x - (r.left - box.left);\n        const dy = from.y - (r.top - box.top);\n        if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5)\n          el.animate(\n            [\n              { transform: `translate(${dx}px, ${dy}px)` },\n              { transform: \"none\" },\n            ],\n            { duration, easing: EASE },\n          );\n      } else {\n        el.animate(\n          [\n            {\n              opacity: 0,\n              filter: \"blur(4px)\",\n              transform: `translateY(${rise}em)`,\n            },\n            { opacity: 1, filter: \"blur(0px)\", transform: \"none\" },\n          ],\n          {\n            duration,\n            easing: EASE,\n            delay: Math.min(order++ * 16, 160),\n            fill: \"backwards\",\n          },\n        );\n      }\n    }\n    if (animateWidth && Math.abs(prev.width - box.width) > 0.5) {\n      // Hold the words on one line while the box is narrower than them, or \"No credits left\" would wrap mid-morph.\n      root.style.whiteSpace = \"nowrap\";\n      const resize = root.animate(\n        [{ width: `${prev.width}px` }, { width: `${box.width}px` }],\n        { duration, easing: EASE },\n      );\n      resize.onfinish = resize.oncancel = () => {\n        root.style.whiteSpace = \"\";\n      };\n    }\n  }, [glyphs, duration, rise, animateWidth]);\n\n  const done = React.useCallback(\n    (key: number) => setLeaving((l) => l.filter((g) => g.key !== key)),\n    [],\n  );\n\n  // Words stay unbroken; lines may only wrap at spaces.\n  const words: Glyph[][] = [];\n  for (const g of glyphs) {\n    if (\n      g.char === \" \" ||\n      !words.length ||\n      words[words.length - 1][0]?.char === \" \"\n    )\n      words.push([g]);\n    else words[words.length - 1].push(g);\n  }\n\n  return (\n    <span\n      ref={rootRef}\n      className={`relative inline-block ${className}`}\n      {...props}\n    >\n      <span className=\"sr-only\">{text}</span>\n      {words.map((word, w) => (\n        <span\n          key={w}\n          aria-hidden=\"true\"\n          className=\"inline-block whitespace-pre\"\n        >\n          {word.map((g) => (\n            <span\n              key={g.key}\n              ref={(el) => {\n                if (el) els.current.set(g.key, el);\n                else els.current.delete(g.key);\n              }}\n              className=\"inline-block\"\n            >\n              {g.char}\n            </span>\n          ))}\n        </span>\n      ))}\n      {leaving.map((g) => (\n        <LeavingGlyph\n          key={`out-${g.key}`}\n          glyph={g}\n          lift={-rise}\n          duration={duration}\n          onDone={done}\n        />\n      ))}\n    </span>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/imported-ui-interaction-motion.ts",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport const EASE_OUT = \"cubic-bezier(0.16, 1, 0.3, 1)\";\nexport const EASE_SETTLE = \"cubic-bezier(0.22, 1.18, 0.36, 1)\";\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = \"cubic-bezier(0.34, 1.36, 0.64, 1)\";\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  \"transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100\";\nexport const INTERACTION_FOCUS =\n  \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background\";\n\nconst query = \"(prefers-reduced-motion: reduce)\";\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", notify);\n  return () => media.removeEventListener(\"change\", notify);\n};\nexport const useInteractionReducedMotion = () =>\n  React.useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) =>\n      setVisible(entry.isIntersecting),\n    );\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility();\n    document.addEventListener(\"visibilitychange\", visibility);\n    return () => {\n      observer.disconnect();\n      document.removeEventListener(\"visibilitychange\", visibility);\n    };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(\n  on: boolean,\n  reduced: boolean,\n): React.CSSProperties {\n  return {\n    opacity: on ? 1 : 0,\n    transform: on ? \"none\" : \"scale(0.6)\",\n    filter: on ? \"blur(0px)\" : \"blur(3px)\",\n    transition: reduced\n      ? \"none\"\n      : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}`,\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(\n  samples: PointerSample[],\n  x: number,\n  time: number,\n) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100)\n    return 0;\n  const first = samples[0],\n    last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(\n  overshoot: number,\n  dimension = 320,\n  constant = 0.55,\n): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(\n  distance: number,\n  velocity: number,\n  time = 0.12,\n): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(\n  velocity: number,\n  distanceToTarget: number,\n  factor = 10,\n): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient =\n    (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value =\n      to +\n      Math.exp(-damping * omega * t) *\n        (displacement * Math.cos(damped * t) +\n          coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n",
      "type": "registry:component"
    }
  ],
  "css": {},
  "meta": {
    "cavemio": {
      "component": "action-button",
      "exportName": "ActionButton",
      "categories": [
        "buttons"
      ],
      "isNew": true,
      "usage": "import { ActionButton } from \"@/components/action-button\";\nimport { CloudUpload } from \"lucide-react\";\n\n<ActionButton\n  icon={<CloudUpload size={14} />}\n  labels={{\n    idle: \"Save changes\",\n    pending: \"Saving...\",\n    success: \"Saved!\",\n    error: \"Failed\",\n  }}\n  action={async () => {\n    await saveSettings();\n  }}\n/>",
      "accessibility": "- Busy uses aria-disabled, not disabled, so focus stays on the button while it works.\n- A status region outside the button announces each state; the shake is WAAPI, the check a drawn stroke.\n- onError receives whatever the action threw.",
      "previewNote": "Interactive local fixture. Data and async results are simulated in the preview; the caller supplies application services.",
      "documentation": {
        "props": [
          {
            "name": "action",
            "type": "() => Promise<unknown> | void",
            "description": "– · Async or sync callback executed on click. Drives status automatically."
          },
          {
            "name": "status",
            "type": "\"idle\" | \"pending\" | \"success\" | \"error\"",
            "description": "– · Controlled status override."
          },
          {
            "name": "labels",
            "type": "Partial<Record<ActionStatus, string>>",
            "description": "– · Custom labels per status state."
          },
          {
            "name": "variant",
            "type": "\"primary\" | \"secondary\" | \"destructive\" | \"outline\" | \"ghost\"",
            "description": "\"primary\" · Visual style."
          },
          {
            "name": "size",
            "type": "\"sm\" | \"md\" | \"lg\"",
            "description": "\"md\" · Button scale and typography."
          },
          {
            "name": "resetAfter",
            "type": "number",
            "description": "2000 · Duration in ms before auto-reverting from success/error to idle."
          }
        ],
        "useCases": [
          {
            "title": "Form submissions",
            "description": "Primary save/update actions that communicate network progress without modal overlays."
          },
          {
            "title": "Deployments & builds",
            "description": "Triggering long-running workflows with clear pending feedback and auto-reset."
          },
          {
            "title": "Destructive confirmations",
            "description": "Critical actions like purging data or deleting workspaces with affirmative feedback."
          }
        ],
        "features": [
          {
            "title": "Promise-driven state machine",
            "description": "Pass an async action callback; the button manages idle, pending, success, and error states automatically."
          },
          {
            "title": "In-place character morphing",
            "description": "Labels transition using TextMorph, animating shared glyphs with spring physics."
          },
          {
            "title": "Self-drawing checkmark",
            "description": "On success, a crisp thin line checkmark draws itself with SVG strokeDashoffset easing."
          },
          {
            "title": "Tactile error shake",
            "description": "On failure, the button executes an organic horizontal shake via WAAPI to catch peripheral attention."
          }
        ],
        "states": [
          {
            "title": "idle",
            "description": "Resting state with optional leading icon and label."
          },
          {
            "title": "pending",
            "description": "Interaction disabled; spinner opens and label morphs to pending state."
          },
          {
            "title": "success",
            "description": "Self-drawing checkmark and affirmative feedback before auto-resetting."
          },
          {
            "title": "error",
            "description": "Error badge and horizontal WAAPI shake alerting the user."
          }
        ]
      }
    }
  },
  "type": "registry:component"
}