{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cavemio-approval-card",
  "title": "Approval card",
  "description": "The agent asks before it acts: what it wants to do, the details, Approve or Deny.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/components/approval-card.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { Ban, Clock, ShieldQuestion } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * APPROVAL CARD: the agent asks before it acts\n *\n *   pending   what it wants to do, with Approve and Deny; an\n *             optional countdown rolls down second by second\n *   approved  the card folds into one line: the body closes,\n *             \"Needs your approval\" morphs to \"Approved\" and a\n *             check draws itself where the shield was\n *   denied    folds the same way into \"Denied\"\n *   expired   the countdown reaches 0:00 and it folds into\n *             \"Expired\"\n *\n * One surface throughout: it changes shape instead of being\n * replaced. Works controlled (pass status) or on its own (it\n * remembers the choice). Mark destructive actions so Approve\n * reads as such.\n * ───────────────────────────────────────────────────────── */\n\nexport type ApprovalStatus = \"pending\" | \"approved\" | \"denied\" | \"expired\";\n\nexport interface ApprovalDetail {\n  label: string;\n  value: React.ReactNode;\n}\n\nexport interface ApprovalCardProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"title\"\n> {\n  /** What the agent wants to do, e.g. \"Send email to 3 people\". */\n  title: string;\n  description?: string;\n  /** The specifics worth checking before approving. */\n  details?: ApprovalDetail[];\n  /** Why approval is needed, e.g. AI SDK's approval.requestReason. */\n  reason?: string;\n  status?: ApprovalStatus;\n  defaultStatus?: ApprovalStatus;\n  onApprove?: () => void;\n  onDeny?: () => void;\n  approveLabel?: string;\n  denyLabel?: string;\n  /** Styles Approve as a destructive action. */\n  destructive?: boolean;\n  /** When the request lapses (ms). Shows a countdown, then expires. */\n  expiresAt?: number;\n  onExpire?: () => void;\n}\n\nconst MORPH = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS =\n  \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst LABELS: Record<ApprovalStatus, string> = {\n  pending: \"Needs your approval\",\n  approved: \"Approved\",\n  denied: \"Denied\",\n  expired: \"Expired\",\n};\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/** Icons trade places through a blur: the old one shrinks away as the new one grows in. */\nconst swap = (on: boolean, reduced: boolean): React.CSSProperties => ({\n  opacity: on ? 1 : 0,\n  transform: on ? \"none\" : \"scale(0.6)\",\n  filter: on ? \"none\" : \"blur(3px)\",\n  transition: reduced\n    ? \"none\"\n    : `opacity 260ms ${MORPH}, transform 380ms ${MORPH}, filter 260ms ${MORPH}`,\n});\n\nfunction DrawnCheck({ drawn, reduced }: { drawn: boolean; reduced: boolean }) {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-3.5\">\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 ${MORPH} 160ms`\n              : \"none\",\n        }}\n      />\n    </svg>\n  );\n}\n\nexport function ApprovalCard({\n  title,\n  description,\n  details,\n  reason,\n  status,\n  defaultStatus = \"pending\",\n  onApprove,\n  onDeny,\n  approveLabel = \"Approve\",\n  denyLabel = \"Deny\",\n  destructive = false,\n  expiresAt,\n  onExpire,\n  className = \"\",\n  ...props\n}: ApprovalCardProps) {\n  const reduced = useReducedMotion();\n  const [ownStatus, setOwnStatus] =\n    React.useState<ApprovalStatus>(defaultStatus);\n  const current = status ?? ownStatus;\n  const decided = current !== \"pending\";\n  const [now, setNow] = React.useState(expiresAt ?? 0);\n  const cardRef = React.useRef<HTMLDivElement>(null);\n\n  // Count down while pending; expire on time.\n  React.useEffect(() => {\n    if (current !== \"pending\" || expiresAt === undefined) return;\n    const tick = () => {\n      const t = Date.now();\n      setNow(t);\n      if (t >= expiresAt) {\n        if (status === undefined) setOwnStatus(\"expired\");\n        onExpire?.();\n      }\n    };\n    tick();\n    const timer = window.setInterval(tick, 1000);\n    return () => window.clearInterval(timer);\n  }, [current, expiresAt, status, onExpire]);\n\n  const decide = (next: \"approved\" | \"denied\") => {\n    // The buttons are about to fold away: keep focus on the card instead of dropping it on the page.\n    if (cardRef.current?.contains(document.activeElement))\n      cardRef.current.focus({ preventScroll: true });\n    if (status === undefined) setOwnStatus(next);\n    if (next === \"approved\") onApprove?.();\n    else onDeny?.();\n  };\n\n  const left =\n    expiresAt === undefined\n      ? 0\n      : Math.max(0, Math.ceil((expiresAt - now) / 1000));\n  const icons: Record<ApprovalStatus, React.ReactNode> = {\n    pending: <ShieldQuestion className=\"size-3.5\" />,\n    approved: (\n      <span className=\"text-emerald-600 dark:text-emerald-400\">\n        <DrawnCheck drawn={current === \"approved\"} reduced={reduced} />\n      </span>\n    ),\n    denied: <Ban className=\"size-3.5\" />,\n    expired: <Clock className=\"size-3.5\" />,\n  };\n  const fold = (open: boolean): React.CSSProperties => ({\n    gridTemplateRows: open ? \"1fr\" : \"0fr\",\n    transition: reduced ? \"none\" : `grid-template-rows 480ms ${MORPH}`,\n  });\n  const fade = (on: boolean): React.CSSProperties => ({\n    opacity: on ? 1 : 0,\n    filter: on ? \"none\" : \"blur(4px)\",\n    transition: reduced\n      ? \"none\"\n      : on\n        ? `opacity 380ms ${MORPH} 120ms, filter 380ms ${MORPH} 120ms`\n        : `opacity 160ms ease-out, filter 160ms ease-out`,\n  });\n\n  return (\n    <div\n      ref={cardRef}\n      tabIndex={-1}\n      role=\"group\"\n      aria-label={\n        decided ? `${LABELS[current]}: ${title}` : `Approval needed: ${title}`\n      }\n      className={`rounded-xl border border-border bg-background outline-none animate-[ui-fade-up_320ms_cubic-bezier(0.23,1,0.32,1)_both] motion-reduce:animate-none ${className}`}\n      style={{\n        padding: decided ? \"10px 12px\" : 16,\n        transition: reduced ? \"none\" : `padding 480ms ${MORPH}`,\n      }}\n      {...props}\n    >\n      {/* The header is also the folded line: it keeps its place while everything under it closes. */}\n      <div className=\"flex min-w-0 items-center gap-2 text-[12.5px] font-medium\">\n        <span\n          aria-hidden=\"true\"\n          className={`relative flex size-3.5 shrink-0 items-center justify-center transition-colors duration-300 ${decided ? \"text-foreground/70\" : \"text-muted-foreground\"}`}\n        >\n          {(Object.keys(icons) as ApprovalStatus[]).map((s) => (\n            <span\n              key={s}\n              className=\"absolute inset-0 flex items-center justify-center\"\n              style={swap(s === current, reduced)}\n            >\n              {icons[s]}\n            </span>\n          ))}\n        </span>\n        <span\n          className={`shrink-0 transition-colors duration-300 ${decided ? \"text-foreground\" : \"text-muted-foreground\"}`}\n        >\n          <TextMorph>{LABELS[current]}</TextMorph>\n        </span>\n        {/* The action slides into the line as the card folds. */}\n        <span\n          aria-hidden={!decided || undefined}\n          className=\"grid min-w-0 flex-1\"\n          style={{\n            gridTemplateColumns: decided ? \"1fr\" : \"0fr\",\n            ...fade(decided),\n            transition: reduced\n              ? \"none\"\n              : `grid-template-columns 480ms ${MORPH}, ${decided ? `opacity 380ms ${MORPH} 160ms, filter 380ms ${MORPH} 160ms` : \"opacity 160ms ease-out, filter 160ms ease-out\"}`,\n          }}\n        >\n          <span className=\"min-w-0 truncate font-normal text-muted-foreground\">\n            {title}\n          </span>\n        </span>\n        {expiresAt !== undefined && (\n          <span\n            aria-hidden={decided || undefined}\n            className=\"ml-auto grid shrink-0\"\n            style={{\n              gridTemplateColumns: decided ? \"0fr\" : \"1fr\",\n              ...fade(!decided),\n              transition: reduced\n                ? \"none\"\n                : `grid-template-columns 480ms ${MORPH}, opacity 160ms ease-out, filter 160ms ease-out`,\n            }}\n          >\n            <span className=\"flex min-w-0 overflow-hidden font-mono font-normal tabular-nums text-muted-foreground\">\n              <span className=\"sr-only\">Time left: </span>\n              <NumberRoll value={Math.floor(left / 60)} duration={600} />\n              <span aria-hidden=\"true\">:</span>\n              <NumberRoll\n                value={left % 60}\n                format={{ minimumIntegerDigits: 2 }}\n                direction=\"down\"\n                duration={600}\n              />\n            </span>\n          </span>\n        )}\n      </div>\n\n      {/* Everything else folds shut once it's answered. */}\n      <div\n        inert={decided}\n        aria-hidden={decided || undefined}\n        className=\"grid\"\n        style={fold(!decided)}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          <div style={fade(!decided)}>\n            <p className=\"pt-2 text-[14px] font-medium leading-snug text-foreground\">\n              {title}\n            </p>\n            {description && (\n              <p className=\"mt-1 text-[13px] leading-relaxed text-muted-foreground\">\n                {description}\n              </p>\n            )}\n\n            {details && details.length > 0 && (\n              <dl className=\"mt-3 grid grid-cols-[minmax(0,auto)_1fr] gap-x-4 gap-y-1.5 rounded-lg bg-muted px-3 py-2.5 text-[12.5px]\">\n                {details.map((d) => (\n                  <React.Fragment key={d.label}>\n                    <dt className=\"text-muted-foreground\">{d.label}</dt>\n                    <dd className=\"min-w-0 break-words text-foreground\">\n                      {d.value}\n                    </dd>\n                  </React.Fragment>\n                ))}\n              </dl>\n            )}\n\n            {reason && (\n              <p className=\"mt-2.5 text-[12px] leading-relaxed text-muted-foreground\">\n                {reason}\n              </p>\n            )}\n\n            <div className=\"mt-4 flex justify-end gap-2\">\n              <button\n                type=\"button\"\n                onClick={() => decide(\"denied\")}\n                className={`cursor-pointer h-8 rounded-lg border border-border px-3 text-[12.5px] font-medium text-foreground transition-colors hover:bg-accent ${FOCUS}`}\n              >\n                {denyLabel}\n              </button>\n              <button\n                type=\"button\"\n                onClick={() => decide(\"approved\")}\n                className={`cursor-pointer h-8 rounded-lg px-3.5 text-[12.5px] font-medium transition-[background-color,transform] active:scale-[0.98] ${FOCUS} ${\n                  destructive\n                    ? \"bg-red-600 text-white hover:bg-red-700\"\n                    : \"bg-primary text-primary-foreground hover:bg-primary/90\"\n                }`}\n              >\n                {approveLabel}\n              </button>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      {/* Announces the answer; outside the buttons so their names stay their labels. */}\n      <span role=\"status\" className=\"sr-only\">\n        {decided ? `${LABELS[current]}: ${title}` : \"\"}\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/number-roll.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * NUMBER ROLL: numbers that change like an odometer\n *\n *   rolling   each digit is a column that rolls to its new\n *             value, in the direction the number moved: going\n *             up, a 9 rolls on to 0 instead of spinning back\n *   places    new places slide open from nothing; lost ones\n *             fold away\n *   format    anything Intl.NumberFormat does: currency,\n *             percent, compact (\"1.2K\"), decimals\n *\n * The real number is always there as text for screen readers\n * and copy and paste; the columns are only what you see.\n * ───────────────────────────────────────────────────────── */\n\nexport interface NumberRollProps extends Omit<\n  React.HTMLAttributes<HTMLSpanElement>,\n  \"children\"\n> {\n  value: number;\n  /** Intl.NumberFormat options, e.g. { style: \"currency\", currency: \"USD\" }. */\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n  prefix?: string;\n  suffix?: string;\n  /** Start from this value and roll to `value` once mounted, e.g. 0 for stats. */\n  from?: number;\n  /** Roll duration in ms. */\n  duration?: number;\n  /** Always roll this way, e.g. \"down\" for a countdown's seconds, which wrap from 00 to 59. Defaults to the way the number moved. */\n  direction?: \"up\" | \"down\";\n}\n\ntype Column = { key: string; char: string; digit: number | null };\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst SETS = 5; // the strip repeats 0–9 five times so a roll never runs out of digits\nconst MIDDLE = 20;\n/** The strip as one text node, a digit a line: fifty lines, but one element to lay out instead of fifty. */\nconst STRIP = Array.from({ length: SETS * 10 }, (_, i) => i % 10).join(\"\\n\");\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/** Digits are keyed by their place counted from the right, so the units column stays the units column. */\nfunction columns(text: string): Column[] {\n  const chars = [...text];\n  const seen = new Map<string, number>();\n  let place = 0;\n  const out: Column[] = [];\n  for (let i = chars.length - 1; i >= 0; i--) {\n    const char = chars[i];\n    if (/\\d/.test(char))\n      out.push({ key: `d${place++}`, char, digit: Number(char) });\n    else {\n      // Symbols are keyed by how many of the same symbol sit to their right, so a comma that shifts is the same comma.\n      const n = seen.get(char) ?? 0;\n      seen.set(char, n + 1);\n      out.push({ key: `s${char}${n}`, char, digit: null });\n    }\n  }\n  return out.reverse();\n}\n\n// Memoised: a parent that re-renders with the same number doesn't rebuild the strips.\nconst Digit = React.memo(function Digit({\n  digit,\n  trend,\n  duration,\n  reduced,\n  rollIn,\n}: {\n  digit: number;\n  trend: number;\n  duration: number;\n  reduced: boolean;\n  rollIn: boolean;\n}) {\n  const [pos, setPos] = React.useState(MIDDLE + (rollIn ? 0 : digit));\n  const [moving, setMoving] = React.useState(false);\n  const posRef = React.useRef(pos);\n  const stripRef = React.useRef<HTMLSpanElement>(null);\n\n  React.useLayoutEffect(() => {\n    const current = posRef.current;\n    const showing = ((current % 10) + 10) % 10;\n    if (showing === digit) return;\n    if (reduced) {\n      posRef.current = MIDDLE + digit;\n      setMoving(false);\n      setPos(MIDDLE + digit);\n      return;\n    }\n    const up = trend > 0 || (trend === 0 && digit > showing);\n    let target = up\n      ? current + ((digit - showing + 10) % 10)\n      : current - ((showing - digit + 10) % 10);\n    // Values arriving faster than a roll (a progress percent) never let it re-centre, so before it runs off the strip,\n    // jump the strip back by whole sets mid-roll (it looks identical) and roll on from there.\n    if (target < 10 || target > SETS * 10 - 11) {\n      const shift = Math.round((target - MIDDLE) / 10) * 10;\n      const strip = stripRef.current;\n      if (strip?.offsetHeight) {\n        let visual = current;\n        try {\n          visual =\n            -new DOMMatrixReadOnly(getComputedStyle(strip).transform).m42 /\n            (strip.offsetHeight / (SETS * 10));\n        } catch {}\n        const transition = strip.style.transition;\n        strip.style.transition = \"none\";\n        strip.style.transform = `translateY(${(-(visual - shift) * 100) / (SETS * 10)}%)`;\n        void strip.offsetHeight;\n        strip.style.transition = transition;\n      }\n      target -= shift;\n    }\n    posRef.current = target;\n    setMoving(true);\n    setPos(target);\n  }, [digit, trend, reduced]);\n\n  // After a roll, quietly re-centre on the middle set so the next roll always has room.\n  const settle = () => {\n    const centred = MIDDLE + (((posRef.current % 10) + 10) % 10);\n    posRef.current = centred;\n    setMoving(false);\n    setPos(centred);\n  };\n\n  return (\n    <span className=\"relative inline-block [clip-path:inset(0)]\">\n      <span className=\"invisible\">{digit}</span>\n      <span\n        ref={stripRef}\n        aria-hidden=\"true\"\n        onTransitionEnd={settle}\n        className=\"absolute inset-x-0 top-0 block whitespace-pre text-center\"\n        style={{\n          transform: `translateY(${(-pos * 100) / (SETS * 10)}%)`,\n          transition: moving ? `transform ${duration}ms ${EASE}` : \"none\",\n        }}\n      >\n        {STRIP}\n      </span>\n    </span>\n  );\n});\n\n/** A place that appeared after the first paint slides open; places that were there from the start just sit. */\nfunction Place({\n  enter,\n  children,\n}: {\n  enter: boolean;\n  children: React.ReactNode;\n}) {\n  const [entering] = React.useState(enter);\n  return (\n    <span\n      className={`inline-block ${entering ? \"[clip-path:inset(0)] animate-[ui-col-in_500ms_cubic-bezier(0.16,1,0.3,1)_both]\" : \"\"}`}\n    >\n      {children}\n    </span>\n  );\n}\n\nexport function NumberRoll({\n  value,\n  format,\n  locales,\n  prefix = \"\",\n  suffix = \"\",\n  from,\n  duration = 900,\n  direction,\n  className = \"\",\n  ...props\n}: NumberRollProps) {\n  const reduced = useReducedMotion();\n  const [shown, setShown] = React.useState(from ?? value);\n  const previous = React.useRef(shown);\n  const mounted = React.useRef(false);\n\n  // Roll from `from` to the real value once on screen (a frame later, so the start is painted).\n  React.useEffect(() => {\n    const frame = requestAnimationFrame(() => setShown(value));\n    return () => cancelAnimationFrame(frame);\n  }, [value]);\n\n  React.useEffect(() => {\n    mounted.current = true;\n  }, []);\n\n  const formatter = React.useMemo(\n    () => new Intl.NumberFormat(locales, format),\n    [locales, format && JSON.stringify(format)],\n  );\n  const text = `${prefix}${formatter.format(shown)}${suffix}`;\n  const cols = React.useMemo(() => columns(text), [text]);\n  const trend =\n    direction === \"up\"\n      ? 1\n      : direction === \"down\"\n        ? -1\n        : Math.sign(shown - previous.current);\n\n  // Places that disappear fold away instead of vanishing.\n  const [leaving, setLeaving] = React.useState<Column[]>([]);\n  const lastCols = React.useRef(cols);\n  React.useLayoutEffect(() => {\n    const gone = lastCols.current.filter(\n      (c) => !cols.some((n) => n.key === c.key),\n    );\n    lastCols.current = cols;\n    previous.current = shown;\n    if (!gone.length || reduced) return;\n    setLeaving(gone);\n    const timer = window.setTimeout(() => setLeaving([]), 420);\n    return () => window.clearTimeout(timer);\n  }, [cols, shown, reduced]);\n\n  return (\n    <span className={`inline-flex tabular-nums ${className}`} {...props}>\n      <span className=\"sr-only\">{`${prefix}${formatter.format(value)}${suffix}`}</span>\n      <span\n        aria-hidden=\"true\"\n        className=\"inline-flex items-baseline whitespace-pre\"\n      >\n        {leaving.map((c) => (\n          <span\n            key={`out-${c.key}`}\n            className=\"inline-block [clip-path:inset(0)] animate-[ui-col-out_400ms_cubic-bezier(0.16,1,0.3,1)_forwards]\"\n          >\n            {c.char}\n          </span>\n        ))}\n        {cols.map((c) => (\n          <Place key={c.key} enter={mounted.current && !reduced}>\n            {c.digit === null ? (\n              c.char\n            ) : (\n              <Digit\n                digit={c.digit}\n                trend={trend}\n                duration={duration}\n                reduced={reduced}\n                rollIn={mounted.current}\n              />\n            )}\n          </Place>\n        ))}\n      </span>\n    </span>\n  );\n}\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"
    }
  ],
  "css": {
    "@keyframes ui-col-in": {
      "from": {
        "max-width": "0",
        "opacity": "0"
      },
      "to": {
        "max-width": "1em",
        "opacity": "1"
      }
    },
    "@keyframes ui-col-out": {
      "from": {
        "max-width": "1em",
        "opacity": "1"
      },
      "to": {
        "max-width": "0",
        "opacity": "0"
      }
    },
    "@keyframes ui-fade-up": {
      "from": {
        "opacity": "0",
        "transform": "translateY(4px)"
      },
      "to": {
        "opacity": "1",
        "transform": "none"
      }
    }
  },
  "meta": {
    "cavemio": {
      "component": "approval-card",
      "exportName": "ApprovalCard",
      "categories": [
        "ai"
      ],
      "isNew": false,
      "usage": "import { ApprovalCard } from \"@/components/approval-card\";\n\n<ApprovalCard\n  title=\"Send email to 3 people\"\n  description=\"The agent drafted a follow-up and wants to send it from your address.\"\n  details={[\n    { label: \"To\", value: \"maya@acme.com, +2 more\" },\n    { label: \"Subject\", value: \"Thursday tasting menu\" },\n  ]}\n  onApprove={send}\n  onDeny={skip}\n/>",
      "accessibility": "- The card is a labelled group in every state; the outcome is announced from a status region inside it, so screen readers hear \"Approved: Send email to 3 people\".\n- When you answer, focus moves to the card itself rather than dropping to the page as the buttons fold away. The folded body is inert.\n- The countdown is not a live region, so it never chatters; its digits are hidden from assistive tech and the time is real text.\n- Installs Number roll and Text morph. With reduced motion, the card changes state in place.\n- Approve is never focused automatically, so a stray Enter can’t approve an action.\n- Details wrap rather than truncate, because they are what the user is approving.",
      "previewNote": "Interactive local fixture. Data and async results are simulated in the preview; the caller supplies application services.",
      "documentation": {
        "props": [
          {
            "name": "title / description",
            "type": "string",
            "description": "– · What the agent wants to do, in plain words."
          },
          {
            "name": "details",
            "type": "{ label; value }[]",
            "description": "– · The specifics worth checking: recipients, amounts, files."
          },
          {
            "name": "reason",
            "type": "string",
            "description": "– · Why approval is needed, e.g. the AI SDK’s requestReason."
          },
          {
            "name": "status / defaultStatus",
            "type": "\"pending\" | \"approved\" | \"denied\" | \"expired\"",
            "description": "\"pending\" · Controlled, or let the card remember the choice."
          },
          {
            "name": "onApprove / onDeny",
            "type": "() => void",
            "description": "– · Send the decision back to your agent."
          },
          {
            "name": "approveLabel / denyLabel",
            "type": "string",
            "description": "\"Approve\" / \"Deny\" · Name the actual action, e.g. \"Send\" and \"Don’t send\"."
          },
          {
            "name": "destructive",
            "type": "boolean",
            "description": "false · Red Approve for deletes, payments and other irreversible actions."
          },
          {
            "name": "expiresAt / onExpire",
            "type": "number / () => void",
            "description": "– · Countdown to when the request lapses."
          }
        ],
        "useCases": [
          {
            "title": "AI agent chats",
            "description": "Ask before the agent sends an email, deletes files or spends money."
          },
          {
            "title": "Payments and billing",
            "description": "Ask before a refund, a plan change or a large payment goes out."
          },
          {
            "title": "Workflow tools",
            "description": "A step that waits for a person’s go-ahead before the run continues."
          },
          {
            "title": "Admin tools",
            "description": "A sign-off before something that can’t be undone, such as deleting a project."
          }
        ],
        "features": [
          {
            "title": "It says what will happen",
            "description": "A title, a description and a list of the specifics worth checking, such as recipients, amounts or files."
          },
          {
            "title": "Approve or Deny",
            "description": "Name the real action (“Send” and “Don’t send”) and get onApprove or onDeny back."
          },
          {
            "title": "Red for irreversible",
            "description": "Set destructive for deletes and payments and Approve turns red."
          },
          {
            "title": "It becomes the receipt",
            "description": "The same card folds into one line, “Approved” with a drawn check, rather than being swapped for something new."
          },
          {
            "title": "Requests can expire",
            "description": "A countdown rolls down like a clock and the card folds into “Expired” when it reaches zero."
          },
          {
            "title": "Hard to approve by accident",
            "description": "Approve is never focused automatically, so a stray Enter can’t approve an action."
          }
        ],
        "states": [
          {
            "title": "pending",
            "description": "The request with its details and Deny / Approve. With expiresAt, a countdown whose digits roll down each second (00 rolls back to 59, like a clock)."
          },
          {
            "title": "approved",
            "description": "One motion over 480ms: the body folds shut and blurs out, the padding tightens, the action slides into the header line, the label morphs to \"Approved\" and an emerald check draws itself in place of the shield."
          },
          {
            "title": "denied",
            "description": "Folds the same way into \"Denied\" with a ban icon; the agent carries on without it."
          },
          {
            "title": "expired",
            "description": "The countdown reaches 0:00, folds away with the body, and the label morphs to \"Expired\"."
          }
        ]
      }
    }
  },
  "type": "registry:component"
}