Files
ipal-kit/src/modules/consent/CookieBanner.tsx
T
Radosław SmolińskiandClaude Opus 5.5 99036eb70c Consent compliance: Global Privacy Control honoured, equal choice by default, withdrawal that stops running tools, consent log on by default
- GPC (gpc.ts): read in the browser before the first paint (consentBannerScript) and in the consent store; pages stay
  static. 'honour' (default): no banner, analytics and marketing off, no request to Google or a pixel; an explicit
  choice on the site wins; a grant made without the signal gives way when it appears. 'ask' and false as opt-outs.
- equalChoice defaults to true; a development warning when the banner has no 'reject'.
- Withdrawal: Meta / TikTok / Clarity told at once, listed localStorage / sessionStorage keys removed.
- Clarity gets consentv2 when it loads; ads_data_redaction with the Consent Mode default.
- consentLog on by default (consentLog: false turns it off); SiteProviders posts to it by itself; a missing SQL table
  answers 503 with one log line.
- Default banner text: one sentence on changing the choice and browser settings; the GPC line (PL / EN).
- Doctor: consent-log-migration, consent-banner rules.
- Stats: Sec-GPC over a choice made without it keeps the visitor id out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:38:39 +01:00

518 lines
23 KiB
TypeScript

'use client'
import { Cookie } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js'
import { BANNER_PENDING_ATTRIBUTE, BANNER_READY_ATTRIBUTE, consentBannerScript } from './firstPaint.js'
/** A button on the banner (first level). */
export type CookieBannerAction = 'accept' | 'reject' | 'settings'
/** A button under the category list (settings view). */
export type CookieSettingsAction = 'accept' | 'back' | 'reject' | 'save'
/**
* Optional class overrides — for when tokens aren't enough, e.g. turning the
* bottom bar into a centred modal. Each slot replaces its default classes
* outright. Per-button slots (acceptButton, rejectButton…) fall back to
* primaryButton / secondaryButton, so styling those two still restyles all.
*/
export type CookieBannerClassNames = {
/** Button "Accept all" — falls back to primaryButton. */
acceptButton?: string
/** Button row on the banner. */
actions?: string
/** Settings view: button "Back" (closes the dialog in modal mode) — falls back to secondaryButton. */
backButton?: string
/** Settings view: badge next to Necessary (CookieSettings → alwaysActiveLabel). */
badge?: string
/** Banner inner wrapper (width / centring). */
body?: string
/** Settings view: list of categories. */
categories?: string
/** Settings view: one category row/card. */
category?: string
/** Detailed window: the card around one category (row + cookie list). */
categoryCard?: string
categoryDescription?: string
categoryTitle?: string
/** Settings dialog (modal mode): the ✕ button. */
closeButton?: string
/** Banner: text + buttons row. */
content?: string
/** Settings view: the switch track or the checkbox. */
control?: string
/** Settings view: the switch knob (controls="switch"). */
controlThumb?: string
/** Detailed window: one cookie in a category's list. */
cookie?: string
/** Detailed window: list of cookies under a category. */
cookieList?: string
/** Detailed window: provider / purpose / duration grid of one cookie. */
cookieMeta?: string
/** Detailed window: cookie name. */
cookieName?: string
/** Detailed window: <details> wrapping a category's cookie list. */
cookies?: string
/** Detailed window: the <summary> that expands the cookie list. */
cookiesToggle?: string
/** Settings dialog box (modal mode; detailed mode uses a wider default). */
dialog?: string
/** Small label above the banner title (CookieSettings → eyebrow). */
eyebrow?: string
/** The line saying the browser's Global Privacy Control was honoured (banner and settings view). */
gpcNotice?: string
/** Cookie icon next to the banner text and the settings title. */
icon?: string
/** Privacy-policy link inside the message. */
link?: string
message?: string
/** Backdrop behind the settings dialog (modal mode). */
overlay?: string
primaryButton?: string
/** Button "Reject" — falls back to primaryButton with equalChoice, else secondaryButton. */
rejectButton?: string
root?: string
/** Settings view: button "Save preferences" — falls back to primaryButton. */
saveButton?: string
secondaryButton?: string
/** Settings view: button row under the categories. */
settingsActions?: string
/** Button "Settings" on the banner — falls back to secondaryButton. */
settingsButton?: string
/** Settings view: intro under the title (CookieSettings → settingsDescription). */
settingsDescription?: string
settingsTitle?: string
/** Banner: block with eyebrow, title and message. */
text?: string
/** Banner heading (CookieSettings → title). */
title?: string
}
/**
* Colours and radius come from the design tokens (docs/design-tokens.md) with
* built-in fallbacks, so the banner looks right with no setup, and re-skinning
* per client means declaring a few variables — no imports, no props, no
* specificity fights:
*
* ```css
* :root {
* --ipal-primary: #16a34a;
* --ipal-radius: 1rem;
* }
* ```
*
* Read: --ipal-surface, --ipal-border, --ipal-text, --ipal-text-strong,
* --ipal-text-muted, --ipal-primary, --ipal-primary-hover, --ipal-primary-text,
* --ipal-hover, --ipal-radius. With @intecion/ipal-kit/tokens.css they switch
* with the theme on their own. Without it, the fallback follows the page's
* color-scheme (light-dark()) and the legacy `-dark` variables
* (e.g. --ipal-surface-dark) still set the dark fallback.
*
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
* exposing them as tokens would mean re-inventing CSS one variable at a time.
* For a different layout use classNames (every element has a slot).
*/
const surface = 'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))]'
const border = 'border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))]'
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
const accent = 'text-[var(--ipal-primary,#2563eb)]'
const bodyText = 'text-[var(--ipal-text,light-dark(#404040,var(--ipal-text-dark,#d4d4d4)))]'
const strongText = 'text-[var(--ipal-text-strong,light-dark(#171717,var(--ipal-text-strong-dark,#f5f5f5)))]'
const mutedText = 'text-[var(--ipal-text-muted,light-dark(#737373,var(--ipal-text-muted-dark,#a3a3a3)))]'
const primaryBg = 'bg-[var(--ipal-primary,#2563eb)]'
const defaults: Required<CookieBannerClassNames> = {
acceptButton: '',
actions: 'flex shrink-0 gap-2',
backButton: '',
badge: `shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${border} ${accent}`,
body: 'mx-auto max-w-4xl',
categories: 'flex flex-col gap-3',
category: 'flex items-start justify-between gap-4',
categoryCard: `flex flex-col gap-3 ${radius} border p-4 ${border}`,
categoryDescription: `text-xs ${mutedText}`,
categoryTitle: `text-sm font-medium ${strongText}`,
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]`,
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
cookie: `flex flex-col gap-1 border-t pt-2 first:border-t-0 first:pt-0 ${border}`,
cookieList: 'mt-3 flex flex-col gap-2',
cookieMeta: `grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs ${mutedText}`,
cookieName: `font-mono text-xs font-semibold ${strongText}`,
cookies: 'group',
cookiesToggle: `inline-flex cursor-pointer select-none items-center gap-1 text-xs font-medium ${accent} hover:underline [&::-webkit-details-marker]:hidden`,
dialog: `relative max-h-[90vh] w-full max-w-2xl overflow-y-auto ${radius} border p-6 shadow-2xl ${surface} ${border}`,
eyebrow: `mb-1 text-xs font-semibold uppercase tracking-wider ${accent}`,
gpcNotice: `text-xs ${mutedText}`,
icon: `h-6 w-6 shrink-0 ${accent}`,
link: `${accent} underline hover:no-underline`,
message: `text-justify text-sm ${bodyText}`,
overlay: 'fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4',
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium ${primaryBg} text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
rejectButton: '',
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
saveButton: '',
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,light-dark(#404040,var(--ipal-text-dark,#d4d4d4)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]`,
settingsActions: 'flex justify-end gap-2',
settingsButton: '',
settingsDescription: `text-sm ${bodyText}`,
settingsTitle: `flex items-center gap-2 text-base font-semibold ${strongText}`,
text: 'flex items-start gap-3',
title: `mb-1 text-base font-semibold ${strongText}`,
}
/** Default switch track (controls="switch") — the checkbox default doesn't fit a <button>. */
/** Default dialog for settings="detailed" — wider and taller than the modal one. */
const DETAILED_DIALOG = `relative max-h-[90vh] w-full max-w-4xl overflow-y-auto ${radius} border p-6 shadow-2xl sm:p-8 ${surface} ${border}`
const SWITCH_TRACK =
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
type CookieBannerProps = {
classNames?: CookieBannerClassNames
/** Category controls: native checkboxes (default) or accessible switches (role="switch"). */
controls?: 'checkbox' | 'switch'
/**
* Style "Reject" like "Accept all" (primary). EU data-protection authorities (EDPB Cookie Banner Taskforce, 2023;
* repeated by UODO) expect refusing to be as easy and as visible as accepting. Default true since 1.17.0;
* `false` styles "Reject" as the secondary button (before 1.17.0) — iapl-doctor then warns.
*/
equalChoice?: boolean
/**
* Render the banner on the server, so it is part of the first paint instead of appearing after hydration (where it
* often becomes the page's LCP element). Default true. On a static page the HTML is the same for every visitor:
* the banner is there with `hidden`, and an inline script right after it (consentBannerScript) shows it, or keeps
* it hidden for a visitor with a current decision, before the browser paints. With a server-read cookie
* (<ConsentProvider cookieValue>) the HTML is exact and there is no script. `false` = as before 1.17.0: nothing
* until the page has hydrated.
*/
firstPaint?: boolean
/** Cookie icon next to the banner text and the settings title. Default true. */
icon?: boolean
/** CSP nonce for the first-paint script. Default: the one given to <ConsentProvider> / <SiteProviders>. */
nonce?: string
/**
* Banner buttons, in this order. Default ['settings', 'reject', 'accept']. Keep 'reject': refusing must be possible
* on the first layer (a development warning and iapl-doctor say so when it is missing).
*/
order?: CookieBannerAction[]
/**
* Where category settings open:
* - 'inline' (default) — in the banner itself;
* - 'modal' — a centred dialog over a dimmed page (closes with ✕, Escape or a click outside);
* - 'detailed' — like 'modal', but a large window: each category is a card with its
* on/off control, description and an expandable list of its cookies (name, provider,
* purpose, duration) from Cookie Settings → Cookies.
*/
settings?: 'detailed' | 'inline' | 'modal'
/** Buttons under the categories, in this order. Default ['back', 'save']. */
settingsActions?: CookieSettingsAction[]
}
const DEFAULT_ORDER: CookieBannerAction[] = ['settings', 'reject', 'accept']
const DEFAULT_SETTINGS_ACTIONS: CookieSettingsAction[] = ['back', 'save']
export function CookieBanner({
classNames,
controls = 'checkbox',
equalChoice = true,
firstPaint = true,
icon = true,
nonce,
order = DEFAULT_ORDER,
settings = 'inline',
settingsActions = DEFAULT_SETTINGS_ACTIONS,
}: CookieBannerProps = {}) {
const { acceptAll, decided, gpc, gpcMode, hydrated, nonce: contextNonce, rejectAll, savePreferences, serverRead, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false)
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
const closeRef = useRef<HTMLButtonElement>(null)
const rootRef = useRef<HTMLDivElement>(null)
const modal = settings !== 'inline'
const detailed = settings === 'detailed'
useEffect(() => {
setChoices(state)
}, [state])
// Modal: focus the ✕ on open, Escape closes (back to the banner)
useEffect(() => {
if (!modal || !showSettings) {return}
closeRef.current?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {setShowSettings(false)}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [modal, showSettings])
// Refusing must be possible on the first layer (EDPB Cookie Banner Taskforce): say so while developing.
const noReject = !order.includes('reject')
useEffect(() => {
if (noReject && process.env.NODE_ENV !== 'production') {
console.warn("[iapl] <CookieBanner order> has no 'reject': visitors cannot refuse on the first layer (docs/consent.md → Equal choice)")
}
}, [noReject])
// A banner that came with the server HTML can be clicked before this component is live: the first-paint script
// noted the button, carry the click out now (once) and take over.
useEffect(() => {
const el = rootRef.current
if (!el || el.hasAttribute(BANNER_READY_ATTRIBUTE)) {return}
const pending = el.getAttribute(BANNER_PENDING_ATTRIBUTE)
el.removeAttribute(BANNER_PENDING_ATTRIBUTE)
el.setAttribute(BANNER_READY_ATTRIBUTE, '')
if (pending === 'accept') {acceptAll()}
else if (pending === 'reject') {rejectAll()}
else if (pending === 'settings') {setShowSettings(true)}
// once, when the server-rendered banner becomes live
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// firstPaint={false}: nothing in the server HTML, the banner appears once the page has hydrated (before 1.17.0).
if (!firstPaint && !hydrated) {return null}
// While hydrating `decided` is the server's value, so this matches the server HTML; the browser's own value
// follows before the next paint (useConsent).
if (decided) {return null}
// The HTML every visitor gets (static page, nothing read on the server): hidden until the script after it, or
// hydration, has looked at the cookie. With a server-read cookie and no decision the server still cannot know
// Global Privacy Control (a browser signal), so with `gpc: 'honour'` the script decides that part too.
const undecidedHtml = !hydrated && (!serverRead || gpcMode === 'honour')
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
const primary = cn('primaryButton')
const secondary = cn('secondaryButton')
const buttonClass: Record<CookieBannerAction | CookieSettingsAction, string> = {
accept: classNames?.acceptButton ?? primary,
back: classNames?.backButton ?? secondary,
reject: classNames?.rejectButton ?? (equalChoice ? primary : secondary),
save: classNames?.saveButton ?? primary,
settings: classNames?.settingsButton ?? secondary,
}
const run: Record<CookieBannerAction | CookieSettingsAction, () => void> = {
accept: acceptAll,
back: () => setShowSettings(false),
reject: rejectAll,
save: () => savePreferences(choices),
settings: () => setShowSettings(true),
}
const label: Record<CookieBannerAction | CookieSettingsAction, string> = {
accept: texts.buttons.acceptAll,
back: texts.buttons.back,
reject: texts.buttons.reject,
save: texts.buttons.save,
settings: texts.buttons.settings,
}
const button = (action: CookieBannerAction | CookieSettingsAction) => (
<button className={buttonClass[action]} data-ipal={action} key={action} onClick={run[action]} type="button">
{label[action]}
</button>
)
const toggle = (cat: ConsentCategory) => {
if (cat === 'necessary') {return}
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
}
const control = (cat: ConsentCategory) => {
const checked = cat === 'necessary' ? true : choices[cat]
if (cat === 'necessary' && texts.alwaysActiveLabel) {
return <span className={cn('badge')}>{texts.alwaysActiveLabel}</span>
}
if (controls === 'switch') {
return (
<button
aria-checked={checked}
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
className={classNames?.control ?? SWITCH_TRACK}
data-checked={checked}
disabled={cat === 'necessary'}
onClick={() => toggle(cat)}
role="switch"
type="button"
>
<span aria-hidden="true" className={cn('controlThumb')} data-checked={checked} />
</button>
)
}
return (
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={checked}
className={cn('control')}
disabled={cat === 'necessary'}
onChange={() => toggle(cat)}
type="checkbox"
/>
)
}
const cookieList = (cat: ConsentCategory) => {
const rows = texts.cookies?.filter((row) => row.category === cat) ?? []
const labels = texts.details
if (!labels || rows.length === 0) {return null}
return (
<details className={cn('cookies')} data-ipal="cookies">
<summary className={cn('cookiesToggle')}>
<svg aria-hidden="true" className="transition-transform group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
<path d="m9 18 6-6-6-6" />
</svg>
{labels.cookies} ({rows.length})
</summary>
<ul className={cn('cookieList')}>
{rows.map((row) => (
<li className={cn('cookie')} key={row.name}>
<code className={cn('cookieName')}>{row.name}</code>
<dl className={cn('cookieMeta')}>
{row.provider && (
<>
<dt>{labels.provider}</dt>
<dd>{row.provider}</dd>
</>
)}
{row.purpose && (
<>
<dt>{labels.purpose}</dt>
<dd>{row.purpose}</dd>
</>
)}
{row.duration && (
<>
<dt>{labels.duration}</dt>
<dd>{row.duration}</dd>
</>
)}
{row.storage && row.storage !== 'cookie' && labels.storage && (
<>
<dt>{labels.storage}</dt>
<dd>{labels.storageTypes?.[row.storage] ?? row.storage}</dd>
</>
)}
</dl>
</li>
))}
</ul>
</details>
)
}
const categoryRow = (cat: ConsentCategory) => (
<>
<div>
<p className={cn('categoryTitle')} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={cn('categoryDescription')} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p>
</div>
{control(cat)}
</>
)
const settingsView = (
<div className="flex flex-col gap-4">
<div className="flex items-start justify-between gap-4">
<h2 className={cn('settingsTitle')} id="ipal-consent-title">
{icon && (!modal || detailed) && <Cookie aria-hidden="true" className={cn('icon')} />}
{texts.settingsTitle}
</h2>
{modal && (
<button aria-label={texts.buttons.close} className={cn('closeButton')} data-ipal="close" onClick={() => setShowSettings(false)} ref={closeRef} type="button">
<svg aria-hidden="true" fill="none" height="20" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="20">
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
)}
</div>
{texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
{gpc && texts.gpcNotice ? <p className={cn('gpcNotice')} data-ipal="gpc-notice">{texts.gpcNotice}</p> : null}
<ul className={cn('categories')}>
{CONSENT_CATEGORIES.map((cat) =>
detailed ? (
<li className={cn('categoryCard')} data-ipal={`category-${cat}`} key={cat}>
<div className={cn('category')}>{categoryRow(cat)}</div>
{cookieList(cat)}
</li>
) : (
<li className={cn('category')} key={cat}>
{categoryRow(cat)}
</li>
),
)}
</ul>
<div className={cn('settingsActions')}>{settingsActions.map(button)}</div>
</div>
)
if (modal && showSettings) {
return (
<div
className={cn('overlay')}
data-ipal="consent-overlay"
// banner text is not page content — keep it out of Google's snippets
data-nosnippet
onClick={(event) => {
if (event.target === event.currentTarget) {setShowSettings(false)}
}}
// klik w tło zamyka dialog; klawiatura: Escape (listener wyżej) i przycisk ✕
role="presentation"
>
<div aria-labelledby="ipal-consent-title" aria-modal="true" className={classNames?.dialog ?? (detailed ? DETAILED_DIALOG : defaults.dialog)} data-ipal="consent-dialog" role="dialog">
{settingsView}
</div>
</div>
)
}
return (
<>
{/* suppressHydrationWarning: the script below changes `hidden` / `style` before React hydrates, on purpose */}
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" data-nosnippet hidden={undecidedHtml || undefined} ref={rootRef} role="dialog" suppressHydrationWarning>
<div className={cn('body')}>
{!showSettings ? (
<div className={cn('content')}>
<div className={cn('text')}>
{icon && <Cookie aria-hidden="true" className={cn('icon')} />}
<div>
{texts.eyebrow && <p className={cn('eyebrow')}>{texts.eyebrow}</p>}
{texts.title && <h2 className={cn('title')}>{texts.title}</h2>}
<p className={cn('message')}>
{texts.message}
{texts.privacyLink && (
<>
{' '}
<a className={cn('link')} href={texts.privacyLink.href}>
{texts.privacyLink.label}
</a>
</>
)}
</p>
{gpc && texts.gpcNotice ? <p className={cn('gpcNotice')} data-ipal="gpc-notice">{texts.gpcNotice}</p> : null}
</div>
</div>
<div className={cn('actions')}>{order.map(button)}</div>
</div>
) : (
settingsView
)}
</div>
</div>
{/* Only in the server HTML (gone with the first client render): a script React creates in the browser never runs.
suppressHydrationWarning: browsers hide the nonce attribute from the DOM. */}
{undecidedHtml ? (
<script
dangerouslySetInnerHTML={{ __html: consentBannerScript({ gpc: gpcMode, version: texts.version }) }}
data-ipal="banner-script"
nonce={nonce ?? contextNonce}
suppressHydrationWarning
/>
) : null}
</>
)
}