'use client' import { useCallback, useEffect, useMemo, useState } from 'react' import type { ConsentCategory, ConsentState } from './categories.js' import { LOCALE_COOKIE_NAME } from '../i18n/index.js' import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js' import { updateConsent } from './googleConsent.js' import { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js' export type ConsentCookieMap = Partial> /** * Cookies deleted when consent for a category is withdrawn (GDPR: withdrawing * must stop the processing). `name*` matches a prefix (`_ga_*` → _ga_ABC123). * Covers the plugin's own functional cookie and the tools Analytics can load; * projects add theirs through (merged, not replaced). */ export const DEFAULT_COOKIE_MAP: ConsentCookieMap = { analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*'], functional: [LOCALE_COOKIE_NAME], marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'], } function mergeCookieMaps(extra?: ConsentCookieMap): ConsentCookieMap { if (!extra) {return DEFAULT_COOKIE_MAP} const out: ConsentCookieMap = { ...DEFAULT_COOKIE_MAP } for (const [cat, names] of Object.entries(extra) as [ConsentCategory, string[]][]) { out[cat] = [...new Set([...(out[cat] ?? []), ...names])] } return out } /** Names of cookies currently set that match a pattern (`name` or prefix `name*`). */ function matchingCookies(pattern: string): string[] { const names = document.cookie.split('; ').map((c) => c.split('=')[0]).filter(Boolean) return pattern.endsWith('*') ? names.filter((n) => n.startsWith(pattern.slice(0, -1))) : names.filter((n) => n === pattern) } /** * Expire a cookie on this host AND every parent domain — GA, Meta and others * set theirs on the registrable domain (.acme.pl), which a host-only delete * leaves behind. */ function deleteCookie(name: string) { const parts = location.hostname.split('.') const domains = [''] // host-only for (let i = 0; i < parts.length - 1; i++) {domains.push(`;domain=.${parts.slice(i).join('.')}`)} for (const domain of domains) {document.cookie = `${name}=;path=/;max-age=0;samesite=lax${domain}`} } type UseConsentOptions = { /** Extra cookies per category to delete on withdrawal — merged with DEFAULT_COOKIE_MAP. */ cookieMap?: ConsentCookieMap /** * Called after every decision with the consent id and choices — e.g. POST to * the consent log (createConsentLogEndpoint). Never blocks the banner. */ onDecision?: (record: { id: string; state: ConsentState; version: number }) => void /** Policy version from the panel (Cookie Settings). A stored consent from another version asks again. */ version?: number } export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) { // Backwards compatible: the old signature took the cookie map directly. const opts: UseConsentOptions = 'cookieMap' in options || 'version' in options || 'onDecision' in options ? (options) : { cookieMap: options as ConsentCookieMap } const version = opts.version ?? CONSENT_VERSION // Merge once per distinct map (props may pass a new object each render). const cookieMapKey = JSON.stringify(opts.cookieMap ?? null) const cookieMap = useMemo(() => mergeCookieMaps(opts.cookieMap), [cookieMapKey]) const { onDecision } = opts const [state, setState] = useState(DEFAULT_CONSENT) const [decided, setDecided] = useState(false) const [consentId, setConsentId] = useState(undefined) useEffect(() => { const raw = document.cookie .split('; ') .find((c) => c.startsWith(`${CONSENT_COOKIE}=`)) ?.split('=')[1] const record = readConsentRecord(raw, version) if (record) { setState(record.state) setDecided(true) setConsentId(record.id) } }, [version]) const persist = useCallback( (next: ConsentState) => { // Withdrawal cleanup: for any category flipping true → false, delete the // cookies tied to it. GDPR: withdrawing consent must stop the processing. for (const cat of Object.keys(cookieMap) as ConsentCategory[]) { if (state[cat] === true && next[cat] !== true) { for (const pattern of cookieMap[cat] ?? []) { for (const name of matchingCookies(pattern)) {deleteCookie(name)} } } } const id = consentId ?? newConsentId() const secure = location.protocol === 'https:' ? ';secure' : '' document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next, version, id)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}` setState(next) setDecided(true) setConsentId(id) // Tell Google right away. Tags are already on the page holding whatever // defaults Analytics set at load; without this update they keep them for // the rest of the session and never write their cookies — the banner would // look like it worked while nothing changed. updateConsent(next) try { onDecision?.({ id, state: next, version }) } catch { // a logging hook must never break the banner } }, [state, consentId, version, onDecision, cookieMap], ) const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist]) const rejectAll = useCallback(() => persist(REJECT_ALL_CONSENT), [persist]) const savePreferences = useCallback( (choices: Partial>) => persist({ ...DEFAULT_CONSENT, ...choices, necessary: true }), [persist], ) const reopen = useCallback(() => setDecided(false), []) return { acceptAll, consentId, decided, rejectAll, reopen, savePreferences, state } }