Files
ipal-kit/src/modules/consent/CookieButton.tsx
T
Radosław SmolińskiandClaude Fable 5.2 1025446a28 Cookie button stays in the bottom corner of the window; it no longer climbs above the footer
Owner, 2026-12-01: by default the cookie button should go to the bottom of the page, not to the footer.
Until now the button (fixed, a child of <body>) moved up by the visible part of the footer: on a phone with a tall
footer it ended at the top of the screen over the header, on a short page in the middle of it.

- Default: fixed in the bottom corner on every page and scroll position; safe-area inset also on the side.
- Only at the very end of the page it steps just above a link, button or form field it would keep covered
  (`clear`, COOKIE_BUTTON_CLEAR, stepAbove); a transform, no layout shift.
- The placement before: avoid={COOKIE_BUTTON_AVOID}; avoid={false} still means never move; className as before.

Tests: test/cookieButtonPlacement.test.ts; reference e2e on desktop and phone (corner on long and short pages,
no covered control at the page end, no layout shift, keyboard reopen).
Docs: consent.md "Where the cookie button sits", AGENT.md, skills, PROGRAMISTA item 83, changelog draft 1.17.2.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-12-01 10:49:23 +01:00

178 lines
8.1 KiB
TypeScript

'use client'
import type { CSSProperties } from 'react'
import { Cookie } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useConsentContext } from './ConsentContext.js'
/**
* The site footer: the selector of the placement before 1.17.2, when the button moved up by the visible part of
* the footer. `<CookieButton avoid={COOKIE_BUTTON_AVOID} />` brings that placement back.
*/
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).
*/
avoid?: false | string
/** Replaces the default classes (look and position). The lift above `avoid` and the step of `clear` still apply. */
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.
*/
clear?: false | string
/** Corner. Default 'left'. */
side?: 'left' | 'right'
}
/**
* Floating "cookie settings" button — lets visitors reopen the consent panel
* 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}`.
*
* 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()
const buttonRef = useRef<HTMLButtonElement>(null)
const lift = useLift({ active: decided, avoid: avoid ?? false, buttonRef, clear: avoid === undefined ? clear : false })
// `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 =
className ??
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] ' +
'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))] border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]'
const position: CSSProperties = className
? {}
: {
bottom: 'calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))',
position: 'fixed',
[side]: `calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-${side}, 0px))`,
zIndex: 'var(--ipal-z-header, 40)' as unknown as number,
}
return (
<button
// a11y label per locale: the panel's "settings title" (Cookie Settings global)
aria-label={texts.settingsTitle}
className={cls}
data-ipal="cookie-button"
onClick={reopen}
ref={buttonRef}
style={{ ...position, ...(lift ? { transform: `translateY(-${lift}px)` } : {}) }}
type="button"
>
<Cookie
aria-hidden="true"
className="h-5 w-5 text-[var(--ipal-text,light-dark(#525252,var(--ipal-text-dark,#d4d4d4)))]"
/>
</button>
)
}
/** Pixels of the `avoid` elements visible at the bottom of the viewport (0 when none). */
export function bottomOverlap(tops: number[], viewportHeight: number): number {
const top = Math.min(...tops, viewportHeight)
// Never push the button off the top of the screen.
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 {
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)
}
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))
})
}
measure()
window.addEventListener('scroll', measure, { passive: true })
window.addEventListener('resize', measure)
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure)
observer?.observe(document.body)
return () => {
cancelAnimationFrame(frame.current)
window.removeEventListener('scroll', measure)
window.removeEventListener('resize', measure)
observer?.disconnect()
}
}, [active, avoid, buttonRef, clear])
return active && (avoid || clear) ? lift : 0
}