Merge claude/consent-banner-first-paint-154f9f: the cookie banner is part of the first render
Conflicts in the docs only, both sides kept: changelog lines, AGENT.md checklist rows 12 (banner) and 13 (wrapper order), the two iapl-upgrade blocks, PROGRAMISTA rows 76 (client hints) and 77 (banner, renumbered from 76). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -6,7 +6,7 @@ import type { ConsentCookieMap } from './useConsent.js'
|
||||
|
||||
import { useConsent } from './useConsent.js'
|
||||
|
||||
type ConsentContextValue = { texts: ConsentTexts } & ReturnType<typeof useConsent>
|
||||
type ConsentContextValue = { nonce?: string; texts: ConsentTexts } & ReturnType<typeof useConsent>
|
||||
|
||||
const ConsentContext = createContext<ConsentContextValue | null>(null)
|
||||
|
||||
@@ -14,18 +14,28 @@ type ConsentProviderProps = {
|
||||
children: ReactNode
|
||||
/** Extra cookies per category to delete when consent is withdrawn — merged with the built-in list. */
|
||||
cookieMap?: ConsentCookieMap
|
||||
/**
|
||||
* Optional server read: the consent cookie's raw value from this request
|
||||
* (`(await cookies()).get(CONSENT_COOKIE)?.value ?? null`). The HTML then has no banner for a visitor who already
|
||||
* decided — and the page is dynamic (no static / ISR copy). Leave out to keep pages static (the default): the
|
||||
* banner is in the HTML for everyone and an inline script decides before the first paint.
|
||||
*/
|
||||
cookieValue?: null | string
|
||||
/**
|
||||
* Consent log endpoint (createConsentLogEndpoint, e.g. '/api/ipal/consent'):
|
||||
* every decision is POSTed — random id, choices, policy version, no personal
|
||||
* data — so the site can demonstrate consent (GDPR Art. 7(1)). Off when omitted.
|
||||
*/
|
||||
logEndpoint?: string
|
||||
/** CSP nonce for the banner's first-paint script (a nonce policy: `(await headers()).get('x-nonce')`). */
|
||||
nonce?: null | string
|
||||
texts: ConsentTexts
|
||||
}
|
||||
|
||||
export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: ConsentProviderProps) {
|
||||
export function ConsentProvider({ children, cookieMap, cookieValue, logEndpoint, nonce, texts }: ConsentProviderProps) {
|
||||
const consent = useConsent({
|
||||
cookieMap,
|
||||
cookieValue,
|
||||
onDecision: logEndpoint
|
||||
? (record) => {
|
||||
void fetch(logEndpoint, {
|
||||
@@ -38,7 +48,7 @@ export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: Con
|
||||
: undefined,
|
||||
version: texts.version,
|
||||
})
|
||||
return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext>
|
||||
return <ConsentContext value={{ ...consent, nonce: nonce ?? undefined, texts }}>{children}</ConsentContext>
|
||||
}
|
||||
|
||||
export function useConsentContext(): ConsentContextValue {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
|
||||
import { useConsentContext } from './ConsentContext.js'
|
||||
import { useIsMounted } from './useIsMounted.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'
|
||||
@@ -177,8 +177,19 @@ type CookieBannerProps = {
|
||||
* keeps the existing look; recommended true.
|
||||
*/
|
||||
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']. */
|
||||
order?: CookieBannerAction[]
|
||||
/**
|
||||
@@ -201,16 +212,18 @@ export function CookieBanner({
|
||||
classNames,
|
||||
controls = 'checkbox',
|
||||
equalChoice = false,
|
||||
firstPaint = true,
|
||||
icon = true,
|
||||
nonce,
|
||||
order = DEFAULT_ORDER,
|
||||
settings = 'inline',
|
||||
settingsActions = DEFAULT_SETTINGS_ACTIONS,
|
||||
}: CookieBannerProps = {}) {
|
||||
const isMounted = useIsMounted()
|
||||
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
|
||||
const { acceptAll, decided, 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'
|
||||
|
||||
@@ -229,11 +242,29 @@ export function CookieBanner({
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [modal, showSettings])
|
||||
|
||||
// Render nothing until mounted — avoids the React 19 hydration mismatch that
|
||||
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
|
||||
// needed now.
|
||||
if (!isMounted) {return null}
|
||||
// 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.
|
||||
const undecidedHtml = !hydrated && !serverRead
|
||||
|
||||
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
|
||||
const primary = cn('primaryButton')
|
||||
@@ -423,7 +454,9 @@ export function CookieBanner({
|
||||
}
|
||||
|
||||
return (
|
||||
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" data-nosnippet role="dialog">
|
||||
<>
|
||||
{/* 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')}>
|
||||
@@ -452,5 +485,16 @@ export function CookieBanner({
|
||||
)}
|
||||
</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({ version: texts.version }) }}
|
||||
data-ipal="banner-script"
|
||||
nonce={nonce ?? contextNonce}
|
||||
suppressHydrationWarning
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Cookie } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { useConsentContext } from './ConsentContext.js'
|
||||
import { useIsMounted } from './useIsMounted.js'
|
||||
|
||||
/** Elements the button moves up for, so it never covers footer links. */
|
||||
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
|
||||
@@ -34,13 +33,11 @@ export type CookieButtonProps = {
|
||||
* view the button moves up by the visible part of it, so footer links stay free.
|
||||
*/
|
||||
export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'left' }: CookieButtonProps = {}) {
|
||||
const isMounted = useIsMounted()
|
||||
const { decided, reopen, texts } = useConsentContext()
|
||||
const lift = useLiftAbove(avoid, isMounted && decided)
|
||||
const lift = useLiftAbove(avoid, decided)
|
||||
|
||||
// Render nothing until mounted — prevents hydration mismatch (no project
|
||||
// ConsentWrapper workaround needed).
|
||||
if (!isMounted) {return null}
|
||||
// `decided` is the server's value while hydrating (no decision on a static page, so nothing is rendered — or the
|
||||
// cookie the server read, <ConsentProvider cookieValue>, and then the button is in the HTML), the browser's after.
|
||||
if (!decided) {return null}
|
||||
|
||||
const cls =
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { CONSENT_COOKIE, readConsentRecord } from './storage.js'
|
||||
|
||||
/**
|
||||
* The stored consent decision as an external store (React `useSyncExternalStore`).
|
||||
*
|
||||
* Why a store and not state filled in an effect: with a store React hydrates with the server's value and switches to
|
||||
* the browser's own before the browser paints, so the banner and the button can be part of the server HTML with no
|
||||
* hydration mismatch and no frame of the wrong one. One decision per document: every <ConsentProvider> on a page
|
||||
* reads the same value.
|
||||
*/
|
||||
export type ConsentRecord = NonNullable<ReturnType<typeof readConsentRecord>>
|
||||
|
||||
const listeners = new Set<() => void>()
|
||||
/** The value last written in this document — still the decision when the browser refuses to keep the cookie. */
|
||||
let written: string | undefined
|
||||
let cache: { key: string; record: ConsentRecord | null } | undefined
|
||||
|
||||
/** Raw value of the consent cookie in this browser (first cookie of that name), undefined when there is none. */
|
||||
export function readConsentCookie(): string | undefined {
|
||||
if (typeof document === 'undefined') {return undefined}
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
|
||||
?.split('=')[1]
|
||||
}
|
||||
|
||||
/** The current decision under `version`, or null. The same object until the stored value changes. */
|
||||
export function getConsentSnapshot(version: number): ConsentRecord | null {
|
||||
const raw = readConsentCookie()
|
||||
const key = `${version}\n${raw ?? ''}\n${written ?? ''}`
|
||||
if (cache?.key !== key) {
|
||||
cache = { key, record: readConsentRecord(raw, version) ?? readConsentRecord(written, version) }
|
||||
}
|
||||
return cache.record
|
||||
}
|
||||
|
||||
export function subscribeConsent(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the cookie (`value` already serialized, `attributes` like `;path=/;max-age=…`) and tells every reader. */
|
||||
export function writeConsentCookie(value: string, attributes: string): void {
|
||||
document.cookie = `${CONSENT_COOKIE}=${value}${attributes}`
|
||||
written = value
|
||||
for (const listener of listeners) {listener()}
|
||||
}
|
||||
|
||||
/** Tests only: forget what this document wrote. */
|
||||
export function resetConsentStore(): void {
|
||||
written = undefined
|
||||
cache = undefined
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { CONSENT_COOKIE, CONSENT_VERSION } from './storage.js'
|
||||
|
||||
/** Set by the first-paint script: the `data-ipal` action of a button clicked before hydration. */
|
||||
export const BANNER_PENDING_ATTRIBUTE = 'data-ipal-pending'
|
||||
/** Set by <CookieBanner> once it handles clicks itself. */
|
||||
export const BANNER_READY_ATTRIBUTE = 'data-ipal-ready'
|
||||
|
||||
export type ConsentBannerScriptOptions = {
|
||||
/** Name of the consent cookie. Default CONSENT_COOKIE (`cookie-consent`). */
|
||||
cookieName?: string
|
||||
/** Policy version the stored decision must carry (ConsentTexts.version). Default CONSENT_VERSION. */
|
||||
version?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The script <CookieBanner> puts right after its own markup, so the banner is decided BEFORE the first paint on a
|
||||
* page that is the same HTML for every visitor (static / ISR, CDN-cached).
|
||||
*
|
||||
* The server renders the banner with the `hidden` attribute. This script — a classic inline script, so it runs while
|
||||
* the HTML is parsed — looks at the element just before it and at the consent cookie:
|
||||
* - no stored decision under this policy version (no cookie, unreadable, foreign, another version) → `hidden` is
|
||||
* removed: the banner is part of the first paint;
|
||||
* - a current decision → `display: none` on the element, until React takes it out after hydration.
|
||||
*
|
||||
* It decides exactly as readConsentRecord does (first cookie of that name, URI-decoded JSON, `version` equal), reads
|
||||
* nothing else, stores nothing, loads nothing. The banner can be clicked before React has hydrated the page; the
|
||||
* script notes the clicked button (`data-ipal-pending` on the banner) and <CookieBanner> carries the click out once
|
||||
* it is live, so an early "Accept" or "Reject" is not lost. Without JavaScript, or when a CSP refuses the script, the banner stays
|
||||
* hidden until hydration: the behaviour before this script existed.
|
||||
*
|
||||
* Exported for a project that renders its own banner: put `hidden` and `suppressHydrationWarning` on the banner's
|
||||
* root, and this script in a `<script>` (with the nonce) as its next sibling.
|
||||
*/
|
||||
export function consentBannerScript({ cookieName = CONSENT_COOKIE, version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
|
||||
// JSON string literal, safe inside <script>: no `</script>`, no line separators
|
||||
const name = JSON.stringify(`${cookieName}=`)
|
||||
.replace(/</g, '\\u003c')
|
||||
.split(String.fromCharCode(0x2028)).join('\\u2028')
|
||||
.split(String.fromCharCode(0x2029)).join('\\u2029')
|
||||
const v = Number.isFinite(version) ? Number(version) : CONSENT_VERSION
|
||||
return (
|
||||
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
|
||||
`var n=${name},d=false,c=document.cookie?document.cookie.split("; "):[];` +
|
||||
`for(var i=0;i<c.length;i++){if(c[i].indexOf(n)===0){try{d=JSON.parse(decodeURIComponent(c[i].split("=")[1])).version===${v}}catch(e){}break}}` +
|
||||
`if(d){b.style.display="none"}else{b.removeAttribute("hidden");` +
|
||||
// a click on a banner button before the page has hydrated is kept for <CookieBanner> to carry out
|
||||
`b.addEventListener("click",function(e){if(b.hasAttribute("${BANNER_READY_ATTRIBUTE}")){return}` +
|
||||
`var t=e.target,a=t&&t.closest?t.closest("[data-ipal]"):null;if(a&&a!==b){b.setAttribute("${BANNER_PENDING_ATTRIBUTE}",a.getAttribute("data-ipal"))}})}` +
|
||||
`}catch(e){}})()`
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,8 @@ export type { ConsentCategory, ConsentState } from './categories.js'
|
||||
export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js'
|
||||
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './consentLog.js'
|
||||
export type { ConsentLogOptions } from './consentLog.js'
|
||||
export { consentBannerScript } from './firstPaint.js'
|
||||
export type { ConsentBannerScriptOptions } from './firstPaint.js'
|
||||
export { CONSENT_FALLBACK, CONSENT_FALLBACK_PL, consentFallback, getConsentTexts, getCookieTable } from './getConsentTexts.js'
|
||||
export type { CookieTableRow } from './getConsentTexts.js'
|
||||
export { setDefaultConsent, updateConsent } from './googleConsent.js'
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
'use client'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useCallback, useMemo, useState, useSyncExternalStore } 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 { getConsentSnapshot, subscribeConsent, writeConsentCookie } from './consentStore.js'
|
||||
import { updateConsent } from './googleConsent.js'
|
||||
import { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js'
|
||||
import { CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js'
|
||||
|
||||
export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
|
||||
|
||||
@@ -52,6 +53,13 @@ function deleteCookie(name: string) {
|
||||
type UseConsentOptions = {
|
||||
/** Extra cookies per category to delete on withdrawal — merged with DEFAULT_COOKIE_MAP. */
|
||||
cookieMap?: ConsentCookieMap
|
||||
/**
|
||||
* The consent cookie's raw value READ ON THE SERVER for this request (`null` = the request had none). Given, the
|
||||
* server render already knows the decision: no banner in the HTML for a visitor who decided, the button instead.
|
||||
* Reading a cookie makes the page dynamic (no static / ISR HTML, no shared CDN copy) — leave it out to keep pages
|
||||
* static; the banner then decides before the first paint with a small inline script (consentBannerScript).
|
||||
*/
|
||||
cookieValue?: null | string
|
||||
/**
|
||||
* Called after every decision with the consent id and choices — e.g. POST to
|
||||
* the consent log (createConsentLogEndpoint). Never blocks the banner.
|
||||
@@ -61,10 +69,14 @@ type UseConsentOptions = {
|
||||
version?: number
|
||||
}
|
||||
|
||||
const noSubscription = () => () => {}
|
||||
const isClient = () => true
|
||||
const isServer = () => false
|
||||
|
||||
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
|
||||
'cookieMap' in options || 'version' in options || 'onDecision' in options || 'cookieValue' in options
|
||||
? (options)
|
||||
: { cookieMap: options as ConsentCookieMap }
|
||||
const version = opts.version ?? CONSENT_VERSION
|
||||
@@ -73,22 +85,25 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
|
||||
const cookieMap = useMemo(() => mergeCookieMaps(opts.cookieMap), [cookieMapKey])
|
||||
const { onDecision } = opts
|
||||
|
||||
const [state, setState] = useState<ConsentState>(DEFAULT_CONSENT)
|
||||
const [decided, setDecided] = useState(false)
|
||||
const [consentId, setConsentId] = useState<string | undefined>(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])
|
||||
// The decision lives in the cookie, read through a store: during the server render and hydration React uses the
|
||||
// server's value (none, or the cookie the server read), then the browser's own before the next paint.
|
||||
const serverRead = opts.cookieValue !== undefined
|
||||
const serverRecord = useMemo(
|
||||
() => (serverRead ? readConsentRecord(opts.cookieValue ?? undefined, version) : null),
|
||||
[serverRead, opts.cookieValue, version],
|
||||
)
|
||||
const record = useSyncExternalStore(
|
||||
subscribeConsent,
|
||||
() => getConsentSnapshot(version),
|
||||
() => serverRecord,
|
||||
)
|
||||
/** False in the server render and while hydrating, true from the first client render on. */
|
||||
const hydrated = useSyncExternalStore(noSubscription, isClient, isServer)
|
||||
// <CookieButton> reopens the banner over a stored decision; the next decision closes it again.
|
||||
const [reopened, setReopened] = useState(false)
|
||||
const state = record?.state ?? DEFAULT_CONSENT
|
||||
const decided = record !== null && !reopened
|
||||
const consentId = record?.id
|
||||
|
||||
const persist = useCallback(
|
||||
(next: ConsentState) => {
|
||||
@@ -104,10 +119,8 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
|
||||
|
||||
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)
|
||||
writeConsentCookie(serializeConsent(next, version, id), `;path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`)
|
||||
setReopened(false)
|
||||
// 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
|
||||
@@ -129,7 +142,7 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
|
||||
persist({ ...DEFAULT_CONSENT, ...choices, necessary: true }),
|
||||
[persist],
|
||||
)
|
||||
const reopen = useCallback(() => setDecided(false), [])
|
||||
const reopen = useCallback(() => setReopened(true), [])
|
||||
|
||||
return { acceptAll, consentId, decided, rejectAll, reopen, savePreferences, state }
|
||||
return { acceptAll, consentId, decided, hydrated, rejectAll, reopen, savePreferences, serverRead, state }
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
'use client'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
/**
|
||||
* Returns true only after the component has mounted on the client. Used to gate
|
||||
* consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /
|
||||
* first paint — preventing the React 19 / Next hydration mismatch that projects
|
||||
* were working around with their own setTimeout-based ConsentWrapper. Built into
|
||||
* the components now, so no project wrapper is needed.
|
||||
*/
|
||||
export function useIsMounted(): boolean {
|
||||
const [mounted, setMounted] = useState(false)
|
||||
useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
return mounted
|
||||
}
|
||||
@@ -23,6 +23,12 @@ export type SiteProvidersProps = {
|
||||
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`equalChoice`, classNames) or `false`. */
|
||||
banner?: false | ReactNode
|
||||
children: ReactNode
|
||||
/**
|
||||
* Optional server read of the consent cookie: `(await cookies()).get(CONSENT_COOKIE)?.value ?? null`. The HTML
|
||||
* then has no banner for a visitor who already decided, and the page becomes dynamic (no static / ISR copy).
|
||||
* Leave out (default) to keep pages static: the banner decides before the first paint with an inline script.
|
||||
*/
|
||||
consentCookie?: null | string
|
||||
/** The "cookie settings" button. Default `<CookieButton />`; your own or `false`. */
|
||||
cookieButton?: false | ReactNode
|
||||
/** Extra cookies per category to delete when consent is withdrawn. */
|
||||
@@ -41,8 +47,9 @@ export type SiteProvidersProps = {
|
||||
logEndpoint?: string
|
||||
/**
|
||||
* CSP nonce for a nonce-based policy (createProxy `csp`): read it in the layout
|
||||
* with `(await headers()).get('x-nonce')`. Goes on the theme script and on the
|
||||
* analytics tags the plugin injects (GTM passes it on to its own tags).
|
||||
* with `(await headers()).get('x-nonce')`. Goes on the theme script, the cookie
|
||||
* banner's first-paint script and the analytics tags the plugin injects (GTM
|
||||
* passes it on to its own tags).
|
||||
*/
|
||||
nonce?: null | string
|
||||
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
|
||||
@@ -82,6 +89,7 @@ export function SiteProviders({
|
||||
analytics,
|
||||
banner,
|
||||
children,
|
||||
consentCookie,
|
||||
cookieButton,
|
||||
cookieMap,
|
||||
jsonLd = [],
|
||||
@@ -98,7 +106,7 @@ export function SiteProviders({
|
||||
{theme ? <ThemeScript {...shell.theme} nonce={nonce ?? undefined} /> : null}
|
||||
{preconnect ? <MediaPreconnect /> : null}
|
||||
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
|
||||
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
|
||||
<ConsentProvider cookieMap={cookieMap} cookieValue={consentCookie} logEndpoint={logEndpoint} nonce={nonce} texts={shell.consent}>
|
||||
<TurnstileProvider siteKey={shell.turnstileSiteKey}>
|
||||
{lightbox ? (
|
||||
<LightboxProvider texts={shell.lightboxTexts} {...(lightbox === true ? {} : lightbox)}>
|
||||
|
||||
Reference in New Issue
Block a user