{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cavemio-auth-card",
  "title": "Auth card",
  "description": "Sign-in that asks one thing at a time: the email field shrinks into a chip round the address, and your server decides whether a password, a code or a link comes next.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/components/auth-card.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowUpRight, Eye, EyeOff, KeyRound } from \"lucide-react\";\nimport { CodeInput } from \"./code-input\";\nimport { NumberRoll } from \"./number-roll\";\nimport { StatusButton, type ActionStatus } from \"./status-button\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * AUTH CARD: sign-in that asks one thing at a time\n *\n *   email     sign-in providers, then the email field; your\n *             server decides what comes next (a password, a\n *             code or a link), the way identifier-first sign-in\n *             works at Google and Clerk\n *   identity  the email field doesn't go anywhere: its frame\n *             shrinks round the address into a chip as the\n *             providers fold away above it, and \"Change\" opens\n *             at its end to take you back\n *   step      each next step slides in from the right (Change\n *             slides back from the left) while the card eases\n *             to its new height; titles lift out and in\n *   code      the code boxes (code input) check as the last\n *             digit lands, and resend counts down\n *   link      \"Check your inbox\", with a button that opens the\n *             inbox itself for Gmail, Outlook, iCloud, Yahoo\n *             and Proton addresses\n *   done      a ring draws, a check draws inside it, \"Signed in\"\n *\n * The card never calls a service: every step is one async\n * function, so it fits Better Auth, Clerk, Supabase or Auth.js.\n * ───────────────────────────────────────────────────────── */\n\nexport type AuthNext = \"password\" | \"code\" | \"link\";\nexport type AuthStep = \"email\" | AuthNext | \"reset\" | \"done\";\n\nexport interface AuthProvider {\n  id: string;\n  label: string;\n  icon?: React.ReactNode;\n}\n\nexport interface AuthCardProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"title\"\n> {\n  mode?: \"sign-in\" | \"sign-up\";\n  /** Above the title: your mark. */\n  logo?: React.ReactNode;\n  /** Words per step: { email: { title, description }, code: { … }, … }. */\n  copy?: Partial<Record<AuthStep, { title?: string; description?: string }>>;\n  providers?: AuthProvider[];\n  /** Starts a provider's sign-in; usually it redirects, so the button keeps spinning. */\n  onProvider?: (id: string) => Promise<unknown> | unknown;\n  /** Shows \"Sign in with a passkey\". Resolve when signed in. */\n  onPasskey?: () => Promise<unknown>;\n  /** Your server says what comes next for this address. Throw to say why not. */\n  onEmail: (email: string) => Promise<AuthNext> | AuthNext;\n  onPassword?: (email: string, password: string) => Promise<unknown>;\n  /** Resolve when the code is right; throw when it isn't. */\n  onCode?: (email: string, code: string) => Promise<unknown>;\n  /** Sends the code or link again. */\n  onResend?: (email: string) => Promise<unknown>;\n  /** Shows \"Forgot password?\" on the password step; sends a reset link. */\n  onForgot?: (email: string) => Promise<unknown>;\n  /** After \"Signed in\" has shown, e.g. to redirect. */\n  onSuccess?: () => void;\n  defaultEmail?: string;\n  codeLength?: number;\n  /** Seconds before a code or link can be sent again. */\n  resendAfter?: number;\n  /** Under the card's content: terms, a link to sign up. */\n  footer?: React.ReactNode;\n}\n\nconst EASE = \"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 EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst SHAKE = [\n  { transform: \"none\" },\n  { transform: \"translateX(-4px)\" },\n  { transform: \"translateX(4px)\" },\n  { transform: \"translateX(-2px)\" },\n  { transform: \"none\" },\n];\nconst ORDER: AuthStep[] = [\n  \"email\",\n  \"password\",\n  \"code\",\n  \"link\",\n  \"reset\",\n  \"done\",\n];\nconst INBOXES: [RegExp, string, string][] = [\n  [\n    /^(gmail|googlemail)\\.com$/,\n    \"Gmail\",\n    \"https://mail.google.com/mail/u/0/#inbox\",\n  ],\n  [\n    /^(outlook|hotmail|live|msn)\\.[a-z.]+$/,\n    \"Outlook\",\n    \"https://outlook.live.com/mail/\",\n  ],\n  [/^(icloud|me|mac)\\.com$/, \"iCloud Mail\", \"https://www.icloud.com/mail\"],\n  [/^yahoo\\.[a-z.]+$/, \"Yahoo Mail\", \"https://mail.yahoo.com\"],\n  [\n    /^(proton\\.me|protonmail\\.com|pm\\.me)$/,\n    \"Proton Mail\",\n    \"https://mail.proton.me\",\n  ],\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\nconst message = (e: unknown, fallback: string) =>\n  e instanceof Error && e.message ? e.message : fallback;\nconst inboxFor = (email: string) => {\n  const domain = email.split(\"@\")[1]?.toLowerCase() ?? \"\";\n  const hit = INBOXES.find(([re]) => re.test(domain));\n  return hit ? { name: hit[1], href: hit[2] } : null;\n};\n\n/** A line that changes by lifting the old words out through a blur and the new ones in. */\nfunction Line({\n  text,\n  className = \"\",\n  reduced,\n  as: Tag = \"p\",\n  id,\n}: {\n  text: string;\n  className?: string;\n  reduced: boolean;\n  as?: \"p\" | \"h2\";\n  id?: string;\n}) {\n  const [shown, setShown] = React.useState(text);\n  const [old, setOld] = React.useState<{ key: number; text: string }[]>([]);\n  const key = React.useRef(0);\n  const ref = React.useRef<HTMLSpanElement>(null);\n  if (text !== shown) {\n    if (!reduced && shown)\n      setOld((o) => [...o, { key: ++key.current, text: shown }]);\n    setShown(text);\n  }\n  React.useLayoutEffect(() => {\n    if (reduced || !old.length) return;\n    ref.current?.animate(\n      [\n        { opacity: 0, transform: \"translateY(0.3em)\", filter: \"blur(4px)\" },\n        { opacity: 1, transform: \"none\", filter: \"blur(0px)\" },\n      ],\n      { duration: 380, delay: 80, easing: EASE, fill: \"backwards\" },\n    );\n  }, [shown]);\n  return (\n    <Tag id={id} className={`relative ${className}`}>\n      <span ref={ref} className=\"block\">\n        {shown}\n      </span>\n      {old.map((o) => (\n        <Leaving\n          key={o.key}\n          onDone={() => setOld((all) => all.filter((x) => x.key !== o.key))}\n        >\n          {o.text}\n        </Leaving>\n      ))}\n    </Tag>\n  );\n}\n\nfunction Leaving({\n  children,\n  onDone,\n}: {\n  children: React.ReactNode;\n  onDone: () => void;\n}) {\n  const ref = React.useRef<HTMLSpanElement>(null);\n  React.useLayoutEffect(() => {\n    const a = ref.current?.animate(\n      [\n        { opacity: 1, filter: \"blur(0px)\" },\n        { opacity: 0, transform: \"translateY(-0.3em)\", filter: \"blur(4px)\" },\n      ],\n      { duration: 220, easing: EASE, fill: \"forwards\" },\n    );\n    if (a) a.onfinish = onDone;\n    return () => a?.cancel();\n  }, []);\n  return (\n    <span\n      ref={ref}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute inset-x-0 top-0 block\"\n    >\n      {children}\n    </span>\n  );\n}\n\nfunction Fold({\n  open,\n  reduced,\n  children,\n}: {\n  open: boolean;\n  reduced: boolean;\n  children: React.ReactNode;\n}) {\n  const [kept, setKept] = React.useState(children);\n  if (open && kept !== children) {\n    setKept(children);\n  }\n  return (\n    <div\n      className=\"grid\"\n      inert={!open}\n      aria-hidden={!open || undefined}\n      style={{\n        gridTemplateRows: open ? \"1fr\" : \"0fr\",\n        opacity: open ? 1 : 0,\n        transition: reduced\n          ? \"none\"\n          : `grid-template-rows 460ms ${EASE}, opacity ${open ? 320 : 180}ms ${EASE}`,\n      }}\n    >\n      <div className=\"min-h-0 overflow-clip [overflow-clip-margin:6px]\">\n        {open ? children : kept}\n      </div>\n    </div>\n  );\n}\n\n/** The steps under the identity: the new one slides in from the side you went, the old one out the other way, and the box eases to fit. */\nfunction Slides({\n  step,\n  dir,\n  reduced,\n  render,\n}: {\n  step: AuthStep;\n  dir: number;\n  reduced: boolean;\n  render: (s: AuthStep) => React.ReactNode;\n}) {\n  const [faces, setFaces] = React.useState<\n    { s: AuthStep; out: boolean; dir: number; enter: boolean }[]\n  >([{ s: step, out: false, dir, enter: false }]);\n  const [seen, setSeen] = React.useState(step);\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const height = React.useRef(0);\n  // Clipped only while a step slides; at rest a menu can open past its edge.\n  const [moving, setMoving] = React.useState(false);\n  React.useEffect(() => {\n    if (!moving) return;\n    const timer = window.setTimeout(() => setMoving(false), 560);\n    return () => window.clearTimeout(timer);\n  }, [moving, step]);\n  if (seen !== step) {\n    setSeen(step);\n    if (!reduced) setMoving(true);\n    setFaces((f) => [\n      ...f.filter((x) => x.out && x.s !== step && x.s !== seen),\n      ...(reduced ? [] : [{ s: seen, out: true, dir, enter: false }]),\n      { s: step, out: false, dir, enter: true },\n    ]);\n  }\n\n  React.useLayoutEffect(() => {\n    const el = boxRef.current;\n    if (!el) return;\n    height.current = el.offsetHeight;\n    const observer = new ResizeObserver(\n      () => (height.current = el.offsetHeight),\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const el = boxRef.current;\n    if (!el || reduced) return;\n    const to = el.offsetHeight;\n    if (Math.abs(to - height.current) > 0.5)\n      el.animate([{ height: `${height.current}px` }, { height: `${to}px` }], {\n        duration: 460,\n        easing: EASE,\n      });\n  }, [step]);\n\n  return (\n    <div\n      ref={boxRef}\n      className=\"relative [overflow-clip-margin:8px]\"\n      style={{ overflowY: moving ? \"clip\" : \"visible\" }}\n    >\n      {faces.map((f) => (\n        <Face\n          key={f.s}\n          out={f.out}\n          enter={f.enter}\n          dir={f.dir}\n          reduced={reduced}\n          onGone={() =>\n            setFaces((all) => all.filter((x) => !(x.s === f.s && x.out)))\n          }\n        >\n          {render(f.s)}\n        </Face>\n      ))}\n    </div>\n  );\n}\n\nfunction Face({\n  out,\n  enter,\n  dir,\n  reduced,\n  onGone,\n  children,\n}: {\n  out: boolean;\n  enter: boolean;\n  dir: number;\n  reduced: boolean;\n  onGone: () => void;\n  children: React.ReactNode;\n}) {\n  const ref = React.useRef<HTMLDivElement>(null);\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    // A face that comes back while it was still leaving drops its exit first.\n    el.getAnimations().forEach((a) => a.cancel());\n    if (reduced) return;\n    if (out) {\n      const a = el.animate(\n        [\n          { opacity: 1, transform: \"none\", filter: \"blur(0px)\" },\n          {\n            opacity: 0,\n            transform: `translateX(${-dir * 28}px)`,\n            filter: \"blur(4px)\",\n          },\n        ],\n        { duration: 240, easing: EASE, fill: \"forwards\" },\n      );\n      a.onfinish = onGone;\n      return;\n    }\n    if (!enter) return;\n    el.animate(\n      [\n        {\n          opacity: 0,\n          transform: `translateX(${dir * 28}px)`,\n          filter: \"blur(4px)\",\n        },\n        { opacity: 1, transform: \"none\", filter: \"blur(0px)\" },\n      ],\n      { duration: 440, delay: 80, easing: EASE, fill: \"backwards\" },\n    );\n  }, [out]);\n  return (\n    <div\n      ref={ref}\n      inert={out}\n      aria-hidden={out || undefined}\n      className={out ? \"pointer-events-none absolute inset-x-0 top-0\" : \"\"}\n    >\n      {children}\n    </div>\n  );\n}\n\n/** \"Resend in 0:28\", rolling down; then Resend → Sending → Sent, and the clock starts again. */\nfunction Resend({\n  after,\n  reduced,\n  onResend,\n}: {\n  after: number;\n  reduced: boolean;\n  onResend: () => Promise<unknown>;\n}) {\n  const [since, setSince] = React.useState(() => Date.now());\n  const [now, setNow] = React.useState(since);\n  const [status, setStatus] = React.useState<ActionStatus>(\"idle\");\n  const left = Math.max(0, since + after * 1000 - now);\n  const counting = left > 0;\n  React.useEffect(() => {\n    if (!counting) return;\n    const timer = window.setTimeout(\n      () => setNow(Date.now()),\n      1000 - (Date.now() % 1000) + 10,\n    );\n    return () => window.clearTimeout(timer);\n  }, [counting, now]);\n  React.useEffect(() => {\n    if (status !== \"success\" && status !== \"error\") return;\n    const timer = window.setTimeout(\n      () => setStatus(\"idle\"),\n      status === \"success\" ? 1400 : 2400,\n    );\n    return () => window.clearTimeout(timer);\n  }, [status]);\n  const ready = !counting && status !== \"pending\" && status !== \"success\";\n  const label =\n    status === \"pending\"\n      ? \"Sending\"\n      : status === \"success\"\n        ? \"Sent\"\n        : status === \"error\"\n          ? \"Try again\"\n          : counting\n            ? \"Resend in\"\n            : \"Resend\";\n  const s = Math.ceil(left / 1000);\n  return (\n    <button\n      type=\"button\"\n      aria-disabled={!ready || undefined}\n      aria-label={counting ? \"Resend, available shortly\" : \"Resend\"}\n      onClick={async () => {\n        if (!ready) return;\n        setStatus(\"pending\");\n        try {\n          await onResend();\n          setStatus(\"success\");\n          setSince(Date.now());\n          setNow(Date.now());\n        } catch {\n          setStatus(\"error\");\n        }\n      }}\n      className={`inline-flex h-7 cursor-pointer items-center rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap tabular-nums transition-colors aria-disabled:cursor-default ${FOCUS} ${\n        status === \"error\"\n          ? \"text-red-600 dark:text-red-400\"\n          : ready\n            ? \"text-foreground hover:bg-accent\"\n            : \"text-muted-foreground\"\n      }`}\n    >\n      <TextMorph>{label}</TextMorph>\n      <span\n        aria-hidden=\"true\"\n        className=\"inline-grid\"\n        style={{\n          gridTemplateColumns: counting && status === \"idle\" ? \"1fr\" : \"0fr\",\n          opacity: counting && status === \"idle\" ? 1 : 0,\n          transition: reduced\n            ? \"none\"\n            : `grid-template-columns 380ms ${EASE}, opacity 260ms ${EASE}`,\n        }}\n      >\n        <span className=\"min-w-0 [clip-path:inset(-4px_0)]\">\n          <span className=\"inline-flex items-baseline pl-[0.25em]\">\n            <NumberRoll value={Math.floor(s / 60)} direction=\"down\" />:\n            <NumberRoll\n              value={s % 60}\n              format={{ minimumIntegerDigits: 2 }}\n              direction=\"down\"\n            />\n          </span>\n        </span>\n      </span>\n    </button>\n  );\n}\n\n/** A ring that draws itself, then a check inside it. */\nfunction Done({ reduced }: { reduced: boolean }) {\n  const ring = React.useRef<SVGCircleElement>(null);\n  const check = React.useRef<SVGPathElement>(null);\n  React.useLayoutEffect(() => {\n    if (reduced) return;\n    ring.current?.animate([{ strokeDashoffset: 1 }, { strokeDashoffset: 0 }], {\n      duration: 640,\n      delay: 120,\n      easing: EASE,\n      fill: \"backwards\",\n    });\n    check.current?.animate([{ strokeDashoffset: 1 }, { strokeDashoffset: 0 }], {\n      duration: 420,\n      delay: 560,\n      easing: EASE,\n      fill: \"backwards\",\n    });\n  }, [reduced]);\n  return (\n    <svg\n      viewBox=\"0 0 48 48\"\n      fill=\"none\"\n      aria-hidden=\"true\"\n      className=\"size-12 text-emerald-600 dark:text-emerald-400\"\n    >\n      <circle cx=\"24\" cy=\"24\" r=\"22.5\" stroke=\"var(--border)\" strokeWidth=\"1\" />\n      <circle\n        ref={ring}\n        cx=\"24\"\n        cy=\"24\"\n        r=\"22.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.25\"\n        pathLength={1}\n        strokeDasharray={1}\n        transform=\"rotate(-90 24 24)\"\n        strokeDashoffset={0}\n      />\n      <path\n        ref={check}\n        d=\"M16.5 24.5 21.5 29.5 31.5 18.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        pathLength={1}\n        strokeDasharray={1}\n        strokeDashoffset={0}\n      />\n    </svg>\n  );\n}\n\nexport function AuthCard({\n  mode = \"sign-in\",\n  logo,\n  copy,\n  providers = [],\n  onProvider,\n  onPasskey,\n  onEmail,\n  onPassword,\n  onCode,\n  onResend,\n  onForgot,\n  onSuccess,\n  defaultEmail = \"\",\n  codeLength = 6,\n  resendAfter = 30,\n  footer,\n  className = \"\",\n  ...props\n}: AuthCardProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const [step, setStep] = React.useState<AuthStep>(\"email\");\n  const [dir, setDir] = React.useState(1);\n  const [email, setEmail] = React.useState(defaultEmail);\n  const [password, setPassword] = React.useState(\"\");\n  const [showPassword, setShowPassword] = React.useState(false);\n  const [busy, setBusy] = React.useState<string | null>(null);\n  const [status, setStatus] = React.useState<ActionStatus>(\"idle\");\n  const [error, setError] = React.useState<string | null>(null);\n  const [announce, setAnnounce] = React.useState(\"\");\n  const [chipWidth, setChipWidth] = React.useState(0);\n  const shellRef = React.useRef<HTMLDivElement>(null);\n  const emailRef = React.useRef<HTMLInputElement>(null);\n  const mirrorRef = React.useRef<HTMLSpanElement>(null);\n  const changeRef = React.useRef<HTMLButtonElement>(null);\n  const passwordRef = React.useRef<HTMLInputElement>(null);\n  const bodyRef = React.useRef<HTMLDivElement>(null);\n  const identity = step !== \"email\";\n  const signUp = mode === \"sign-up\";\n\n  const words: Record<AuthStep, { title: string; description: string }> = {\n    email: {\n      title: signUp ? \"Create your account\" : \"Sign in\",\n      description: signUp\n        ? \"Start with your work email.\"\n        : \"Welcome back. Use the email you signed up with.\",\n    },\n    password: { title: \"Enter your password\", description: \"\" },\n    code: {\n      title: \"Check your email\",\n      description: \"We sent you a code. It works for 10 minutes.\",\n    },\n    link: {\n      title: \"Check your inbox\",\n      description: \"We sent you a sign-in link. It works for 10 minutes.\",\n    },\n    reset: {\n      title: \"Check your inbox\",\n      description: \"We sent a link to reset your password.\",\n    },\n    done: {\n      title: signUp ? \"You're in\" : \"Signed in\",\n      description: \"Taking you to your workspace.\",\n    },\n  };\n  const title = copy?.[step]?.title ?? words[step].title;\n  const description = copy?.[step]?.description ?? words[step].description;\n\n  const go = (next: AuthStep) => {\n    setDir(ORDER.indexOf(next) >= ORDER.indexOf(step) ? 1 : -1);\n    setError(null);\n    setStatus(\"idle\");\n    setStep(next);\n    setAnnounce(copy?.[next]?.title ?? words[next].title);\n  };\n\n  const shake = (el: Element | null | undefined) => {\n    if (!reduced) el?.animate(SHAKE, { duration: 380, easing: \"ease-out\" });\n  };\n\n  // The chip is as wide as the address plus \"Change\".\n  React.useLayoutEffect(() => {\n    const m = mirrorRef.current;\n    const c = changeRef.current;\n    if (!m || !c) return;\n    const w = Math.ceil(m.offsetWidth + c.offsetWidth + 6);\n    setChipWidth((p) => (p === w ? p : w));\n  }, [email, identity]);\n\n  // Each step puts focus on the thing to do next.\n  React.useEffect(() => {\n    const body = bodyRef.current;\n    if (step === \"email\") {\n      if (dir < 0) emailRef.current?.select();\n      return;\n    }\n    const timer = window.setTimeout(\n      () => {\n        if (step === \"password\")\n          passwordRef.current?.focus({ preventScroll: true });\n        else\n          body\n            ?.querySelector<HTMLElement>(\n              \"[data-autofocus], input, a[href], button:not([aria-disabled])\",\n            )\n            ?.focus({ preventScroll: true });\n      },\n      reduced ? 0 : 120,\n    );\n    return () => window.clearTimeout(timer);\n  }, [step]);\n\n  React.useEffect(() => {\n    if (step !== \"done\" || !onSuccess) return;\n    const timer = window.setTimeout(onSuccess, reduced ? 400 : 1300);\n    return () => window.clearTimeout(timer);\n  }, [step, onSuccess, reduced]);\n\n  const submitEmail = async () => {\n    if (status === \"pending\") return;\n    const value = email.trim();\n    if (!EMAIL.test(value)) {\n      setError(\n        value\n          ? `“${value}” doesn't look like an email address.`\n          : \"Enter your email address.\",\n      );\n      shake(shellRef.current);\n      emailRef.current?.focus();\n      return;\n    }\n    setEmail(value);\n    setStatus(\"pending\");\n    setError(null);\n    try {\n      const next = await onEmail(value);\n      go(next);\n    } catch (e) {\n      setStatus(\"error\");\n      setError(message(e, \"We couldn't check that address. Try again.\"));\n      shake(shellRef.current);\n    }\n  };\n\n  const submitPassword = async () => {\n    if (status === \"pending\" || !onPassword) return;\n    if (!password) {\n      setError(\"Enter your password.\");\n      shake(passwordRef.current?.parentElement);\n      return;\n    }\n    setStatus(\"pending\");\n    setError(null);\n    try {\n      await onPassword(email, password);\n      go(\"done\");\n    } catch (e) {\n      setStatus(\"error\");\n      setError(message(e, \"That password isn't right.\"));\n      shake(passwordRef.current?.parentElement);\n      passwordRef.current?.select();\n    }\n  };\n\n  const runProvider = async (key: string, run: () => unknown) => {\n    if (busy) return;\n    setBusy(key);\n    setError(null);\n    try {\n      await run();\n      // A redirect never gets here; a popup or a passkey does.\n      go(\"done\");\n    } catch (e) {\n      setBusy(null);\n      setError(\n        message(\n          e,\n          key === \"passkey\"\n            ? \"Passkey sign-in didn't finish.\"\n            : \"That sign-in didn't finish. Try again.\",\n        ),\n      );\n    }\n  };\n\n  const errorLine = (\n    <Fold open={Boolean(error)} reduced={reduced}>\n      <p\n        id={`${id}-error`}\n        className=\"pt-2 text-[12px] text-red-600 dark:text-red-400\"\n      >\n        {error}\n      </p>\n    </Fold>\n  );\n\n  const inbox = inboxFor(email);\n  const render = (s: AuthStep): React.ReactNode => {\n    if (s === \"email\")\n      return (\n        <div className=\"pt-3\">\n          <StatusButton\n            type=\"submit\"\n            status={status}\n            labels={{\n              idle: \"Continue\",\n              pending: \"Checking\",\n              success: \"Continue\",\n              error: \"Try again\",\n            }}\n            className=\"w-full\"\n          />\n          {onPasskey && (\n            <button\n              type=\"button\"\n              onClick={() => runProvider(\"passkey\", onPasskey)}\n              aria-busy={busy === \"passkey\" || undefined}\n              className={`mt-2 inline-flex h-9 w-full cursor-pointer items-center justify-center gap-2 rounded-full text-[13px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground aria-busy:cursor-default ${FOCUS}`}\n            >\n              {busy === \"passkey\" ? (\n                <span className=\"size-3.5 animate-spin rounded-full border-[1.5px] border-current border-t-transparent motion-reduce:animate-none\" />\n              ) : (\n                <KeyRound\n                  className=\"size-4\"\n                  strokeWidth={1.75}\n                  aria-hidden=\"true\"\n                />\n              )}\n              <TextMorph>\n                {busy === \"passkey\"\n                  ? \"Waiting for your passkey\"\n                  : \"Sign in with a passkey\"}\n              </TextMorph>\n            </button>\n          )}\n        </div>\n      );\n    if (s === \"password\")\n      return (\n        <div className=\"pt-3\">\n          <label\n            htmlFor={`${id}-password`}\n            className=\"text-[12px] font-medium text-muted-foreground\"\n          >\n            Password\n          </label>\n          <div\n            className={`mt-1.5 flex h-10 items-center rounded-[12px] pr-1 transition-shadow ${error ? \"shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-red-500)_45%,transparent)]\" : \"shadow-[inset_0_0_0_1px_var(--border)] focus-within:shadow-[inset_0_0_0_1px_var(--ring)]\"}`}\n          >\n            <input\n              ref={passwordRef}\n              id={`${id}-password`}\n              type={showPassword ? \"text\" : \"password\"}\n              autoComplete={signUp ? \"new-password\" : \"current-password\"}\n              value={password}\n              onChange={(e) => {\n                setPassword(e.target.value);\n                setError(null);\n                if (status === \"error\") setStatus(\"idle\");\n              }}\n              aria-invalid={Boolean(error) || undefined}\n              aria-describedby={error ? `${id}-error` : undefined}\n              className=\"h-full min-w-0 flex-1 bg-transparent px-3 text-[16px] text-foreground outline-none [@media(pointer:fine)]:text-[14px]\"\n            />\n            <button\n              type=\"button\"\n              aria-label={showPassword ? \"Hide password\" : \"Show password\"}\n              aria-pressed={showPassword}\n              onClick={() => setShowPassword((v) => !v)}\n              className={`relative grid size-8 shrink-0 cursor-pointer place-items-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground ${FOCUS}`}\n            >\n              {[false, true].map((on) => (\n                <span\n                  key={String(on)}\n                  aria-hidden=\"true\"\n                  className=\"absolute inset-0 grid place-items-center\"\n                  style={{\n                    opacity: showPassword === on ? 1 : 0,\n                    transform: showPassword === on ? \"none\" : \"scale(0.6)\",\n                    filter:\n                      showPassword === on || reduced ? \"none\" : \"blur(3px)\",\n                    transition: reduced\n                      ? \"none\"\n                      : `opacity 240ms ${EASE}, transform 360ms ${EASE}, filter 240ms ${EASE}`,\n                  }}\n                >\n                  {on ? (\n                    <EyeOff className=\"size-4\" strokeWidth={1.75} />\n                  ) : (\n                    <Eye className=\"size-4\" strokeWidth={1.75} />\n                  )}\n                </span>\n              ))}\n            </button>\n          </div>\n          {errorLine}\n          <div className=\"mt-3 flex items-center justify-between gap-2\">\n            {onForgot ? (\n              <ForgotButton\n                onForgot={async () => {\n                  await onForgot(email);\n                  go(\"reset\");\n                }}\n              />\n            ) : (\n              <span />\n            )}\n            <StatusButton\n              type=\"submit\"\n              status={status}\n              labels={{\n                idle: \"Sign in\",\n                pending: \"Signing in\",\n                success: \"Signed in\",\n                error: \"Try again\",\n              }}\n            />\n          </div>\n        </div>\n      );\n    if (s === \"code\")\n      return (\n        <div className=\"pt-4\">\n          <CodeInput\n            length={codeLength}\n            autoFocus\n            onComplete={async (code) => {\n              await onCode?.(email, code);\n              window.setTimeout(() => go(\"done\"), reduced ? 0 : 900);\n              return true;\n            }}\n            onResend={onResend ? () => onResend(email) : undefined}\n            resendAfter={resendAfter}\n          />\n        </div>\n      );\n    if (s === \"link\" || s === \"reset\")\n      return (\n        <div className=\"flex flex-wrap items-center gap-2 pt-4\">\n          {inbox && (\n            <a\n              data-autofocus=\"\"\n              href={inbox.href}\n              target=\"_blank\"\n              rel=\"noopener noreferrer\"\n              className={`inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/90 ${FOCUS}`}\n            >\n              Open {inbox.name}\n              <ArrowUpRight\n                className=\"size-3.5\"\n                strokeWidth={2}\n                aria-hidden=\"true\"\n              />\n            </a>\n          )}\n          {onResend && (\n            <Resend\n              after={resendAfter}\n              reduced={reduced}\n              onResend={() => onResend(email)}\n            />\n          )}\n        </div>\n      );\n    return (\n      <div className=\"flex flex-col items-center pt-5 pb-1 text-center\">\n        <Done reduced={reduced} />\n      </div>\n    );\n  };\n\n  return (\n    <div\n      className={`w-full rounded-[22px] border border-border bg-background p-5 text-foreground sm:p-6 ${className}`}\n      {...props}\n    >\n      {logo && <div className=\"mb-4\">{logo}</div>}\n      <Line\n        as=\"h2\"\n        id={`${id}-title`}\n        text={title}\n        reduced={reduced}\n        className=\"text-[19px] font-medium tracking-[-0.02em]\"\n      />\n      <Fold open={Boolean(description)} reduced={reduced}>\n        <Line\n          text={description}\n          reduced={reduced}\n          className=\"mt-1 text-[13px] leading-[1.5] text-muted-foreground\"\n        />\n      </Fold>\n\n      <form\n        noValidate\n        aria-labelledby={`${id}-title`}\n        onSubmit={(e) => {\n          e.preventDefault();\n          if (step === \"email\") submitEmail();\n          else if (step === \"password\") submitPassword();\n        }}\n      >\n        {/* Providers fold away above the address once it's chosen. */}\n        <Fold open={!identity && providers.length > 0} reduced={reduced}>\n          <div className=\"pt-5\">\n            <div\n              className={`grid gap-2 ${providers.length > 1 ? \"grid-cols-2\" : \"\"}`}\n            >\n              {providers.map((p) => (\n                <button\n                  key={p.id}\n                  type=\"button\"\n                  onClick={() =>\n                    onProvider && runProvider(p.id, () => onProvider(p.id))\n                  }\n                  aria-busy={busy === p.id || undefined}\n                  disabled={Boolean(busy) && busy !== p.id}\n                  className={`inline-flex h-10 cursor-pointer items-center justify-center gap-2 rounded-full text-[13px] font-medium shadow-[inset_0_0_0_1px_var(--border)] transition-[background-color,opacity] duration-200 hover:bg-accent disabled:cursor-default disabled:opacity-40 aria-busy:cursor-default ${FOCUS}`}\n                >\n                  <span\n                    className=\"relative grid size-4 place-items-center [&_svg]:size-4\"\n                    aria-hidden=\"true\"\n                  >\n                    <span\n                      className=\"absolute inset-0 grid place-items-center\"\n                      style={{\n                        opacity: busy === p.id ? 0 : 1,\n                        transform: busy === p.id ? \"scale(0.6)\" : \"none\",\n                        transition: reduced\n                          ? \"none\"\n                          : `opacity 200ms ${EASE}, transform 320ms ${EASE}`,\n                      }}\n                    >\n                      {p.icon}\n                    </span>\n                    <span\n                      className={`absolute inset-0.5 rounded-full border-[1.5px] border-current border-t-transparent motion-reduce:animate-none ${busy === p.id ? \"animate-spin\" : \"\"}`}\n                      style={{\n                        opacity: busy === p.id ? 1 : 0,\n                        transition: reduced ? \"none\" : `opacity 200ms ${EASE}`,\n                      }}\n                    />\n                  </span>\n                  {p.label}\n                </button>\n              ))}\n            </div>\n            <div\n              className=\"mt-5 flex items-center gap-3 text-[11.5px] text-muted-foreground\"\n              aria-hidden=\"true\"\n            >\n              <span className=\"h-px flex-1 bg-border\" />\n              or\n              <span className=\"h-px flex-1 bg-border\" />\n            </div>\n          </div>\n        </Fold>\n\n        <div className=\"pt-4\">\n          {!identity && (\n            <label\n              htmlFor={`${id}-email`}\n              className=\"mb-1.5 block text-[12px] font-medium text-muted-foreground\"\n            >\n              Email\n            </label>\n          )}\n          {/* The address: a field, then the same frame shrunk round it as a chip. */}\n          <div\n            ref={shellRef}\n            className=\"relative flex items-center overflow-hidden\"\n            style={{\n              width: identity ? chipWidth || \"auto\" : \"100%\",\n              maxWidth: \"100%\",\n              height: identity ? 32 : 40,\n              borderRadius: identity ? 16 : 12,\n              boxShadow: identity\n                ? \"inset 0 0 0 1px var(--border)\"\n                : error && step === \"email\"\n                  ? \"inset 0 0 0 1px color-mix(in oklab, var(--color-red-500) 45%, transparent)\"\n                  : undefined,\n              transition: reduced\n                ? \"none\"\n                : `width 520ms ${EASE}, height 520ms ${EASE}, border-radius 520ms ${EASE}, box-shadow 200ms`,\n            }}\n          >\n            <span\n              aria-hidden=\"true\"\n              className={`pointer-events-none absolute inset-0 rounded-[inherit] transition-shadow duration-200 ${identity || (error && step === \"email\") ? \"\" : \"shadow-[inset_0_0_0_1px_var(--border)] [:focus-within>&]:shadow-[inset_0_0_0_1px_var(--ring)]\"}`}\n            />\n            <span\n              ref={mirrorRef}\n              aria-hidden=\"true\"\n              className=\"pointer-events-none invisible absolute left-0 top-0 whitespace-pre px-3 text-[16px] [@media(pointer:fine)]:text-[14px]\"\n            >\n              {email || \" \"}\n            </span>\n            <input\n              ref={emailRef}\n              id={`${id}-email`}\n              type=\"email\"\n              inputMode=\"email\"\n              autoComplete={onPasskey ? \"username webauthn\" : \"email\"}\n              placeholder=\"you@company.com\"\n              value={email}\n              readOnly={identity || status === \"pending\"}\n              tabIndex={identity ? -1 : undefined}\n              aria-label={identity ? `Signing in as ${email}` : undefined}\n              aria-invalid={(Boolean(error) && step === \"email\") || undefined}\n              aria-describedby={\n                error && step === \"email\" ? `${id}-error` : undefined\n              }\n              onChange={(e) => {\n                setEmail(e.target.value);\n                setError(null);\n                if (status === \"error\") setStatus(\"idle\");\n              }}\n              className=\"h-full min-w-0 flex-1 bg-transparent px-3 text-[16px] text-foreground outline-none placeholder:text-muted-foreground/70 [@media(pointer:fine)]:text-[14px]\"\n            />\n            <span\n              className=\"inline-grid shrink-0\"\n              style={{\n                gridTemplateColumns:\n                  identity && step !== \"done\" ? \"1fr\" : \"0fr\",\n                opacity: identity && step !== \"done\" ? 1 : 0,\n                transition: reduced\n                  ? \"none\"\n                  : `grid-template-columns 420ms ${EASE} ${identity ? 160 : 0}ms, opacity 260ms ${EASE} ${identity ? 220 : 0}ms`,\n              }}\n              inert={!identity || step === \"done\"}\n            >\n              <span className=\"min-w-0 overflow-clip\">\n                <button\n                  ref={changeRef}\n                  type=\"button\"\n                  onClick={() => {\n                    setPassword(\"\");\n                    go(\"email\");\n                  }}\n                  className={`mr-1 h-6 cursor-pointer rounded-full px-2 text-[12px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground ${FOCUS}`}\n                >\n                  Change\n                </button>\n              </span>\n            </span>\n          </div>\n          {step === \"email\" && errorLine}\n        </div>\n\n        <div ref={bodyRef}>\n          <Slides step={step} dir={dir} reduced={reduced} render={render} />\n        </div>\n      </form>\n\n      {footer && (\n        <Fold open={step === \"email\"} reduced={reduced}>\n          <div className=\"pt-5 text-center text-[12px] text-muted-foreground [&_a]:font-medium [&_a]:text-foreground [&_a]:underline-offset-2 hover:[&_a]:underline\">\n            {footer}\n          </div>\n        </Fold>\n      )}\n\n      <span className=\"sr-only\" role=\"status\">\n        {announce}\n      </span>\n    </div>\n  );\n}\n\nfunction ForgotButton({ onForgot }: { onForgot: () => Promise<void> }) {\n  const [status, setStatus] = React.useState<ActionStatus>(\"idle\");\n  return (\n    <button\n      type=\"button\"\n      aria-disabled={status === \"pending\" || undefined}\n      onClick={async () => {\n        if (status === \"pending\") return;\n        setStatus(\"pending\");\n        try {\n          await onForgot();\n        } catch {\n          setStatus(\"error\");\n        }\n      }}\n      className={`-ml-2 h-7 cursor-pointer rounded-full px-2 text-[12px] font-medium transition-colors hover:bg-accent ${FOCUS} ${status === \"error\" ? \"text-red-600 dark:text-red-400\" : \"text-muted-foreground hover:text-foreground\"}`}\n    >\n      <TextMorph>\n        {status === \"pending\"\n          ? \"Sending a link\"\n          : status === \"error\"\n            ? \"Couldn't send it. Try again\"\n            : \"Forgot password?\"}\n      </TextMorph>\n    </button>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/code-input.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { StatusButton, type ActionStatus } from \"./status-button\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * CODE INPUT: the six boxes, done properly\n *\n *   typing     each digit rises into its box out of a blur; the\n *              box you're on carries a blinking caret; deleting\n *              lifts a digit away rather than blinking it out\n *   paste      a pasted or autofilled code drops in one box after\n *              another\n *   checking   with every box full, the row carries a sweep of\n *              light while onComplete runs\n *   wrong      the row shakes, the boxes turn red, the label\n *              says so, and the digits clear from the right\n *   right      the digits stay where they are while the boxes'\n *              own outlines melt into one pill around them; a\n *              check draws itself at its end, \"Verified\"\n *   resend     \"Resend in 0:28\", the seconds rolling down, then\n *              a Resend button that spins, ticks and starts the\n *              clock again\n *\n * One real input sits over the boxes (one-time-code autofill,\n * paste and the numeric keyboard all just work); the boxes are\n * only what you see.\n * ───────────────────────────────────────────────────────── */\n\nexport interface CodeInputProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"onChange\" | \"defaultValue\"\n> {\n  length?: number;\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Runs when every box is filled. Resolve (or return true) to accept; throw or return false to reject. */\n  onComplete?: (code: string) => Promise<boolean | void> | boolean | void;\n  /** Shows the resend line; the clock starts on mount and after each resend. */\n  onResend?: () => Promise<unknown> | void;\n  /** Seconds before a code can be resent. */\n  resendAfter?: number;\n  label?: string;\n  /** Box groups, e.g. [3, 3] puts a dash between two threes. */\n  groups?: number[];\n  /** Letters as well as digits. */\n  alphanumeric?: boolean;\n  autoFocus?: boolean;\n}\n\ntype Phase = \"idle\" | \"checking\" | \"wrong\" | \"right\";\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst SHEEN =\n  \"[mask-image:linear-gradient(90deg,rgb(0_0_0/0.4)_35%,#000_50%,rgb(0_0_0/0.4)_65%)] [mask-size:200%_100%] animate-[ui-sheen_1.4s_linear_infinite] motion-reduce:animate-none motion-reduce:[mask-image:none]\";\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/** One character: rises in out of a blur when it arrives, lifts away when it goes. */\nfunction Glyph({\n  char,\n  delay,\n  reduced,\n}: {\n  char: string | undefined;\n  delay: number;\n  reduced: boolean;\n}) {\n  const [shown, setShown] = React.useState(char);\n  const [leaving, setLeaving] = React.useState(false);\n  const ref = React.useRef<HTMLSpanElement>(null);\n  // The character last drawn rising in: the one there on mount never rises, a new one always does.\n  const risen = React.useRef(char);\n  if (char !== undefined && (char !== shown || leaving)) {\n    setShown(char);\n    setLeaving(false);\n  } else if (\n    char === undefined &&\n    shown !== undefined &&\n    (!leaving || reduced)\n  ) {\n    // With reduced motion a character just goes; otherwise it lifts away first.\n    if (reduced) {\n      setShown(undefined);\n      setLeaving(false);\n    } else setLeaving(true);\n  }\n\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el || reduced) return;\n    if (leaving) {\n      const a = el.animate(\n        [\n          { opacity: 1, transform: \"none\", filter: \"blur(0px)\" },\n          { opacity: 0, transform: \"translateY(-35%)\", filter: \"blur(4px)\" },\n        ],\n        { duration: 200, delay, easing: EASE, fill: \"forwards\" },\n      );\n      a.onfinish = () => setShown(undefined);\n      return () => a.cancel();\n    }\n    if (shown === undefined) {\n      risen.current = undefined;\n      return;\n    }\n    if (risen.current === shown) return;\n    risen.current = shown;\n    const a = el.animate(\n      [\n        { opacity: 0, transform: \"translateY(45%)\", filter: \"blur(4px)\" },\n        { opacity: 1, transform: \"none\", filter: \"blur(0px)\" },\n      ],\n      { duration: 300, delay, easing: EASE, fill: \"backwards\" },\n    );\n    return () => a.cancel();\n  }, [shown, leaving]);\n\n  if (shown === undefined) return null;\n  return (\n    <span ref={ref} className=\"inline-block\">\n      {shown}\n    </span>\n  );\n}\n\nexport function CodeInput({\n  length = 6,\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  onComplete,\n  onResend,\n  resendAfter = 30,\n  label = `Enter the ${length}-digit code`,\n  groups,\n  alphanumeric = false,\n  autoFocus,\n  className = \"\",\n  ...props\n}: CodeInputProps) {\n  const reduced = useReducedMotion();\n  const id = React.useId();\n  const [own, setOwn] = React.useState(defaultValue.slice(0, length));\n  const code = (value ?? own).slice(0, length);\n  const [phase, setPhase] = React.useState<Phase>(\"idle\");\n  const [focused, setFocused] = React.useState(false);\n  const [arrival, setArrival] = React.useState({\n    length: code.length,\n    from: code.length,\n  });\n  const [clearing, setClearing] = React.useState(false);\n  // Resend clock: whole seconds, running from the start when there's a resend, and again after each one.\n  const [left, setLeft] = React.useState<number | null>(\n    onResend ? resendAfter : null,\n  );\n  const [resend, setResend] = React.useState<ActionStatus>(\"idle\");\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const rowRef = React.useRef<HTMLDivElement>(null);\n\n  // How the new characters arrived: one typed, or several at once (paste, autofill) to cascade in.\n  if (arrival.length !== code.length)\n    setArrival({ length: code.length, from: arrival.length });\n  const arrivedFrom = arrival.from;\n\n  const setCode = (next: string) => {\n    if (value === undefined) setOwn(next);\n    onValueChange?.(next);\n  };\n\n  const startClock = React.useCallback(\n    () => setLeft(resendAfter),\n    [resendAfter],\n  );\n  React.useEffect(() => {\n    if (left === null || left <= 0) return;\n    const timer = window.setTimeout(\n      () => setLeft((s) => (s === null ? s : s - 1)),\n      1000,\n    );\n    return () => window.clearTimeout(timer);\n  }, [left]);\n\n  const check = async (full: string) => {\n    if (!onComplete) return;\n    setPhase(\"checking\");\n    let ok = true;\n    try {\n      ok = (await onComplete(full)) !== false;\n    } catch {\n      ok = false;\n    }\n    if (ok) {\n      setPhase(\"right\");\n      inputRef.current?.blur();\n      return;\n    }\n    setPhase(\"wrong\");\n    if (!reduced) {\n      rowRef.current?.animate(\n        [\n          { transform: \"none\" },\n          { transform: \"translateX(-5px)\" },\n          { transform: \"translateX(5px)\" },\n          { transform: \"translateX(-3px)\" },\n          { transform: \"none\" },\n        ],\n        { duration: 380, easing: \"ease-out\" },\n      );\n    }\n    // Let the shake land, then clear from the right and start again at the first box.\n    window.setTimeout(\n      () => {\n        setClearing(true);\n        setCode(\"\");\n        inputRef.current?.focus();\n        window.setTimeout(() => setClearing(false), 400);\n      },\n      reduced ? 0 : 650,\n    );\n  };\n\n  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    if (phase === \"checking\" || phase === \"right\") return;\n    const raw = e.target.value;\n    const clean = (\n      alphanumeric\n        ? raw.replace(/[^a-z0-9]/gi, \"\").toUpperCase()\n        : raw.replace(/\\D/g, \"\")\n    ).slice(0, length);\n    if (phase === \"wrong\") setPhase(\"idle\");\n    setCode(clean);\n  };\n\n  // A full code, however it arrived (typed, pasted, autofilled or set from outside), gets checked once.\n  const lastLength = React.useRef(code.length);\n  React.useEffect(() => {\n    if (\n      code.length === length &&\n      lastLength.current < length &&\n      (phase === \"idle\" || phase === \"wrong\")\n    )\n      check(code);\n    lastLength.current = code.length;\n  }, [code]);\n\n  const doResend = async () => {\n    if (!onResend || resend === \"pending\") return;\n    setResend(\"pending\");\n    try {\n      await onResend();\n      setResend(\"success\");\n      window.setTimeout(\n        () => {\n          setResend(\"idle\");\n          startClock();\n        },\n        reduced ? 0 : 1100,\n      );\n    } catch {\n      setResend(\"error\");\n    }\n  };\n\n  // Where the dashes go between groups.\n  const breaks = new Set<number>();\n  if (groups)\n    groups.reduce((at, size) => (breaks.add(at + size), at + size), 0);\n  const right = phase === \"right\";\n  const wrong = phase === \"wrong\";\n  const active =\n    focused && phase !== \"checking\" && !right\n      ? Math.min(code.length, length - 1)\n      : -1;\n  const labelText = right\n    ? \"Verified\"\n    : wrong\n      ? \"That code didn't work\"\n      : phase === \"checking\"\n        ? \"Checking the code\"\n        : label;\n\n  return (\n    <div className={`@container w-full ${className}`} {...props}>\n      <label\n        htmlFor={id}\n        className={`block text-[12.5px] transition-colors duration-300 ${wrong ? \"text-red-600 dark:text-red-400\" : \"text-muted-foreground\"}`}\n      >\n        <TextMorph>{labelText}</TextMorph>\n      </label>\n\n      <div className=\"relative mt-2 w-fit\">\n        <input\n          ref={inputRef}\n          id={id}\n          value={code}\n          onChange={onChange}\n          onFocus={(e) => {\n            setFocused(true);\n            const end = e.currentTarget.value.length;\n            e.currentTarget.setSelectionRange(end, end);\n          }}\n          onBlur={() => setFocused(false)}\n          onSelect={(e) => {\n            // The caret always sits at the end; the boxes show where you are.\n            const el = e.currentTarget;\n            if (el.selectionStart !== el.value.length)\n              el.setSelectionRange(el.value.length, el.value.length);\n          }}\n          readOnly={phase === \"checking\" || right}\n          autoFocus={autoFocus}\n          autoComplete=\"one-time-code\"\n          inputMode={alphanumeric ? \"text\" : \"numeric\"}\n          pattern={alphanumeric ? \"[A-Za-z0-9]*\" : \"[0-9]*\"}\n          maxLength={length}\n          spellCheck={false}\n          aria-invalid={wrong || undefined}\n          className=\"absolute inset-0 z-10 h-full w-full cursor-text bg-transparent text-[16px] text-transparent caret-transparent opacity-0 outline-none [&::selection]:bg-transparent\"\n        />\n\n        {/* The boxes, and the one pill they become when the code is right. */}\n        <div\n          ref={rowRef}\n          aria-hidden=\"true\"\n          className={`relative flex items-center gap-[var(--code-gap,8px)] rounded-[12px] @max-[19rem]:gap-[var(--code-gap,4px)] transition-[box-shadow,background-color] duration-500 ${phase === \"checking\" ? SHEEN : \"\"}`}\n          style={{\n            boxShadow: right\n              ? \"0 0 0 1px color-mix(in oklab, #10b981 55%, transparent)\"\n              : \"0 0 0 1px transparent\",\n            background: right\n              ? \"color-mix(in oklab, #10b981 6%, var(--background))\"\n              : \"transparent\",\n            transitionTimingFunction: EASE,\n          }}\n        >\n          {Array.from({ length }, (_, i) => {\n            const char = code[i];\n            const isActive = i === active;\n            const cascade =\n              !clearing && code.length - arrivedFrom > 1 && i >= arrivedFrom\n                ? (i - arrivedFrom) * 45\n                : 0;\n            const exitDelay = clearing ? (length - 1 - i) * 30 : 0;\n            return (\n              <React.Fragment key={i}>\n                {/* The dash fades but keeps its place, so no digit moves when the code is right. */}\n                {breaks.has(i) && i > 0 && (\n                  <span\n                    className=\"mx-0.5 block h-px w-2 bg-muted-foreground/40 transition-opacity duration-300\"\n                    style={{ opacity: right ? 0 : 1 }}\n                  />\n                )}\n                <span\n                  className=\"relative flex h-10 w-[34px] shrink-0 items-center justify-center text-[18px] font-medium tabular-nums text-foreground transition-[box-shadow,background-color] duration-300 @max-[19rem]:w-[30px] @min-[22rem]:h-11 @min-[22rem]:w-9 @min-[22rem]:text-[19px]\"\n                  style={{\n                    borderRadius: 10,\n                    boxShadow: right\n                      ? \"inset 0 0 0 1px transparent\"\n                      : wrong\n                        ? \"inset 0 0 0 1px color-mix(in oklab, #ef4444 60%, transparent)\"\n                        : isActive\n                          ? \"inset 0 0 0 1.5px color-mix(in oklab, var(--ring) 70%, transparent)\"\n                          : \"inset 0 0 0 1px var(--border)\",\n                    background: right ? \"transparent\" : \"var(--background)\",\n                  }}\n                >\n                  <Glyph\n                    char={char}\n                    delay={char !== undefined ? cascade : exitDelay}\n                    reduced={reduced}\n                  />\n                  {/* The caret, blinking only in the box you're on. */}\n                  {isActive && char === undefined && (\n                    <span className=\"absolute h-5 w-px bg-foreground animate-[ui-blink_1s_steps(1)_infinite] motion-reduce:animate-none\" />\n                  )}\n                </span>\n              </React.Fragment>\n            );\n          })}\n\n          {/* The check at the end of the pill: the pill grows to the right for it, the digits stay put. */}\n          <span\n            className=\"grid transition-[grid-template-columns,opacity] duration-500\"\n            style={{\n              gridTemplateColumns: right ? \"1fr\" : \"0fr\",\n              opacity: right ? 1 : 0,\n              transitionTimingFunction: EASE,\n            }}\n          >\n            <span className=\"flex min-w-0 items-center overflow-hidden\">\n              <svg\n                viewBox=\"0 0 16 16\"\n                className=\"ml-1 mr-3 size-4 shrink-0 text-emerald-600\"\n                fill=\"none\"\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: right ? 0 : 1,\n                    transition: reduced\n                      ? \"none\"\n                      : `stroke-dashoffset 420ms ${EASE} 260ms`,\n                  }}\n                />\n              </svg>\n            </span>\n          </span>\n        </div>\n      </div>\n\n      {onResend && !right && (\n        <div className=\"mt-3 flex h-7 items-center gap-1.5 text-[12px] text-muted-foreground\">\n          <span>Didn’t get it?</span>\n          {/* The countdown and the button share one place; each fades through a blur into the other. */}\n          <span className=\"grid items-center\">\n            {/* The ticking digits stay out of screen readers; they hear that a resend is coming instead. */}\n            <span className=\"sr-only\">\n              {left && left > 0 ? \"You can resend the code shortly.\" : \"\"}\n            </span>\n            <span\n              className=\"col-start-1 row-start-1 flex items-baseline whitespace-nowrap tabular-nums\"\n              aria-hidden=\"true\"\n              style={{\n                opacity: left && left > 0 ? 1 : 0,\n                filter: left && left > 0 ? \"none\" : \"blur(3px)\",\n                transition: reduced\n                  ? \"none\"\n                  : `opacity 260ms ${EASE}, filter 260ms ${EASE}`,\n              }}\n            >\n              Resend in 0:\n              <NumberRoll\n                value={left ?? resendAfter}\n                format={{ minimumIntegerDigits: 2 }}\n                direction=\"down\"\n                duration={700}\n              />\n            </span>\n            <span\n              className=\"col-start-1 row-start-1\"\n              inert={!!(left && left > 0)}\n              style={{\n                opacity: left && left > 0 ? 0 : 1,\n                filter: left && left > 0 ? \"blur(3px)\" : \"none\",\n                transition: reduced\n                  ? \"none\"\n                  : `opacity 260ms ${EASE}, filter 260ms ${EASE}`,\n              }}\n            >\n              <StatusButton\n                variant=\"ghost\"\n                size=\"sm\"\n                status={resend}\n                labels={{\n                  idle: \"Resend code\",\n                  pending: \"Sending\",\n                  success: \"Sent\",\n                  error: \"Try again\",\n                }}\n                onClick={doResend}\n                className=\"-ml-2\"\n              />\n            </span>\n          </span>\n        </div>\n      )}\n\n      <p role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {right\n          ? \"Code verified\"\n          : wrong\n            ? \"That code didn't work. Enter it again.\"\n            : phase === \"checking\"\n              ? \"Checking the code\"\n              : \"\"}\n      </p>\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/status-button.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * STATUS BUTTON: a button that tells you what happened\n *\n *   idle     \"Save\", with an optional icon\n *   pending  a spinner opens in; the label morphs to \"Saving\"\n *   success  a check draws itself; \"Saved\"\n *   error    the button gives a small shake; \"Try again\"\n *\n * Every change is one motion: the icon slot opens and closes,\n * icons swap through a blur, letters the labels share stay put\n * and the button's width eases to fit.\n * ───────────────────────────────────────────────────────── */\n\nexport type ActionStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport interface StatusButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n  status?: ActionStatus;\n  /** Labels per state; defaults to Save, Saving, Saved, Try again. */\n  labels?: Partial<Record<ActionStatus, string>>;\n  /** Shown before the label while idle. */\n  icon?: React.ReactNode;\n  variant?: \"primary\" | \"outline\" | \"ghost\";\n  /** \"sm\" is 28px tall, for toolbars and headers. */\n  size?: \"default\" | \"sm\";\n  /** Called this long after success (ms), e.g. to go back to idle. */\n  onReset?: () => void;\n  resetAfter?: number;\n}\n\nconst LABELS: Record<ActionStatus, string> = {\n  idle: \"Save\",\n  pending: \"Saving\",\n  success: \"Saved\",\n  error: \"Try again\",\n};\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS =\n  \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-2 focus-visible:ring-offset-background\";\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\nfunction Check({ drawn, reduced }: { drawn: boolean; reduced: boolean }) {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\">\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} 120ms`\n              : \"none\",\n        }}\n      />\n    </svg>\n  );\n}\n\nfunction Alert() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\">\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\nexport function StatusButton({\n  status = \"idle\",\n  labels,\n  icon,\n  variant = \"primary\",\n  size = \"default\",\n  onReset,\n  resetAfter = 1800,\n  className = \"\",\n  onClick,\n  ...props\n}: StatusButtonProps) {\n  const reduced = useReducedMotion();\n  const ref = React.useRef<HTMLButtonElement>(null);\n  const label = { ...LABELS, ...labels }[status];\n  const showIcon = status !== \"idle\" || Boolean(icon);\n  const busy = status === \"pending\";\n  const sm = size === \"sm\";\n  const iconSize = sm ? 14 : 16;\n\n  // A short shake when it fails: the eye catches it even if you looked away.\n  React.useEffect(() => {\n    if (status !== \"error\" || reduced) return;\n    ref.current?.animate(\n      [\n        { transform: \"none\" },\n        { transform: \"translateX(-4px)\" },\n        { transform: \"translateX(4px)\" },\n        { transform: \"translateX(-2px)\" },\n        { transform: \"none\" },\n      ],\n      { duration: 380, easing: \"ease-out\" },\n    );\n  }, [status, reduced]);\n\n  React.useEffect(() => {\n    if (status !== \"success\" || !onReset) return;\n    const timer = window.setTimeout(onReset, resetAfter);\n    return () => window.clearTimeout(timer);\n  }, [status, onReset, resetAfter]);\n\n  const tone =\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      : variant === \"primary\"\n        ? \"bg-primary text-primary-foreground hover:bg-primary/90\"\n        : variant === \"ghost\"\n          ? `hover:bg-accent hover:text-foreground ${status === \"idle\" ? \"text-muted-foreground\" : \"text-foreground\"}`\n          : \"text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\";\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={`${sm ? \"size-3\" : \"size-3.5\"} rounded-full border-[1.5px] border-current border-t-transparent opacity-80 motion-reduce:animate-none ${status === \"pending\" ? \"animate-spin\" : \"\"}`}\n      />\n    ),\n    success: <Check drawn={status === \"success\"} reduced={reduced} />,\n    error: <Alert />,\n  };\n\n  return (\n    <>\n      <button\n        ref={ref}\n        type=\"button\"\n        aria-busy={busy || undefined}\n        aria-disabled={busy || undefined}\n        onClick={(e) => {\n          if (busy) return e.preventDefault();\n          onClick?.(e);\n        }}\n        className={`cursor-pointer disabled:cursor-default aria-disabled:cursor-default inline-flex items-center justify-center whitespace-nowrap rounded-full font-medium transition-[background-color,color,box-shadow,scale,padding] duration-300 active:scale-[0.97] motion-reduce:active:scale-100 ${\n          sm\n            ? `h-7 text-[12px] ${variant === \"ghost\" ? \"px-2.5\" : \"px-3\"}`\n            : \"h-9 px-4 text-[13px]\"\n        } ${FOCUS} ${tone} ${className}`}\n        {...props}\n      >\n        <span\n          aria-hidden=\"true\"\n          className={`relative flex shrink-0 items-center justify-center ${sm ? \"h-3.5 [&_svg]:size-3.5\" : \"h-4 [&_svg]:size-4\"}`}\n          style={{\n            width: showIcon ? iconSize : 0,\n            marginRight: showIcon ? (sm ? 5 : 6) : 0,\n            transition: reduced\n              ? \"none\"\n              : `width 380ms ${EASE}, margin 380ms ${EASE}`,\n          }}\n        >\n          {(Object.keys(icons) as ActionStatus[]).map((s) => (\n            <span\n              key={s}\n              className=\"absolute inset-0 flex items-center justify-center\"\n              style={{\n                opacity: s === status ? 1 : 0,\n                transform: s === status ? \"none\" : \"scale(0.6)\",\n                filter: s === status ? \"none\" : \"blur(3px)\",\n                transition: reduced\n                  ? \"none\"\n                  : `opacity 260ms ${EASE}, transform 380ms ${EASE}, filter 260ms ${EASE}`,\n              }}\n            >\n              {icons[s]}\n            </span>\n          ))}\n        </span>\n        <TextMorph>{label}</TextMorph>\n      </button>\n      {/* Outside the button, so the announcement isn't read as part of its name. */}\n      <span className=\"sr-only\" role=\"status\">\n        {status === \"idle\" ? \"\" : label}\n      </span>\n    </>\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-blink": {
      "0%, 100%": {
        "opacity": "1"
      },
      "50%": {
        "opacity": "0"
      }
    },
    "@keyframes ui-sheen": {
      "from": {
        "mask-position": "150% 0"
      },
      "to": {
        "mask-position": "-50% 0"
      }
    }
  },
  "meta": {
    "cavemio": {
      "component": "auth-card",
      "exportName": "AuthCard",
      "categories": [
        "app"
      ],
      "isNew": false,
      "usage": "import { AuthCard } from \"@/components/auth-card\";\n\n<AuthCard\n  onEmail={async (email) => (await hasPassword(email) ? \"password\" : \"code\")}\n  onPassword={(email, password) => signIn(email, password)}\n  onCode={(email, code) => verify(email, code)}\n  onSuccess={() => router.push(\"/app\")}\n/>",
      "accessibility": "- It is one form: Enter continues from the email field and signs in from the password field. The address is a real email input (autocomplete=\"email\", or \"username webauthn\" with passkeys) and stays one, read-only, while it's a chip; Change is a button at its end.\n- Each step moves focus to what comes next: the password field, the first code box, or the Open inbox button. Change returns focus to the address and selects it. Every new step's title is announced in a status region.\n- Errors are linked to their field with aria-describedby and the field is marked aria-invalid. The resend countdown is hidden from screen readers; the button says when it can be used.\n- The card never stores the password or code and never calls a service itself.\n- Inputs use 16px type on touch screens so phones don't zoom into them.\n- Reduced motion changes steps in place: no shrinking frame, slides, shakes or drawing; the words still say what happened.",
      "previewNote": "Interactive local fixture. Data and async results are simulated in the preview; the caller supplies application services.",
      "documentation": {
        "props": [
          {
            "name": "onEmail",
            "type": "(email) => Promise<\"password\" | \"code\" | \"link\">",
            "description": "– · Asks your server what this address needs next (and sends the code or link if that's it). Throw to keep the field and show the message."
          },
          {
            "name": "onPassword",
            "type": "(email, password) => Promise<unknown>",
            "description": "– · Signs in with a password. Throw when it's wrong."
          },
          {
            "name": "onCode",
            "type": "(email, code) => Promise<unknown>",
            "description": "– · Checks a one-time code. Resolve when it's right; throw when it isn't."
          },
          {
            "name": "onResend",
            "type": "(email) => Promise<unknown>",
            "description": "– · Sends the code or link again. Without it there is no resend."
          },
          {
            "name": "onForgot",
            "type": "(email) => Promise<unknown>",
            "description": "– · Sends a password reset link; shows \"Forgot password?\" on the password step."
          },
          {
            "name": "providers",
            "type": "{ id, label, icon? }[]",
            "description": "– · Sign-in providers above the email field, two to a row."
          },
          {
            "name": "onProvider",
            "type": "(id) => Promise<unknown>",
            "description": "– · Starts a provider's sign-in. A redirect keeps its button spinning; a popup that resolves moves the card to done."
          },
          {
            "name": "onPasskey",
            "type": "() => Promise<unknown>",
            "description": "– · Shows \"Sign in with a passkey\" and sets the email field's autocomplete to \"username webauthn\" for passkey autofill."
          },
          {
            "name": "onSuccess",
            "type": "() => void",
            "description": "– · Runs after \"Signed in\" has shown, e.g. to redirect."
          },
          {
            "name": "mode",
            "type": "\"sign-in\" | \"sign-up\"",
            "description": "\"sign-in\" · Sets the default words and the password field's autocomplete."
          },
          {
            "name": "copy",
            "type": "Partial<Record<step, { title?, description? }>>",
            "description": "– · Words per step: email, password, code, link, reset and done."
          },
          {
            "name": "logo",
            "type": "ReactNode",
            "description": "– · Above the title."
          },
          {
            "name": "footer",
            "type": "ReactNode",
            "description": "– · Under the email step: a link to sign up, terms. It folds away after the first step."
          },
          {
            "name": "defaultEmail",
            "type": "string",
            "description": "– · Starts the field with an address, e.g. from an invite link."
          },
          {
            "name": "codeLength",
            "type": "number",
            "description": "6 · Digits in a one-time code."
          },
          {
            "name": "resendAfter",
            "type": "number",
            "description": "30 · Seconds before a code or link can be sent again."
          }
        ],
        "useCases": [
          {
            "title": "Sign-in and sign-up pages",
            "description": "One card for passwords, one-time codes and magic links, asked one step at a time."
          },
          {
            "title": "Passwordless login",
            "description": "Email a code or a link as the main way in, with no password field to fill."
          },
          {
            "title": "Social login",
            "description": "Google or GitHub buttons above the email field, two to a row."
          },
          {
            "title": "Invite links",
            "description": "Open with the invited address already in the field."
          }
        ],
        "features": [
          {
            "title": "Your server picks the next step",
            "description": "onEmail answers “password”, “code” or “link” for each address, and the card moves on."
          },
          {
            "title": "The email becomes a chip",
            "description": "The field shrinks round the address, and Change takes you back to edit it."
          },
          {
            "title": "Codes check themselves",
            "description": "The code is sent for checking as the last digit lands. A wrong one shakes and clears, and Resend counts down."
          },
          {
            "title": "It opens the inbox for you",
            "description": "A link step offers “Open Gmail”, and the same for Outlook, iCloud, Yahoo and Proton addresses."
          },
          {
            "title": "Providers and passkeys",
            "description": "Provider buttons sit above the email field, and a passkey button appears when you pass onPasskey."
          },
          {
            "title": "Any auth service fits",
            "description": "The card never calls a service or stores a password. Every step is one async function you connect."
          }
        ],
        "states": [
          {
            "title": "email",
            "description": "Providers (two to a row), \"or\", then the email field and Continue. An address that isn't one shakes the field and says so under it; a passkey button sits under Continue when onPasskey is set."
          },
          {
            "title": "checking",
            "description": "Continue morphs to \"Checking\" with a spinner while onEmail runs. If it throws, the field shakes ±4px, its thin line turns red and the message opens under it."
          },
          {
            "title": "identity",
            "description": "The field's frame eases from full width and 40px to the address's own width and 32px, its corners to a pill, in 520ms; the address stays where it was typed. The providers fold up above it in 460ms and \"Change\" opens at its end 160ms later."
          },
          {
            "title": "next step",
            "description": "The new step slides in 28px from the right out of a 4px blur (440ms) while the old one leaves the other way; the card eases to its new height. Change runs it backwards and selects the address."
          },
          {
            "title": "password",
            "description": "A password field with a show/hide eye that swaps through a blur. A wrong password shakes the field, selects it and says why. \"Forgot password?\" morphs to \"Sending a link\" and moves on to Check your inbox."
          },
          {
            "title": "code",
            "description": "The code boxes (code input): digits rise in, the row sweeps while onCode runs, a wrong code shakes and clears, a right one melts into one pill; then the card moves on. Resend counts down."
          },
          {
            "title": "link",
            "description": "\"Check your inbox\", with \"Open Gmail\" (or Outlook, iCloud Mail, Yahoo Mail, Proton Mail) for addresses it knows, and \"Resend in 0:28\" rolling down to Resend."
          },
          {
            "title": "providers",
            "description": "The pressed provider's mark gives way to a spinner while the others dim. If onProvider throws, the reason opens under the field; if it resolves (a popup), the card moves to done."
          },
          {
            "title": "done",
            "description": "A ring draws itself in 640ms, then a check inside it; \"Signed in\". onSuccess runs 1.3s later, e.g. to redirect."
          }
        ]
      }
    }
  },
  "type": "registry:component"
}