{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "consent",
  "title": "Consent",
  "description": "A visitor’s cookie consent: the categories they turn on, saved in the browser and asked again when it expires or the categories change, with a hook, a gate that holds a script back until its category is on, and Google Consent Mode set before the tags load.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/dates.json"
  ],
  "files": [
    {
      "path": "registry/lib/consent.tsx",
      "content": "'use client'\n\nimport { addDays, daysAgoInline, today } from '@/registry/lib/dates'\nimport { type ReactNode, useDeferredValue, useSyncExternalStore } from 'react'\n\n/*\n * What a visitor agreed to, by category, such as analytics or marketing:\n * kept in the browser for a few months, asked again when it runs out or when\n * the categories change, and read with `useConsent` to hold scripts back\n * until their category is on. The Cookie consent block asks for it; a link\n * anywhere reopens it with `consent.open`. Saved in localStorage, which\n * Safari keeps while the site is visited, where a cookie a script writes\n * lasts seven days.\n */\n\n/** A Google Consent Mode type, which Google's tags read before they set cookies. */\ntype GoogleConsentType =\n  | 'ad_storage'\n  | 'ad_user_data'\n  | 'ad_personalization'\n  | 'analytics_storage'\n  | 'functionality_storage'\n  | 'personalization_storage'\n  | 'security_storage'\n\ninterface ConsentCategory<Id extends string = string> {\n  id: Id\n  label: string\n  /** What it's for, in a sentence a visitor reads before turning it on. */\n  description: string\n  /** Always on, such as what keeps someone signed in: shown on and locked. */\n  required?: boolean\n  /** The tools it covers, named under it, such as `PostHog`. */\n  services?: readonly string[]\n  /** The Google Consent Mode types it grants. */\n  google?: readonly GoogleConsentType[]\n  /** Kept off while the browser sends Global Privacy Control, which asks sites not to sell or share data. */\n  gpc?: boolean\n}\n\ninterface ConsentChoice<Id extends string = string> {\n  /** The categories turned on, other than the required ones, which always are. */\n  granted: readonly Id[]\n  /** The day it was given, as `yyyy-mm-dd`: it holds for `expiresAfterDays` from then. */\n  date: string\n  /** The `revision` it was given under: a newer one asks again. */\n  revision: number\n}\n\ntype ConsentState<Id extends string = string> =\n  /** On the server and before hydration: nothing is granted and nothing shows. */\n  | { status: 'unknown' }\n  /**\n   * The banner shows: nothing valid is saved, or `open` was called, which\n   * asks for its settings. `choice` is what still applies meanwhile.\n   */\n  | { status: 'asking'; choice: ConsentChoice<Id> | null; opened: boolean }\n  | { status: 'given'; choice: ConsentChoice<Id> }\n\ninterface ConsentOptions<Id extends string> {\n  categories: readonly ConsentCategory<Id>[]\n  /** Raise it when the categories or what they cover change, to ask everyone again. */\n  revision?: number\n  /** How long a choice is kept before the banner asks again. Six months, as France's CNIL advises. */\n  expiresAfterDays?: number\n  /** The localStorage key it's saved under; `null` keeps the choice for this visit only, as a preview does. */\n  storageKey?: string | null\n}\n\ninterface Consent<Id extends string = string> {\n  readonly categories: readonly ConsentCategory<Id>[]\n  /** What the script before the first paint reads. */\n  readonly config: ConsentConfig\n  get: () => ConsentState<Id>\n  /** Whether the browser sends Global Privacy Control, which keeps the `gpc` categories off. */\n  gpc: () => boolean\n  /** Whether a category is on now: a required one always is, another once it is granted. */\n  has: (id: Id) => boolean\n  /** Saves which optional categories are on; the rest are off. */\n  save: (granted: readonly Id[]) => void\n  /** Shows the banner again on its settings, so a choice is changed as easily as it was given. */\n  open: () => void\n  subscribe: (onChange: () => void) => () => void\n}\n\n/** What the script before the first paint needs, as plain data. */\ninterface ConsentConfig {\n  storageKey: string | null\n  revision: number\n  expiresAfterDays: number\n  /** Each category's id, with what it grants Google and whether GPC keeps it off. */\n  categories: {\n    id: string\n    required: boolean\n    google: readonly string[]\n    gpc: boolean\n  }[]\n}\n\n/**\n * The saved choice, when it is still valid: well formed, under `revision`\n * and given after `since`, the day a choice kept `expiresAfterDays` would\n * have to be given after to hold today. `null` when there's none, storage\n * is blocked or it was kept by hand. Inlined in the script, so it\n * references nothing outside itself.\n */\nfunction readChoice(storageKey: string | null, revision: number, since: string) {\n  if (storageKey === null) return null\n  let value: unknown\n  try {\n    value = JSON.parse(localStorage.getItem(storageKey) ?? 'null')\n  } catch {\n    return null\n  }\n  if (typeof value !== 'object' || value === null) return null\n  const { granted, date } = value as Record<string, unknown>\n  if (\n    !Array.isArray(granted) ||\n    !granted.every((id) => typeof id === 'string') ||\n    typeof date !== 'string' ||\n    !/^\\d{4}-\\d{2}-\\d{2}$/.test(date) ||\n    (value as { revision?: unknown }).revision !== revision ||\n    date <= since\n  )\n    return null\n  return { granted: granted as string[], date, revision }\n}\n\n/**\n * Every Google Consent Mode type the categories name, granted when a\n * category that is on names it and denied otherwise. Inlined in the script.\n */\nfunction googleConsent(\n  categories: ConsentConfig['categories'],\n  isOn: (category: ConsentConfig['categories'][number]) => boolean,\n): Record<string, 'granted' | 'denied'> {\n  const types: Record<string, 'granted' | 'denied'> = {}\n  for (const category of categories) {\n    for (const type of category.google) {\n      if (isOn(category)) types[type] = 'granted'\n      else types[type] ??= 'denied'\n    }\n  }\n  return types\n}\n\n/** Whether a category is on, for a choice and the browser's GPC. */\nfunction isGranted(\n  category: { id: string; required?: boolean; gpc?: boolean },\n  choice: { granted: readonly string[] } | null,\n  gpc: boolean,\n): boolean {\n  if (category.required) return true\n  if (category.gpc && gpc) return false\n  return choice?.granted.includes(category.id) ?? false\n}\n\n/**\n * Runs before the first paint, from `<head>`: Google's tags start with every\n * type denied, and a saved choice grants its own before they load.\n */\nfunction applySavedConsent(\n  config: ConsentConfig,\n  read: typeof readChoice,\n  google: typeof googleConsent,\n  granted: typeof isGranted,\n  daysAgo: typeof daysAgoInline,\n) {\n  const page = window as unknown as {\n    dataLayer?: unknown[]\n    gtag?: (...args: unknown[]) => void\n  }\n  const dataLayer = (page.dataLayer ??= [])\n  // Google's own snippet: its tag reads each call's `arguments` object, not an\n  // array. Nothing in this script is named, so it runs as written once inlined.\n  page.gtag ??= function () {\n    // eslint-disable-next-line prefer-rest-params -- Google's tag reads each call's arguments object\n    dataLayer.push(arguments)\n  }\n  const gtag = page.gtag\n  const denied = google(config.categories, () => false)\n  gtag('consent', 'default', { ...denied, wait_for_update: 500 })\n  const choice = read(\n    config.storageKey,\n    config.revision,\n    daysAgo(config.expiresAfterDays),\n  )\n  const gpc =\n    (navigator as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n  if (choice)\n    gtag(\n      'consent',\n      'update',\n      google(config.categories, (category) => granted(category, choice, gpc)),\n    )\n}\n\nfunction consentScript(config: ConsentConfig): string {\n  return `(${applySavedConsent.toString()})(${JSON.stringify(config)},${readChoice.toString()},${googleConsent.toString()},${isGranted.toString()},${daysAgoInline.toString()})`\n}\n\n/** Tells Google's tags what is on now, when the page has them. */\nfunction updateGoogle(config: ConsentConfig, choice: ConsentChoice | null, gpc: boolean) {\n  const types = googleConsent(config.categories, (category) =>\n    isGranted(category, choice, gpc),\n  )\n  if (Object.keys(types).length === 0) return\n  const { gtag } = window as unknown as { gtag?: (...args: unknown[]) => void }\n  gtag?.('consent', 'update', types)\n}\n\n/** The state for what is saved and whether the banner was opened. */\nfunction stateOf<Id extends string>(\n  choice: ConsentChoice<Id> | null,\n  opened: boolean,\n): ConsentState<Id> {\n  return choice && !opened\n    ? { status: 'given', choice }\n    : { status: 'asking', choice, opened }\n}\n\n/** The choice to save: the optional categories it turns on that GPC leaves free, given `on` the day it is. */\nfunction choiceFor<Id extends string>(\n  categories: readonly ConsentCategory<Id>[],\n  granted: readonly Id[],\n  { on, revision, gpc }: { on: string; revision: number; gpc: boolean },\n): ConsentChoice<Id> {\n  return {\n    granted: categories\n      .filter(\n        (category) =>\n          !category.required && !(category.gpc && gpc) && granted.includes(category.id),\n      )\n      .map((category) => category.id),\n    date: on,\n    revision,\n  }\n}\n\nfunction createConsent<const Id extends string>({\n  categories,\n  revision = 1,\n  expiresAfterDays = 182,\n  storageKey = 'consent',\n}: ConsentOptions<Id>): Consent<Id> {\n  const config: ConsentConfig = {\n    storageKey,\n    revision,\n    expiresAfterDays,\n    categories: categories.map((category) => ({\n      id: category.id,\n      required: category.required ?? false,\n      google: category.google ?? [],\n      gpc: category.gpc ?? false,\n    })),\n  }\n  const ids = new Set<string>(categories.map((category) => category.id))\n  const listeners = new Set<() => void>()\n  let saved: ConsentChoice<Id> | null | undefined\n  let opened = false\n  let state: ConsentState<Id> | null = null\n  let stopListening = () => {}\n\n  const gpc = () =>\n    typeof navigator !== 'undefined' &&\n    (navigator as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n  const read = (): ConsentChoice<Id> | null => {\n    const choice = readChoice(storageKey, revision, addDays(today(), -expiresAfterDays))\n    if (!choice) return null\n    // A category since removed is dropped, so it can't come back granted.\n    return {\n      ...choice,\n      granted: choice.granted.filter((id): id is Id => ids.has(id)),\n    }\n  }\n  const choice = () => (saved === undefined ? (saved = read()) : saved)\n  const get = () => (state ??= stateOf(choice(), opened))\n  const changed = () => {\n    state = null\n    for (const listener of listeners) listener()\n  }\n\n  return {\n    categories,\n    config,\n    get,\n    gpc,\n    has: (id) => {\n      const category = categories.find((each) => each.id === id)\n      return category ? isGranted(category, choice(), gpc()) : false\n    },\n    save: (granted) => {\n      const next = choiceFor(categories, granted, {\n        on: today(),\n        revision,\n        gpc: gpc(),\n      })\n      try {\n        if (storageKey !== null) localStorage.setItem(storageKey, JSON.stringify(next))\n      } catch {\n        // Blocked or full storage: the choice still holds for this visit.\n      }\n      saved = next\n      opened = false\n      updateGoogle(config, next, gpc())\n      changed()\n    },\n    open: () => {\n      if (opened) return\n      opened = true\n      changed()\n    },\n    subscribe: (onChange) => {\n      if (listeners.size === 0 && storageKey !== null) {\n        // A choice made in another tab; a `null` key means its storage was cleared.\n        const onStorage = (event: StorageEvent) => {\n          if (event.key !== null && event.key !== storageKey) return\n          saved = read()\n          updateGoogle(config, saved, gpc())\n          changed()\n        }\n        window.addEventListener('storage', onStorage)\n        stopListening = () => window.removeEventListener('storage', onStorage)\n      }\n      listeners.add(onChange)\n      return () => {\n        listeners.delete(onChange)\n        if (listeners.size === 0) stopListening()\n      }\n    },\n  }\n}\n\nconst UNKNOWN: ConsentState<never> = { status: 'unknown' }\nconst serverState = () => UNKNOWN\n\n/** The consent's state, whether a category is on, and the functions that change it. */\nfunction useConsent<Id extends string>(consent: Consent<Id>) {\n  const state = useSyncExternalStore(consent.subscribe, consent.get, serverState)\n  const has = (id: Id) => {\n    if (state.status === 'unknown') return false\n    const category = consent.categories.find((each) => each.id === id)\n    return category ? isGranted(category, state.choice, consent.gpc()) : false\n  }\n  return { state, has, save: consent.save, open: consent.open }\n}\n\n/**\n * Renders `children`, such as an analytics script, only while `category` is\n * on. They mount once the press that granted it has painted, so the banner\n * answers first.\n */\nfunction ConsentGate<Id extends string>({\n  consent,\n  category,\n  children,\n}: {\n  consent: Consent<Id>\n  category: Id\n  children: ReactNode\n}) {\n  const on = useDeferredValue(useConsent(consent).has(category))\n  return on ? children : null\n}\n\n/**\n * Starts Google's tags with every type denied, then grants what a saved\n * choice turned on, before they load. Put it in `<head>`, before Google's\n * own script.\n */\nfunction ConsentScript({\n  consent,\n  nonce,\n}: {\n  consent: Consent\n  /** Your Content Security Policy's nonce, for the inline script. */\n  nonce?: string\n}) {\n  return (\n    <script\n      // It runs once, from the server's HTML, as the Preferences item's colour scheme script does.\n      type={typeof window === 'undefined' ? undefined : 'text/plain'}\n      nonce={nonce}\n      suppressHydrationWarning\n      // oxlint-disable-next-line react/no-danger\n      dangerouslySetInnerHTML={{ __html: consentScript(consent.config) }}\n    />\n  )\n}\n\nexport { ConsentGate, ConsentScript, createConsent, useConsent }\n\nexport { choiceFor, consentScript, googleConsent, isGranted, readChoice, stateOf }\n\nexport type { Consent, ConsentCategory, ConsentChoice, ConsentOptions, ConsentState }\n",
      "type": "registry:lib",
      "target": "@lib/consent.tsx"
    }
  ],
  "type": "registry:lib"
}