Merge claude/cookie-button-bottom: the cookie button never moves; the footer keeps room under its last row (owner's option 3)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 12:08:57 +01:00
co-authored by Claude Opus 5.5
20 changed files with 763 additions and 321 deletions
+4 -3
View File
@@ -24,16 +24,17 @@ export {
ConsentProvider,
ConsentScript,
COOKIE_BUTTON_AVOID,
COOKIE_BUTTON_CLEAR,
COOKIE_BUTTON_RESERVE,
COOKIE_BUTTON_SPACE_ATTRIBUTE,
CookieBanner,
CookieButton,
readEffectiveConsent,
reserveCookieButtonSpace,
signalVendors,
stepAbove,
useConsent,
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieButtonProps, CookieSettingsAction } from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieButtonProps, CookieButtonSpaceOptions, CookieSettingsAction } from '../modules/consent/client.js'
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
+1
View File
@@ -118,6 +118,7 @@ export {
CONSENT_VERSION,
consentBannerScript,
consentCategoryOptions,
consentDecidedScript,
consentFallback,
DEFAULT_CONSENT,
getConsentTexts,
+76 -76
View File
@@ -2,9 +2,11 @@
import type { CSSProperties } from 'react'
import { Cookie } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useConsentContext } from './ConsentContext.js'
import { COOKIE_BUTTON_RESERVE, cookieButtonSpaceScript, reserveCookieButtonSpace } from './cookieButtonSpace.js'
import { consentDecidedScript } from './firstPaint.js'
/**
* The site footer: the selector of the placement before 1.17.2, when the button moved up by the visible part of
@@ -12,24 +14,23 @@ import { useConsentContext } from './ConsentContext.js'
*/
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
/** Controls the button never stays on top of once the page cannot be scrolled any further. */
export const COOKIE_BUTTON_CLEAR = 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"]'
export type CookieButtonProps = {
/**
* Placement before 1.17.2: a CSS selector of elements the button lifts above while they are on screen
* (`COOKIE_BUTTON_AVOID` = the site footer). Default: none — the button stays in the bottom corner of the
* window. `false` = never move at all (also turns `clear` off).
* (`COOKIE_BUTTON_AVOID` = the site footer; no room is reserved then). Default: none — the button stays in the
* bottom corner of the window and never moves. `false` = the same as the default (kept for sites that set it).
*/
avoid?: false | string
/** Replaces the default classes (look and position). The lift above `avoid` and the step of `clear` still apply. */
/** Replaces the default classes (look and position). The lift above `avoid` still applies. */
className?: string
/**
* CSS selector of controls the button must not keep covered. Only at the very end of the page (where a visitor
* cannot scroll a covered link out from under it) the button steps up just far enough to free them. Default
* `COOKIE_BUTTON_CLEAR` (links, buttons, form fields). `false` = stay in the corner whatever is under it.
* Room for the button at the end of the page, so the footer's last row ends above it and nothing stays covered:
* a CSS selector of the block that gets the bottom padding (the last match; default `COOKIE_BUTTON_RESERVE`, the
* footer; no match: `<body>`). Only while the button is shown, only as much as is missing (the block's own
* bottom padding counts, an empty corner needs none). `false` = no room. A fixed amount instead of the measured
* one: `--ipal-cookie-button-space` on that block (`0` = none, also per breakpoint).
*/
clear?: false | string
reserve?: false | string
/** Corner. Default 'left'. */
side?: 'left' | 'right'
}
@@ -39,24 +40,42 @@ export type CookieButtonProps = {
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
* Hidden while the banner is showing.
*
* Placement (1.17.2): fixed in the bottom corner of the window, on every page and at every scroll position — it
* does not climb above the footer any more. At the very end of the page, if it would lie on a link or a button
* there (a footer link in that corner), it steps up just above it, so nothing stays unreachable. The placement
* before 1.17.2 (riding on the footer's top edge): `avoid={COOKIE_BUTTON_AVOID}`.
* Placement (1.17.2): fixed in the bottom corner of the window, on every page and at every scroll position. It
* never moves — it does not climb above the footer any more. So that it covers nothing at the very end of a page,
* the footer gets room under its last row while the button is shown (`reserve`, cookieButtonSpace.ts). The
* placement before 1.17.2 (riding on the footer's top edge): `avoid={COOKIE_BUTTON_AVOID}`.
*
* Colours follow the same design tokens as CookieBanner (--ipal-surface,
* --ipal-border, --ipal-hover, --ipal-text). Position: --ipal-cookie-button-offset
* (distance from the bottom, default 1rem), --ipal-cookie-button-inset (from the
* side, default 1rem), both plus the device's safe-area inset; z-index --ipal-z-header (below the banner and dialogs).
*/
export function CookieButton({ avoid, className, clear = COOKIE_BUTTON_CLEAR, side = 'left' }: CookieButtonProps = {}) {
const { decided, reopen, texts } = useConsentContext()
export function CookieButton({ avoid, className, reserve = COOKIE_BUTTON_RESERVE, side = 'left' }: CookieButtonProps = {}) {
const { decided, gpcMode, hydrated, nonce, reopen, serverRead, texts } = useConsentContext()
const buttonRef = useRef<HTMLButtonElement>(null)
const lift = useLift({ active: decided, avoid: avoid ?? false, buttonRef, clear: avoid === undefined ? clear : false })
const lift = useLiftAbove(avoid ?? false, decided)
// the old placement keeps the button off the footer by itself
const room = avoid ? false : reserve
useReservedSpace({ active: decided, buttonRef, selector: room, side })
// `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}
if (!decided) {
// Static HTML, the same for every visitor: for one who already decided, the room is made before the first
// paint, so nothing shifts when the button appears with hydration. Only in the server HTML (a script React
// creates in the browser never runs); a button with classes of its own is measured once it is there.
if (hydrated || serverRead || !room || className) {return null}
return (
<script
dangerouslySetInnerHTML={{
__html: cookieButtonSpaceScript({ decided: consentDecidedScript({ gpc: gpcMode, version: texts.version }), selector: room, side }),
}}
data-ipal="cookie-button-script"
nonce={nonce}
suppressHydrationWarning
/>
)
}
const cls =
className ??
@@ -98,67 +117,16 @@ export function bottomOverlap(tops: number[], viewportHeight: number): number {
return Math.max(0, Math.min(viewportHeight - top, viewportHeight - 96))
}
type Box = { bottom: number; left: number; right: number; top: number }
/** Space kept between the button and a control it stepped above. */
const CLEAR_GAP = 8
/**
* How far the button must move up so that it lies on none of `obstacles` (boxes in viewport pixels; `button` is the
* button's box in its resting place). 0 when nothing is under it — and 0 when no free place exists within `max`:
* better in its corner than wandering over the page.
*/
export function stepAbove(button: Box, obstacles: Box[], max: number): number {
let lift = 0
// each pass clears the lowest control still under the button; a control is passed at most once
for (let pass = 0; pass <= obstacles.length; pass++) {
const top = button.top - lift
const bottom = button.bottom - lift
const hit = obstacles.filter((o) => o.right > button.left && o.left < button.right && o.bottom > top && o.top < bottom)
if (!hit.length) {return lift}
lift = button.bottom - Math.min(...hit.map((o) => o.top)) + CLEAR_GAP
if (lift > max) {return 0}
}
return 0
}
type LiftOptions = {
active: boolean
avoid: false | string
buttonRef: { current: HTMLButtonElement | null }
clear: false | string
}
function useLift({ active, avoid, buttonRef, clear }: LiftOptions): number {
function useLiftAbove(selector: false | string, active: boolean): number {
const [lift, setLift] = useState(0)
const applied = useRef(0)
const frame = useRef(0)
useEffect(() => {
if (!active || (!avoid && !clear)) {return}
const set = (value: number) => {
applied.current = value
setLift(value)
}
if (!selector || !active) {return}
const measure = () => {
cancelAnimationFrame(frame.current)
frame.current = requestAnimationFrame(() => {
if (avoid) {
const tops = [...document.querySelectorAll(avoid)].map((el) => el.getBoundingClientRect().top)
return set(bottomOverlap(tops, window.innerHeight))
}
const button = buttonRef.current
const page = document.documentElement
// Anywhere else a covered control is one scroll away; at the end of the page it would stay covered.
const atEnd = window.innerHeight + window.scrollY >= page.scrollHeight - 2
if (!button || !clear || !atEnd || getComputedStyle(button).position !== 'fixed') {return set(0)}
const now = button.getBoundingClientRect()
// the resting place: the measured box without the step the button has already taken
const rest = { bottom: now.bottom + applied.current, left: now.left, right: now.right, top: now.top + applied.current }
const obstacles = [...document.querySelectorAll(clear)]
.filter((el) => el !== button && !button.contains(el))
.map((el) => el.getBoundingClientRect())
.filter((box) => box.width > 0 && box.height > 0)
set(stepAbove(rest, obstacles, window.innerHeight / 2))
const tops = [...document.querySelectorAll(selector)].map((el) => el.getBoundingClientRect().top)
setLift(bottomOverlap(tops, window.innerHeight))
})
}
measure()
@@ -172,6 +140,38 @@ function useLift({ active, avoid, buttonRef, clear }: LiftOptions): number {
window.removeEventListener('resize', measure)
observer?.disconnect()
}
}, [active, avoid, buttonRef, clear])
return active && (avoid || clear) ? lift : 0
}, [selector, active])
return selector && active ? lift : 0
}
type ReservedSpaceOptions = {
active: boolean
buttonRef: { current: HTMLButtonElement | null }
selector: false | string
side: 'left' | 'right'
}
/** Keeps the room for the button while it is shown; takes it away when the button goes (banner reopened, unmount). */
function useReservedSpace({ active, buttonRef, selector, side }: ReservedSpaceOptions): void {
// before the browser paints the button: the room is there in the same frame (and already is, after the inline script)
useLayoutEffect(() => {
if (!active || !selector) {return}
let frame = 0
const apply = () => reserveCookieButtonSpace({ button: buttonRef.current, selector, side })
const later = () => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(apply)
}
apply()
window.addEventListener('resize', later)
// fonts, images, content that loads later: the footer's last row may end somewhere else
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(later)
observer?.observe(document.body)
return () => {
cancelAnimationFrame(frame)
window.removeEventListener('resize', later)
observer?.disconnect()
reserveCookieButtonSpace({ release: true, selector, side })
}
}, [active, buttonRef, selector, side])
}
+3 -1
View File
@@ -4,8 +4,10 @@ export { ConsentScript } from './ConsentScript.js'
export { readEffectiveConsent } from './consentStore.js'
export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
export { bottomOverlap, COOKIE_BUTTON_AVOID, COOKIE_BUTTON_CLEAR, CookieButton, stepAbove } from './CookieButton.js'
export { bottomOverlap, COOKIE_BUTTON_AVOID, CookieButton } from './CookieButton.js'
export type { CookieButtonProps } from './CookieButton.js'
export { COOKIE_BUTTON_RESERVE, COOKIE_BUTTON_SPACE_ATTRIBUTE, reserveCookieButtonSpace } from './cookieButtonSpace.js'
export type { CookieButtonSpaceOptions } from './cookieButtonSpace.js'
// Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
export type { ConsentCookieMap } from './useConsent.js'
+171
View File
@@ -0,0 +1,171 @@
/**
* Room for the cookie button at the end of the page (1.17.2).
*
* The button is fixed in the bottom corner of the window and never moves. At the very end of a page whatever is in
* that corner — usually the footer's last row — would stay under it for good. So while the button is shown, the
* page's last block (`reserve`, default the footer) gets just enough bottom padding for its content to end above the
* button. Measured, not guessed: only what lies in the button's column counts, the block's own bottom padding is
* used first, and a page with nothing in that corner gets nothing.
*
* NO IMPORTS, NO OUTER NAMES in `reserveCookieButtonSpace`: <CookieButton> also puts the function's own source into
* an inline script (`cookieButtonSpaceScript`), so that a returning visitor's page has the room before the first
* paint and nothing shifts when the button appears.
*/
/** Attribute on the block that carries the room: its inline `padding-bottom` from before (may be empty). */
export const COOKIE_BUTTON_SPACE_ATTRIBUTE = 'data-ipal-cookie-space'
/** The block that gets the room: the last one on the page that matches (the site footer). No match: `<body>`. */
export const COOKIE_BUTTON_RESERVE = 'footer, [role="contentinfo"]'
export type CookieButtonSpaceOptions = {
/** The button, when it is on the page. Without it the default button's box is measured with a probe. */
button?: HTMLElement | null
/** `true` takes the room away (the button is gone or the banner is open). */
release?: boolean
/** CSS selector of the block that gets the room. */
selector: string
/**
* Before hydration: put the padding in a constructed style sheet instead of on the element, so React finds the
* server's markup untouched (no hydration warning). The next call without it moves the room onto the element.
*/
sheet?: boolean
/** The button's corner. */
side: 'left' | 'right'
}
/**
* Gives the page's last block the room the button needs, or takes it away. Returns the pixels added (0 = none).
* Safe to call again and again: it measures the block without its own addition each time.
*/
export function reserveCookieButtonSpace(options: CookieButtonSpaceOptions): number {
const ATTRIBUTE = 'data-ipal-cookie-space'
const GAP = 8
const SHEET = '__iaplCookieSpaceSheet'
const doc = document
const store = window as unknown as Record<string, CSSStyleSheet | undefined>
let i: number
// put back what an earlier call changed — every measurement starts from the page as the project made it
const marked = doc.querySelectorAll('[' + ATTRIBUTE + ']')
for (i = 0; i < marked.length; i++) {
const was = marked[i] as HTMLElement
was.style.paddingBottom = was.getAttribute(ATTRIBUTE) || ''
was.removeAttribute(ATTRIBUTE)
}
const before = store[SHEET]
if (before) {
doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(function (sheet) {return sheet !== before})
store[SHEET] = undefined
}
if (options.release || !doc.body) {return 0}
const found = doc.querySelectorAll(options.selector)
let target: HTMLElement = doc.body
for (i = found.length - 1; i >= 0; i--) {
if ((found[i] as HTMLElement).getBoundingClientRect().height > 0) {
target = found[i] as HTMLElement
break
}
}
// the button's box; before the button exists, a probe with the default button's size and place
let button = options.button || null
let probe: HTMLElement | null = null
if (!button) {
probe = doc.createElement('div')
probe.style.cssText =
'position:fixed;visibility:hidden;pointer-events:none;width:2.75rem;height:2.75rem;' +
'bottom:calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px));' +
options.side + ':calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-' + options.side + ', 0px))'
doc.body.appendChild(probe)
button = probe
}
const fixed = getComputedStyle(button).position === 'fixed'
const box = button.getBoundingClientRect()
if (probe) {doc.body.removeChild(probe)}
// a button the project placed in the flow (className) covers nothing at the end of the page
if (!fixed || box.height <= 0) {return 0}
const style = getComputedStyle(target)
const own = parseFloat(style.paddingBottom) || 0
const give = function (value: string): boolean {
if (!options.sheet) {
target.setAttribute(ATTRIBUTE, target.style.paddingBottom)
target.style.paddingBottom = value
return true
}
if (typeof CSSStyleSheet !== 'function' || !('adoptedStyleSheets' in doc)) {return false}
// the one element, without marking it: its path from <body>
let path = ''
for (let el: Element | null = target; el && el !== doc.body; el = el.parentElement) {
let nth = 1
for (let prev = el.previousElementSibling; prev; prev = prev.previousElementSibling) {nth++}
path = ' > ' + el.tagName.toLowerCase() + ':nth-child(' + nth + ')' + path
}
const sheet = new CSSStyleSheet()
sheet.replaceSync('body' + path + '{padding-bottom:' + value + ' !important}')
doc.adoptedStyleSheets = doc.adoptedStyleSheets.concat(sheet)
store[SHEET] = sheet
return true
}
// a project's own amount: --ipal-cookie-button-space (any length; 0 = none on this breakpoint)
const token = style.getPropertyValue('--ipal-cookie-button-space').replace(/^\s+|\s+$/g, '')
if (token) {
if (/^[+-]?(?:0+(?:\.0+)?|\.0+)[a-z%]*$/i.test(token)) {return 0}
if (!give('calc(' + own + 'px + ' + token + ')')) {return 0}
return Math.max(0, (parseFloat(getComputedStyle(target).paddingBottom) || 0) - own)
}
// from the window's bottom edge up to the button's top, plus a gap: what must be free at the end of the page
const zone = window.innerHeight - box.top + GAP
let free: number
if (target === doc.body) {
free = own
} else {
// the lowest thing in the button's column: text and replaced elements, by their real boxes
let lowest = -Infinity
const note = function (rects: ArrayLike<{ bottom: number; height: number; left: number; right: number; width: number }>) {
for (let k = 0; k < rects.length; k++) {
const r = rects[k]
if (r.width > 0 && r.height > 0 && r.right > box.left - GAP && r.left < box.right + GAP && r.bottom > lowest) {lowest = r.bottom}
}
}
const walker = doc.createTreeWalker(target, 4) // NodeFilter.SHOW_TEXT
const range = doc.createRange()
let node = walker.nextNode()
while (node) {
if (/\S/.test(node.nodeValue || '')) {
range.selectNodeContents(node)
note(range.getClientRects())
}
node = walker.nextNode()
}
const solid = target.querySelectorAll('img, svg, video, canvas, iframe, input, select, textarea, button')
for (i = 0; i < solid.length; i++) {note([solid[i].getBoundingClientRect()])}
if (lowest === -Infinity) {return 0}
// where the page ends, in the same (window) coordinates
free = doc.documentElement.scrollHeight - window.scrollY - lowest
}
const extra = Math.ceil(Math.min(zone, zone - free))
if (extra <= 0) {return 0}
return give(own + extra + 'px') ? extra : 0
}
export type CookieButtonSpaceScriptOptions = {
/** JavaScript that leaves `true` in a variable `d` when the visitor has a current decision (consentDecidedScript). */
decided: string
selector: string
side: 'left' | 'right'
}
/**
* Inline script for the server HTML of a static page: for a visitor who already decided (the button will appear
* after hydration) the room is there before the first paint. Nothing happens for a visitor who has not.
*/
export function cookieButtonSpaceScript({ decided, selector, side }: CookieButtonSpaceScriptOptions): string {
const options = JSON.stringify({ selector, sheet: true, side: side === 'right' ? 'right' : 'left' })
.replace(/</g, '\\u003c')
.split(String.fromCharCode(0x2028)).join('\\u2028')
.split(String.fromCharCode(0x2029)).join('\\u2029')
return `(function(){try{${decided}if(d){(${reserveCookieButtonSpace.toString()})(${options})}}catch(e){}})()`
}
+14 -3
View File
@@ -37,7 +37,12 @@ export type ConsentBannerScriptOptions = {
* 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, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
/**
* JavaScript statements that leave `true` in a variable `d` when this browser holds a current decision (or sends
* Global Privacy Control under `gpc: 'honour'`), decided exactly as readConsentRecord / resolveConsent do. The shared
* start of the inline scripts that act before the first paint (the banner's, the cookie button's room).
*/
export function consentDecidedScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
// JSON string literal, safe inside <script>: no `</script>`, no line separators
const name = JSON.stringify(`${cookieName}=`)
.replace(/</g, '\\u003c')
@@ -45,11 +50,17 @@ export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour
.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}}` +
// Global Privacy Control honoured: no banner, the same decision React makes (resolveConsent)
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '') +
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '')
)
}
export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
return (
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
consentDecidedScript({ cookieName, gpc, version }) +
`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}` +
+1 -1
View File
@@ -11,7 +11,7 @@ export type { ConsentCategory, ConsentState } from './categories.js'
export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js'
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_MAX_BYTES, CONSENT_LOG_PATH, CONSENT_LOG_SLUG, readCappedBody } from './consentLog.js'
export type { ConsentLogOptions } from './consentLog.js'
export { consentBannerScript } from './firstPaint.js'
export { consentBannerScript, consentDecidedScript } 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'