{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cookie-consent-parts",
  "title": "Cookie consent parts",
  "description": "What the Cookie consent blocks share: when the banner shows, the switches a visitor sets before saving, the three ways to answer, where focus goes, what a screen reader hears, and a category’s row.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/consent.json",
    "https://kinoui.com/r/field.json",
    "https://kinoui.com/r/panel.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/switch.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/cookie-consent-parts.tsx",
      "content": "'use client'\n\nimport { Field, FieldDescription, FieldLabel } from '@/registry/components/kino/field'\nimport { Switch } from '@/registry/components/kino/switch'\nimport { announce } from '@/registry/lib/announce'\nimport {\n  type Consent,\n  type ConsentCategory,\n  isGranted,\n  useConsent,\n} from '@/registry/lib/consent'\nimport { panelDescriptionClassName } from '@/registry/lib/panel'\nimport { revealBehavior } from '@/registry/lib/scroll'\nimport {\n  type ReactNode,\n  type RefObject,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * What every arrangement of the Cookie consent banner shares: when it shows,\n * the switches a visitor sets before saving, the three ways to answer, where\n * focus goes, what a screen reader hears, and a category's row.\n */\n\ninterface CookieConsentText {\n  /** The banner's heading. */\n  title?: ReactNode\n  /** What the cookies are for, in a sentence or two. */\n  description?: ReactNode\n  /** The cookie policy, linked after the description. */\n  policyHref?: string\n}\n\nconst defaultText = {\n  title: 'Cookies',\n  description:\n    'We use them to keep the site working and, with your OK, to learn how it’s used and to show ads that fit.',\n} satisfies CookieConsentText\n\n/**\n * The banner's state: shown while the consent asks, the switches as they\n * stand, whether its settings are open, and its answers.\n */\nfunction useCookieConsent<Id extends string>(\n  consent: Consent<Id>,\n  surfaceRef: RefObject<HTMLElement | null>,\n) {\n  const { state, save } = useConsent(consent)\n  // Where focus was when a link opened the banner, to go back to once it's answered.\n  const returnTo = useRef<HTMLElement | null>(null)\n\n  const ready = state.status !== 'unknown'\n  const shown = state.status === 'asking'\n  const opened = state.status === 'asking' && state.opened\n  const gpc = consent.gpc()\n  // The switches start from what applies, and nothing is on until it's turned on.\n  const [granted, setGranted] = useState<readonly Id[]>([])\n  const [customising, setCustomising] = useState(false)\n  const [asked, setAsked] = useState(state)\n  if (state !== asked) {\n    setAsked(state)\n    // The switches start again only when the banner comes back; one that\n    // leaves keeps what it showed until it has gone.\n    if (state.status === 'asking' && asked.status !== 'asking') {\n      setGranted(state.choice?.granted ?? [])\n      setCustomising(state.opened)\n    } else if (opened) setCustomising(true)\n  }\n\n  // Opened from a link, the banner takes focus, so a keyboard is where the choices are.\n  useLayoutEffect(() => {\n    if (!opened) return\n    const active = document.activeElement\n    const surface = surfaceRef.current\n    if (!surface || surface.contains(active)) return\n    returnTo.current = active instanceof HTMLElement ? active : null\n    surface.focus({ preventScroll: true })\n    // A banner in the page's flow may be out of view, as the Top bar is from the footer.\n    surface.scrollIntoView({\n      block: 'nearest',\n      behavior: revealBehavior(surface),\n    })\n  }, [opened, surfaceRef])\n\n  // Customise takes focus to the first switch, so the settings are next by\n  // keyboard and a screen reader lands in them. Folding them back, or a\n  // button that went away with them, as the Island's pill does, leaves focus\n  // on the banner itself.\n  const focusSwitch = useRef(false)\n  useLayoutEffect(() => {\n    const surface = surfaceRef.current\n    if (!surface) return\n    const first = focusSwitch.current\n      ? surface.querySelector<HTMLElement>('[role=\"switch\"]:not([data-disabled])')\n      : null\n    focusSwitch.current = false\n    if (first) return first.focus()\n    const active = document.activeElement\n    if (active === document.body || active?.closest('[inert]'))\n      surface.focus({ preventScroll: true })\n  }, [customising, surfaceRef])\n\n  // Escape folds the settings back; it never counts as an answer.\n  useEffect(() => {\n    const surface = surfaceRef.current\n    if (!surface || !customising) return\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.key !== 'Escape') return\n      event.stopPropagation()\n      setCustomising(false)\n      surface.focus({ preventScroll: true })\n    }\n    surface.addEventListener('keydown', onKeyDown)\n    return () => surface.removeEventListener('keydown', onKeyDown)\n  }, [customising, surfaceRef])\n\n  const answer = (next: readonly Id[], said: string) => {\n    const surface = surfaceRef.current\n    // Never left on a button that is going away (cookieconsent #530).\n    if (surface?.contains(document.activeElement)) {\n      const back = returnTo.current\n      if (back?.isConnected) back.focus({ preventScroll: true })\n      else if (document.activeElement instanceof HTMLElement)\n        document.activeElement.blur()\n    }\n    returnTo.current = null\n    save(next)\n    announce(said)\n  }\n\n  return {\n    ready,\n    shown,\n    customising,\n    categories: consent.categories,\n    isOn: (category: ConsentCategory<Id>) => isGranted(category, { granted }, gpc),\n    /** Kept off by the browser's Global Privacy Control. */\n    locked: (category: ConsentCategory<Id>) => Boolean(category.gpc && gpc),\n    toggle: (id: Id, on: boolean) =>\n      setGranted((last) =>\n        on\n          ? [...last.filter((each) => each !== id), id]\n          : last.filter((each) => each !== id),\n      ),\n    /**\n     * Customise, then Save choices on the same button: the second click of a\n     * double-click on Customise never saves the switches it just showed.\n     */\n    customiseOrSave: (event: { detail: number }) => {\n      if (customising) {\n        if (event.detail <= 1) answer(granted, 'Cookie choices saved.')\n        return\n      }\n      focusSwitch.current = true\n      setCustomising(true)\n      announce('Cookie settings shown.')\n    },\n    // The store leaves out what GPC keeps off, and the visitor hears that it did.\n    acceptAll: () => {\n      const kept = consent.categories.filter((category) => category.gpc && gpc)\n      answer(\n        consent.categories.map((category) => category.id),\n        kept.length\n          ? `Cookies accepted, except ${kept.map((category) => category.label).join(', ')}: your browser asks sites not to share your data.`\n          : 'All cookies accepted.',\n      )\n    },\n    rejectAll: () => answer([], 'Only necessary cookies kept.'),\n  }\n}\n\ntype CookieConsentModel<Id extends string> = ReturnType<typeof useCookieConsent<Id>>\n\n/**\n * Where the banner comes from and goes to: it rises into place\n * `--cookie-consent-rise` far, and once gone it is hidden and inert, so\n * nothing in it keeps focus.\n */\nconst cookieConsentStatesClassName =\n  'starting:opacity-0 motion-safe:starting:translate-y-(--cookie-consent-rise,0.75rem) data-closed:invisible data-closed:opacity-0 motion-safe:data-closed:translate-y-(--cookie-consent-rise,0.75rem)'\n\n/**\n * The banner arriving on `enter` and leaving on `exit`, between its states.\n * It is visible from the start of its entrance, so focus can move into it\n * at once, and hidden only once its exit has played.\n */\nconst cookieConsentPresenceClassName = cn(\n  cookieConsentStatesClassName,\n  '[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),translate_var(--motion-enter-duration)_var(--motion-enter-easing),visibility_0s] data-closed:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),translate_var(--motion-exit-duration)_var(--motion-exit-easing),visibility_0s_var(--motion-exit-duration)] motion-reduce:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),visibility_0s] motion-reduce:data-closed:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),visibility_0s_var(--motion-exit-duration)]',\n)\n\n/** The banner takes focus when reopened: its ring, as a focusable region's. */\nconst cookieConsentFocusClassName =\n  'focus-visible:ring-ring/50 focus-visible:ring-3 focus-visible:outline-hidden'\n\n/** What the cookies are for, then the link to the cookie policy. */\nfunction CookieConsentDescription({\n  description,\n  policyHref,\n  className,\n}: {\n  description: ReactNode\n  policyHref?: string\n  className?: string\n}) {\n  return (\n    <p className={cn(panelDescriptionClassName, className)}>\n      {description}\n      {policyHref ? (\n        <>\n          {' '}\n          <a href={policyHref}>Cookie policy</a>\n        </>\n      ) : null}\n    </p>\n  )\n}\n\n/** One category: its name and what it's for, the tools it covers, and its switch. */\nfunction CookieConsentCategory<Id extends string>({\n  category,\n  model,\n  className,\n}: {\n  category: ConsentCategory<Id>\n  model: CookieConsentModel<Id>\n  className?: string\n}) {\n  const locked = model.locked(category)\n  return (\n    <Field\n      disabled={locked}\n      className={cn(\n        \"grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 [grid-template-areas:'label_control'_'message_control']\",\n        className,\n      )}\n    >\n      <FieldLabel className='self-end pb-0.5'>{category.label}</FieldLabel>\n      <FieldDescription className='self-start pt-0.5'>\n        {category.description}\n        {category.services?.length ? (\n          <span className='text-foreground/70 block'>{category.services.join(', ')}</span>\n        ) : null}\n        {locked ? (\n          <span className='block'>\n            Off: your browser asks sites not to share your data.\n          </span>\n        ) : null}\n      </FieldDescription>\n      {category.required ? (\n        <span className='text-muted-foreground text-xs font-medium [grid-area:control]'>\n          Always on\n        </span>\n      ) : (\n        <Switch\n          checked={model.isOn(category)}\n          onCheckedChange={(on) => model.toggle(category.id, on)}\n          className='[grid-area:control]'\n        />\n      )}\n    </Field>\n  )\n}\n\nexport {\n  CookieConsentCategory,\n  CookieConsentDescription,\n  cookieConsentFocusClassName,\n  cookieConsentPresenceClassName,\n  cookieConsentStatesClassName,\n  defaultText,\n  useCookieConsent,\n}\n\nexport type { CookieConsentModel, CookieConsentText }\n",
      "type": "registry:lib",
      "target": "@lib/cookie-consent-parts.tsx"
    }
  ],
  "type": "registry:lib"
}