{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cavemio-cookie-banner",
  "title": "Cookie banner",
  "description": "Asks once, plainly, then folds into a small cookie button in the corner that grows back into the preferences.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/components/cookie-banner.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * COOKIE BANNER: ask once, plainly, then get out of the way\n *\n *   ask        a thin line card in the corner: one sentence,\n *              Customise, and Reject all beside Accept all,\n *              equally easy\n *   customise  the same card grows into the preferences: each\n *              kind of cookie with a switch thrown to its side;\n *              what's necessary says it's always on, and why\n *   save       a check draws itself on the button you pressed,\n *              its label morphs to \"Accepted\", and the card\n *              shrinks into a small cookie button in the corner\n *   revisit    that button grows back into the preferences, with\n *              the choices as they were\n *\n * The choice is remembered and handed to you, so you only load\n * what people allowed. Global Privacy Control is respected; new\n * kinds of cookie, or a year passing, ask again.\n * ───────────────────────────────────────────────────────── */\n\nexport interface CookieCategory {\n  id: string;\n  label: string;\n  description: string;\n  /** Always on, e.g. what keeps people signed in. */\n  required?: boolean;\n  /** Ads or cross-site tracking: stays off for browsers that send Global Privacy Control, unless switched on here. */\n  tracking?: boolean;\n}\n\nexport type CookieConsent = Record<string, boolean>;\n\nexport interface CookieBannerProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"onChange\"\n> {\n  categories?: CookieCategory[];\n  /** The one sentence on the banner. */\n  message?: React.ReactNode;\n  /** Link to your cookie policy. */\n  policyHref?: string;\n  /**\n   * Called with the remembered choice on load (\"load\") and with every new one (\"save\"),\n   * so you can start what people allowed. Return a promise to record consent on your\n   * server; the button waits for it.\n   */\n  onConsentChange?: (\n    consent: CookieConsent,\n    reason: \"load\" | \"save\",\n  ) => void | Promise<unknown>;\n  storageKey?: string;\n  /** Days before asking again. */\n  expiresAfter?: number;\n  position?: \"bottom-left\" | \"bottom-right\" | \"bottom-center\";\n  /** \"absolute\" keeps it inside a positioned parent instead of the window. */\n  strategy?: \"fixed\" | \"absolute\";\n  /** Keep the small cookie button after a choice, so people can change their mind. */\n  showReopen?: boolean;\n}\n\ntype Phase = \"hidden\" | \"ask\" | \"prefs\" | \"folded\";\ntype Action = \"accept\" | \"reject\" | \"save\";\ntype Work = { action: Action; stage: \"busy\" | \"done\" };\ntype Saved = { choices: CookieConsent; savedAt: number };\n\nconst OPEN_EVENT = \"cookie-preferences:open\";\n\n/** Opens the preferences from anywhere, e.g. a \"Cookie settings\" link in your footer. */\nexport function openCookiePreferences() {\n  window.dispatchEvent(new Event(OPEN_EVENT));\n}\n\n/** The saved choice, or null if people haven't chosen yet. */\nexport function getCookieConsent(\n  storageKey = \"cookie-consent\",\n): CookieConsent | null {\n  try {\n    return (\n      (JSON.parse(localStorage.getItem(storageKey) ?? \"null\") as Saved | null)\n        ?.choices ?? null\n    );\n  } catch {\n    return null;\n  }\n}\n\nconst DEFAULT_CATEGORIES: CookieCategory[] = [\n  {\n    id: \"necessary\",\n    label: \"Necessary\",\n    description: \"Keeps you signed in and your basket full.\",\n    required: true,\n  },\n  {\n    id: \"analytics\",\n    label: \"Analytics\",\n    description:\n      \"Counts visits and what gets used, so we can make it better. Never sold.\",\n  },\n  {\n    id: \"marketing\",\n    label: \"Marketing\",\n    description:\n      \"Shows you our ads on other sites and tells us if they worked.\",\n    tracking: true,\n  },\n];\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst THROW = \"cubic-bezier(0.34,1.36,0.64,1)\";\nconst DURATION = 480;\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-popover\";\nconst TONES = {\n  solid: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  line: \"text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\",\n  ghost: \"text-muted-foreground hover:bg-accent hover:text-foreground\",\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\nfunction CookieIcon({ className = \"size-4\" }: { className?: string }) {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 20 20\"\n      fill=\"none\"\n      className={className}\n    >\n      <path\n        d=\"M17.5 10.2A7.5 7.5 0 1 1 9.8 2.5a2.6 2.6 0 0 0 3.1 3 2.6 2.6 0 0 0 3.5 3.5 2.4 2.4 0 0 0 1.1 1.2Z\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinejoin=\"round\"\n      />\n      <circle cx=\"7.3\" cy=\"8.6\" r=\"1\" fill=\"currentColor\" />\n      <circle cx=\"12.2\" cy=\"13\" r=\"1\" fill=\"currentColor\" />\n      <circle cx=\"7.8\" cy=\"13.4\" r=\"0.9\" fill=\"currentColor\" />\n    </svg>\n  );\n}\n\n/** A button that confirms itself: a spinner while your server records it, then a drawn check and a new label. */\nfunction ActionButton({\n  label,\n  doneLabel,\n  stage,\n  locked,\n  tone,\n  reduced,\n  onClick,\n  className = \"\",\n}: {\n  label: string;\n  doneLabel: string;\n  stage: \"idle\" | Work[\"stage\"];\n  locked: boolean;\n  tone: keyof typeof TONES;\n  reduced: boolean;\n  onClick: () => void;\n  className?: string;\n}) {\n  const on = stage !== \"idle\";\n  return (\n    <button\n      type=\"button\"\n      onClick={() => !locked && onClick()}\n      aria-disabled={(locked && !on) || undefined}\n      aria-busy={stage === \"busy\" || undefined}\n      className={`cursor-pointer disabled:cursor-default aria-disabled:cursor-default inline-flex h-8 shrink-0 items-center justify-center rounded-full px-3.5 text-[12.5px] font-medium transition-colors ${FOCUS} ${TONES[tone]} ${className}`}\n    >\n      <span\n        aria-hidden=\"true\"\n        className=\"relative flex h-3.5 shrink-0 items-center justify-center\"\n        style={{\n          width: on ? 14 : 0,\n          marginRight: on ? 6 : 0,\n          transition: reduced\n            ? \"none\"\n            : `width 320ms ${EASE}, margin 320ms ${EASE}`,\n        }}\n      >\n        <span\n          className={`absolute size-3 rounded-full border-[1.5px] border-current/30 border-t-current motion-reduce:animate-none ${stage === \"busy\" ? \"animate-spin\" : \"\"}`}\n          style={{\n            opacity: stage === \"busy\" ? 1 : 0,\n            transition: reduced ? \"none\" : \"opacity 200ms\",\n          }}\n        />\n        <svg\n          viewBox=\"0 0 16 16\"\n          fill=\"none\"\n          className=\"absolute size-3.5\"\n          style={{ opacity: stage === \"done\" ? 1 : 0 }}\n        >\n          <path\n            d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n            stroke=\"currentColor\"\n            strokeWidth=\"2\"\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            pathLength={1}\n            strokeDasharray={1}\n            style={{\n              strokeDashoffset: stage === \"done\" ? 0 : 1,\n              transition:\n                stage === \"done\" && !reduced\n                  ? `stroke-dashoffset 380ms ${EASE} 120ms`\n                  : \"none\",\n            }}\n          />\n        </svg>\n      </span>\n      <TextMorph>{stage === \"done\" ? doneLabel : label}</TextMorph>\n    </button>\n  );\n}\n\nfunction Switch({\n  id,\n  checked,\n  describedBy,\n  reduced,\n  onChange,\n}: {\n  id: string;\n  checked: boolean;\n  describedBy: string;\n  reduced: boolean;\n  onChange: (on: boolean) => void;\n}) {\n  return (\n    <button\n      id={id}\n      type=\"button\"\n      role=\"switch\"\n      aria-checked={checked}\n      aria-describedby={describedBy}\n      onClick={() => onChange(!checked)}\n      className={`cursor-pointer relative mt-0.5 h-6 w-10 shrink-0 rounded-full ${FOCUS} ${checked ? \"bg-primary\" : \"bg-muted shadow-[inset_0_0_0_1px_var(--border)]\"}`}\n      style={{\n        transition: reduced ? \"none\" : `background-color 300ms ${EASE}`,\n      }}\n    >\n      <span\n        aria-hidden=\"true\"\n        className=\"absolute left-0.5 top-0.5 size-5 rounded-full bg-background shadow-[0_0_0_1px_var(--border)]\"\n        style={{\n          transform: checked ? \"translateX(16px)\" : \"none\",\n          transition: reduced ? \"none\" : `transform 400ms ${THROW}`,\n        }}\n      />\n    </button>\n  );\n}\n\nconst subscribeNothing = () => () => {};\n\nexport function CookieBanner({\n  categories = DEFAULT_CATEGORIES,\n  message = \"We use cookies to keep the site working and, if you agree, to see how it’s used.\",\n  policyHref,\n  onConsentChange,\n  storageKey = \"cookie-consent\",\n  expiresAfter = 365,\n  position = \"bottom-left\",\n  strategy = \"fixed\",\n  showReopen = true,\n  className = \"\",\n  ...props\n}: CookieBannerProps) {\n  const reduced = useReducedMotion();\n  const id = React.useId();\n  const required = React.useCallback(\n    () =>\n      Object.fromEntries(categories.map((c) => [c.id, Boolean(c.required)])),\n    [categories],\n  );\n  const [phase, setPhase] = React.useState<Phase>(\"hidden\");\n  const [work, setWork] = React.useState<Work | null>(null);\n  const [choice, setChoice] = React.useState<CookieConsent>(required);\n  const gpc = React.useSyncExternalStore(\n    subscribeNothing,\n    () =>\n      Boolean(\n        (navigator as Navigator & { globalPrivacyControl?: boolean })\n          .globalPrivacyControl,\n      ),\n    () => false,\n  );\n  const [size, setSize] = React.useState({\n    ask: { w: 0, h: 0 },\n    prefs: { w: 0, h: 0 },\n  });\n  const [room, setRoom] = React.useState(432);\n  const regionRef = React.useRef<HTMLDivElement>(null);\n  const cardRef = React.useRef<HTMLDivElement>(null);\n  const askRef = React.useRef<HTMLDivElement>(null);\n  const prefsRef = React.useRef<HTMLDivElement>(null);\n  const customiseRef = React.useRef<HTMLButtonElement>(null);\n  const cornerRef = React.useRef<HTMLButtonElement>(null);\n  const live = React.useRef({ phase, locked: false });\n  const back = React.useRef<Phase>(\"ask\");\n  const saved = React.useRef<CookieConsent | null>(null);\n  const focusTo = React.useRef<\"prefs\" | \"ask\" | \"corner\" | null>(null);\n  const timers = React.useRef<number[]>([]);\n  const change = React.useRef(onConsentChange);\n\n  React.useEffect(() => {\n    live.current.phase = phase;\n    change.current = onConsentChange;\n  });\n\n  const later = (fn: () => void, ms: number) => {\n    timers.current.push(window.setTimeout(fn, ms));\n  };\n  React.useEffect(() => () => timers.current.forEach(window.clearTimeout), []);\n\n  // On load: a remembered, current choice goes straight to the corner button; otherwise ask.\n  React.useEffect(() => {\n    const frame = requestAnimationFrame(() => {\n      try {\n        const stored = JSON.parse(\n          localStorage.getItem(storageKey) ?? \"null\",\n        ) as Saved | null;\n        if (stored?.choices) {\n          setChoice({ ...required(), ...stored.choices });\n          const fresh = Date.now() - stored.savedAt < expiresAfter * 864e5;\n          const complete = categories.every(\n            (c) => c.required || c.id in stored.choices,\n          );\n          if (fresh && complete) {\n            saved.current = stored.choices;\n            change.current?.(stored.choices, \"load\");\n            setPhase(\"folded\");\n            return;\n          }\n        }\n      } catch {}\n      setPhase(\"ask\");\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [storageKey, categories, expiresAfter, required]);\n\n  const visible = phase !== \"hidden\" && (phase !== \"folded\" || showReopen);\n\n  // How much room there is: the window, or the parent when it's positioned inside one.\n  React.useLayoutEffect(() => {\n    if (!visible) return;\n    const parent =\n      strategy === \"absolute\" ? regionRef.current?.offsetParent : null;\n    const fit = () =>\n      setRoom(\n        parent instanceof HTMLElement\n          ? parent.clientWidth\n          : document.documentElement.clientWidth,\n      );\n    fit();\n    window.addEventListener(\"resize\", fit);\n    const observer =\n      parent instanceof HTMLElement ? new ResizeObserver(fit) : null;\n    if (parent instanceof HTMLElement) observer?.observe(parent);\n    return () => {\n      window.removeEventListener(\"resize\", fit);\n      observer?.disconnect();\n    };\n  }, [visible, strategy]);\n\n  // The card's two open shapes, measured, so it can grow from one to the other.\n  React.useLayoutEffect(() => {\n    if (!visible) return;\n    const measure = () => {\n      const a = askRef.current;\n      const p = prefsRef.current;\n      setSize((s) => {\n        const next = {\n          ask: { w: a?.offsetWidth ?? 0, h: a?.offsetHeight ?? 0 },\n          prefs: { w: p?.offsetWidth ?? 0, h: p?.offsetHeight ?? 0 },\n        };\n        return s.ask.w === next.ask.w &&\n          s.ask.h === next.ask.h &&\n          s.prefs.w === next.prefs.w &&\n          s.prefs.h === next.prefs.h\n          ? s\n          : next;\n      });\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    if (askRef.current) observer.observe(askRef.current);\n    if (prefsRef.current) observer.observe(prefsRef.current);\n    return () => observer.disconnect();\n  }, [visible]);\n\n  // Arrives by rising out of the corner, a beat after the page.\n  React.useLayoutEffect(() => {\n    if (!visible || reduced) return;\n    cardRef.current?.animate(\n      [\n        { transform: \"translateY(20px) scale(0.97)\", opacity: 0 },\n        { transform: \"none\", opacity: 1 },\n      ],\n      {\n        duration: 640,\n        delay: phase === \"ask\" ? 400 : 0,\n        easing: EASE,\n        fill: \"backwards\",\n      },\n    );\n  }, [visible]);\n\n  // Focus follows the surface, so keyboard people never land on something that just faded.\n  React.useEffect(() => {\n    const target = focusTo.current;\n    if (!target) return;\n    focusTo.current = null;\n    if (target === \"prefs\")\n      prefsRef.current\n        ?.querySelector<HTMLElement>('[role=\"switch\"]')\n        ?.focus({ preventScroll: true });\n    if (target === \"ask\") customiseRef.current?.focus({ preventScroll: true });\n    if (target === \"corner\") cornerRef.current?.focus({ preventScroll: true });\n  }, [phase]);\n\n  const openPrefs = () => {\n    const p = live.current.phase;\n    if (live.current.locked || p === \"hidden\" || p === \"prefs\") return;\n    back.current = p;\n    focusTo.current = \"prefs\";\n    setPhase(\"prefs\");\n  };\n\n  React.useEffect(() => {\n    window.addEventListener(OPEN_EVENT, openPrefs);\n    return () => window.removeEventListener(OPEN_EVENT, openPrefs);\n  }, []);\n\n  const close = () => {\n    if (live.current.locked) return;\n    const to = back.current === \"folded\" ? \"folded\" : \"ask\";\n    if (to === \"folded\" && saved.current)\n      setChoice({ ...required(), ...saved.current });\n    focusTo.current = to === \"folded\" ? \"corner\" : \"ask\";\n    setPhase(to);\n  };\n\n  const commit = async (action: Action, consent: CookieConsent) => {\n    if (live.current.locked) return;\n    live.current.locked = true;\n    const final = Object.fromEntries(\n      categories.map((c) => [c.id, Boolean(c.required || consent[c.id])]),\n    );\n    setChoice(final);\n    saved.current = final;\n    try {\n      localStorage.setItem(\n        storageKey,\n        JSON.stringify({ choices: final, savedAt: Date.now() } satisfies Saved),\n      );\n    } catch {}\n    const pending = change.current?.(final, \"save\");\n    if (pending && typeof pending.then === \"function\") {\n      setWork({ action, stage: \"busy\" });\n      await pending.then(undefined, () => {});\n    }\n    setWork({ action, stage: \"done\" });\n    later(() => {\n      if (cardRef.current?.contains(document.activeElement))\n        focusTo.current = \"corner\";\n      setPhase(\"folded\");\n      later(() => {\n        setWork(null);\n        live.current.locked = false;\n      }, 500);\n    }, 950);\n  };\n\n  const all = (on: boolean) =>\n    Object.fromEntries(\n      categories.map((c) => [\n        c.id,\n        Boolean(c.required || (on && !(gpc && c.tracking))),\n      ]),\n    );\n  const stageOf = (action: Action) =>\n    work?.action === action ? work.stage : \"idle\";\n  const locked = work !== null;\n  const prefs = phase === \"prefs\";\n  const folded = phase === \"folded\";\n  const shape = folded ? { w: 44, h: 44 } : prefs ? size.prefs : size.ask;\n  const place =\n    position === \"bottom-right\"\n      ? \"right-4\"\n      : position === \"bottom-center\"\n        ? \"left-1/2 -translate-x-1/2\"\n        : \"left-4\";\n  const fadeIn = (delay: number) =>\n    reduced\n      ? \"none\"\n      : `opacity 320ms ${EASE} ${delay}ms, filter 320ms ${EASE} ${delay}ms`;\n  const fadeOut = reduced\n    ? \"none\"\n    : \"opacity 120ms ease-out, filter 120ms ease-out\";\n\n  if (!visible) return null;\n\n  return (\n    <div\n      ref={regionRef}\n      role=\"region\"\n      aria-label=\"Cookie consent\"\n      className={`${strategy} bottom-4 z-[80] ${place} ${className}`}\n      onKeyDown={(e) => {\n        if (e.key === \"Escape\" && prefs) close();\n      }}\n      {...props}\n    >\n      {/* One surface: the banner, the preferences and the corner button are three sizes of it. */}\n      <div\n        ref={cardRef}\n        className=\"relative overflow-hidden bg-popover text-popover-foreground\"\n        style={{\n          width: shape.w || undefined,\n          height: shape.h || undefined,\n          borderRadius: folded ? 22 : 20,\n          boxShadow: \"inset 0 0 0 1px var(--border)\",\n          transition: reduced\n            ? \"none\"\n            : `width ${DURATION}ms ${EASE}, height ${DURATION}ms ${EASE}, border-radius ${DURATION}ms ${EASE}`,\n        }}\n      >\n        {/* The ask. */}\n        <div\n          ref={askRef}\n          inert={phase !== \"ask\"}\n          aria-hidden={phase !== \"ask\" || undefined}\n          className=\"absolute bottom-0 left-0 p-4\"\n          style={{\n            width: Math.min(400, room - 32),\n            opacity: phase === \"ask\" ? 1 : 0,\n            filter: phase === \"ask\" ? \"none\" : \"blur(4px)\",\n            transition: phase === \"ask\" ? fadeIn(160) : fadeOut,\n          }}\n        >\n          <div className=\"flex gap-3\">\n            <span className=\"mt-[3px] text-muted-foreground\">\n              <CookieIcon />\n            </span>\n            <p className=\"text-[13px] leading-relaxed text-foreground\">\n              {message}\n              {policyHref && (\n                <>\n                  {\" \"}\n                  <a\n                    href={policyHref}\n                    className={`rounded-sm text-muted-foreground underline decoration-border underline-offset-4 transition-colors hover:text-foreground hover:decoration-current ${FOCUS}`}\n                  >\n                    Cookie policy\n                  </a>\n                </>\n              )}\n            </p>\n          </div>\n          {/* Reject all and Accept all share the width equally; in a narrow card they take their own row. */}\n          <div className=\"mt-4 flex flex-wrap-reverse items-center gap-2\">\n            <button\n              ref={customiseRef}\n              type=\"button\"\n              onClick={openPrefs}\n              aria-disabled={locked || undefined}\n              className={`cursor-pointer disabled:cursor-default aria-disabled:cursor-default -ml-1.5 h-8 shrink-0 rounded-full px-2.5 text-[12.5px] font-medium ${FOCUS} ${TONES.ghost}`}\n            >\n              Customise\n            </button>\n            <div className=\"ml-auto flex min-w-[200px] max-w-[248px] flex-1 gap-2\">\n              <ActionButton\n                label=\"Reject all\"\n                doneLabel=\"Rejected\"\n                stage={stageOf(\"reject\")}\n                locked={locked}\n                tone=\"line\"\n                reduced={reduced}\n                onClick={() => commit(\"reject\", all(false))}\n                className=\"flex-1\"\n              />\n              <ActionButton\n                label=\"Accept all\"\n                doneLabel=\"Accepted\"\n                stage={stageOf(\"accept\")}\n                locked={locked}\n                tone=\"solid\"\n                reduced={reduced}\n                onClick={() => commit(\"accept\", all(true))}\n                className=\"flex-1\"\n              />\n            </div>\n          </div>\n        </div>\n\n        {/* The preferences. */}\n        <div\n          ref={prefsRef}\n          role=\"group\"\n          aria-labelledby={`${id}-title`}\n          inert={!prefs}\n          aria-hidden={!prefs || undefined}\n          className=\"absolute bottom-0 left-0 p-4\"\n          style={{\n            width: Math.min(420, room - 32),\n            opacity: prefs ? 1 : 0,\n            filter: prefs ? \"none\" : \"blur(4px)\",\n            transition: prefs ? fadeIn(180) : fadeOut,\n          }}\n        >\n          <div className=\"flex items-start justify-between gap-3\">\n            <div>\n              <p\n                id={`${id}-title`}\n                className=\"text-[14px] font-medium text-foreground\"\n              >\n                Choose your cookies\n              </p>\n              {gpc && (\n                <p className=\"mt-1 text-[12px] leading-relaxed text-muted-foreground\">\n                  Your browser asks sites not to track you, so tracking stays\n                  off unless you switch it on.\n                </p>\n              )}\n            </div>\n            <button\n              type=\"button\"\n              aria-label=\"Close\"\n              onClick={close}\n              className={`cursor-pointer -mr-1.5 -mt-1 grid size-7 shrink-0 place-items-center rounded-full ${FOCUS} ${TONES.ghost}`}\n            >\n              <svg\n                aria-hidden=\"true\"\n                viewBox=\"0 0 16 16\"\n                fill=\"none\"\n                className=\"size-3.5\"\n              >\n                <path\n                  d=\"m4 4 8 8M12 4l-8 8\"\n                  stroke=\"currentColor\"\n                  strokeWidth=\"1.5\"\n                  strokeLinecap=\"round\"\n                />\n              </svg>\n            </button>\n          </div>\n          <ul className=\"mt-3 max-h-[min(55vh,360px)] divide-y divide-border overflow-y-auto overscroll-contain border-y border-border\">\n            {categories.map((c) => (\n              <li key={c.id} className=\"flex items-start gap-4 py-3 pr-1\">\n                <div className=\"min-w-0 flex-1\">\n                  {c.required ? (\n                    <p className=\"text-[13px] font-medium text-foreground\">\n                      {c.label}\n                    </p>\n                  ) : (\n                    <label\n                      htmlFor={`${id}-${c.id}`}\n                      className=\"cursor-pointer text-[13px] font-medium text-foreground\"\n                    >\n                      {c.label}\n                    </label>\n                  )}\n                  <p\n                    id={`${id}-${c.id}-about`}\n                    className=\"mt-0.5 text-[12px] leading-relaxed text-muted-foreground\"\n                  >\n                    {c.description}\n                  </p>\n                </div>\n                {c.required ? (\n                  <span className=\"mt-0.5 shrink-0 text-[12px] font-medium text-muted-foreground\">\n                    Always on\n                  </span>\n                ) : (\n                  <Switch\n                    id={`${id}-${c.id}`}\n                    checked={Boolean(choice[c.id])}\n                    describedBy={`${id}-${c.id}-about`}\n                    reduced={reduced}\n                    onChange={(on) =>\n                      !locked && setChoice((x) => ({ ...x, [c.id]: on }))\n                    }\n                  />\n                )}\n              </li>\n            ))}\n          </ul>\n          <div className=\"mt-3 flex items-center justify-end gap-2\">\n            <ActionButton\n              label=\"Reject all\"\n              doneLabel=\"Rejected\"\n              stage={stageOf(\"reject\")}\n              locked={locked}\n              tone=\"line\"\n              reduced={reduced}\n              onClick={() => commit(\"reject\", all(false))}\n            />\n            <ActionButton\n              label=\"Save choices\"\n              doneLabel=\"Saved\"\n              stage={stageOf(\"save\")}\n              locked={locked}\n              tone=\"solid\"\n              reduced={reduced}\n              onClick={() => commit(\"save\", choice)}\n            />\n          </div>\n        </div>\n\n        {/* The corner button it shrinks into; it grows back into the preferences. */}\n        <button\n          ref={cornerRef}\n          type=\"button\"\n          inert={!folded}\n          aria-hidden={!folded || undefined}\n          aria-label=\"Cookie preferences\"\n          onClick={openPrefs}\n          className=\"cursor-pointer group absolute inset-0 flex items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50\"\n          style={{\n            opacity: folded ? 1 : 0,\n            transform: folded ? \"none\" : \"scale(0.5) rotate(-40deg)\",\n            transition: reduced\n              ? \"none\"\n              : folded\n                ? `opacity 260ms ${EASE} 280ms, transform 520ms ${THROW} 240ms`\n                : \"opacity 100ms ease-out, transform 200ms ease-out\",\n          }}\n        >\n          <span className=\"transition-transform duration-300 group-hover:-rotate-[18deg] motion-reduce:transition-none\">\n            <CookieIcon className=\"size-5\" />\n          </span>\n        </button>\n      </div>\n      <span role=\"status\" className=\"sr-only\">\n        {work?.stage === \"done\" ? \"Cookie choices saved\" : \"\"}\n      </span>\n    </div>\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": {},
  "meta": {
    "cavemio": {
      "component": "cookie-banner",
      "exportName": "CookieBanner",
      "categories": [
        "overlays"
      ],
      "isNew": false,
      "usage": "import { CookieBanner } from \"@/components/cookie-banner\";\n\n<CookieBanner\n  policyHref=\"/cookies\"\n  onConsentChange={(consent) => {\n    if (consent.analytics) loadAnalytics();\n    if (consent.marketing) loadAdPixels();\n  }}\n/>",
      "accessibility": "- Nothing optional is on until people say so, and Reject all is as easy and as visible as Accept all, as European regulators expect.\n- Browsers that send Global Privacy Control get tracking categories off even on Accept all, with a line saying why.\n- A labelled region, not a modal: the page stays usable. Switches are real switches with their descriptions attached; Esc closes the preferences.\n- Focus moves with the surface: into the preferences when they open, to the cookie button when it folds.\n- The choice is announced when it’s saved. Installs Text morph. With reduced motion the card changes size at once and nothing slides.",
      "previewNote": "Interactive local fixture. Data and async results are simulated in the preview; the caller supplies application services.",
      "documentation": {
        "props": [
          {
            "name": "categories",
            "type": "CookieCategory[]",
            "description": "Necessary, Analytics, Marketing · Each kind of cookie: id, label, description, and required (always on) or tracking (kept off by Global Privacy Control)."
          },
          {
            "name": "onConsentChange",
            "type": "(consent, reason) => void | Promise",
            "description": "– · Called with the remembered choice on load and with each new one; return a promise and the button waits for it."
          },
          {
            "name": "message",
            "type": "ReactNode",
            "description": "– · The one sentence on the banner."
          },
          {
            "name": "policyHref",
            "type": "string",
            "description": "– · Adds a \"Cookie policy\" link after the sentence."
          },
          {
            "name": "position",
            "type": "\"bottom-left\" | \"bottom-right\" | \"bottom-center\"",
            "description": "\"bottom-left\" · Which corner it sits in and folds into."
          },
          {
            "name": "showReopen",
            "type": "boolean",
            "description": "true · Keep the cookie button after a choice. Without it, use openCookiePreferences() from a link."
          },
          {
            "name": "expiresAfter",
            "type": "number",
            "description": "365 · Days before asking again. Adding a new kind of cookie asks again too."
          },
          {
            "name": "storageKey",
            "type": "string",
            "description": "\"cookie-consent\" · Where the choice is kept in localStorage. getCookieConsent(storageKey) reads it anywhere."
          },
          {
            "name": "strategy",
            "type": "\"fixed\" | \"absolute\"",
            "description": "\"fixed\" · Absolute keeps it inside a positioned parent, as in this preview."
          }
        ],
        "useCases": [
          {
            "title": "Marketing sites",
            "description": "Ask for consent before analytics or ad scripts run."
          },
          {
            "title": "SaaS products",
            "description": "Record a visitor’s choices and keep them with your account system."
          },
          {
            "title": "Sites with EU and UK visitors",
            "description": "A banner where rejecting is as easy as accepting."
          },
          {
            "title": "Footer “Cookie settings” links",
            "description": "Let people change their mind later from any link on the page."
          }
        ],
        "features": [
          {
            "title": "Reject is as easy as Accept",
            "description": "Both buttons are the same size and side by side, and nothing optional is on until people say so."
          },
          {
            "title": "Preferences in the same card",
            "description": "Customise grows the card into a switch for each kind of cookie. Use the defaults or your own categories."
          },
          {
            "title": "The choice confirms itself",
            "description": "While your server records it, the button shows a spinner, then a drawn check and “Accepted”, “Rejected” or “Saved”."
          },
          {
            "title": "It folds into a cookie button",
            "description": "The card shrinks to a small cookie in the corner, or reopens from a footer link with openCookiePreferences()."
          },
          {
            "title": "It respects Global Privacy Control",
            "description": "Browsers that send the signal get tracking categories off, even on Accept all, with a line saying why."
          },
          {
            "title": "It remembers, and asks again when needed",
            "description": "The choice is kept for 365 days, and asks again when you add a new kind of cookie."
          }
        ],
        "states": [
          {
            "title": "ask",
            "description": "The card rises 20px out of the corner 400ms after the page (640ms). Reject all and Accept all are the same size, side by side."
          },
          {
            "title": "customise",
            "description": "The card’s width and height grow to the preferences (480ms) while the banner blurs out and the preferences blur in. Switch thumbs are thrown with a slight overshoot (400ms). Esc or the close button returns."
          },
          {
            "title": "saving",
            "description": "When onConsentChange returns a promise, the pressed button opens a spinner beside its label until it settles."
          },
          {
            "title": "saved",
            "description": "A check draws itself on the button and the label morphs (\"Accepted\", \"Rejected\", \"Saved\"); after a beat the card shrinks to a 44px circle and the cookie spins in with a small overshoot."
          },
          {
            "title": "revisit",
            "description": "The cookie button, or openCookiePreferences() from a footer link, grows the card back into the preferences. Closing without saving puts the saved choices back."
          }
        ]
      }
    }
  },
  "type": "registry:component"
}