Owner, 2026-12-01, after the review of fb92b35: option 3, "miejsce pod stopką" — the button stays in its corner at
all times and covers nothing; the page gets room under its last row.
- Removed: the step up at the end of the page (`clear`, COOKIE_BUTTON_CLEAR, stepAbove; never released).
- New: while the button is shown, the last footer (`reserve`, COOKIE_BUTTON_RESERVE; no footer: <body>) gets bottom
padding, measured: button height + offset + safe area + 8 px, minus what is already free under the lowest text or
control in the button's column. The footer's own padding counts (no double space); an empty corner gets nothing.
Not before a decision, not while the banner is open, gone with the button; `reserve={false}` turns it off,
`--ipal-cookie-button-space` on the footer sets the amount (0 = none, per breakpoint).
- No layout shift: on a static page <CookieButton> renders an inline script that makes the room before the first
paint for a visitor who already decided — in a constructed style sheet, so the server's markup is untouched and
React hydrates without a mismatch; after hydration the same function moves it onto the element.
- consentDecidedScript: the shared start of the banner's and the button's pre-paint scripts.
- avoid={COOKIE_BUTTON_AVOID} is still the placement before 1.17.2 (no room then).
Tests: test/cookieButtonPlacement.test.ts rewritten (24); reference e2e on desktop, 390 px and 360 px phones, light
and dark, five pages: the corner at every scroll position, nothing under the button at the very end, every footer
link clickable, layout shift < 0.001, the room before hydration.
Docs: consent.md, AGENT.md, skills, PROGRAMISTA item 83, changelog draft 1.17.2.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
348 lines
16 KiB
TypeScript
348 lines
16 KiB
TypeScript
// @vitest-environment happy-dom
|
||
/**
|
||
* Where <CookieButton> sits (1.17.2): the bottom corner of the window, always. It never moves — not above the
|
||
* footer, not at the end of the page. So that it covers nothing there, the footer gets room under its last row
|
||
* while the button is shown (measured, only what is missing). The placement before 1.17.2 stays available.
|
||
*/
|
||
import { act, createElement, type ReactElement } from 'react'
|
||
import { createRoot, hydrateRoot, type Root } from 'react-dom/client'
|
||
import { renderToString } from 'react-dom/server'
|
||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||
|
||
import { ConsentProvider } from '../src/modules/consent/ConsentContext.js'
|
||
import { resetConsentStore } from '../src/modules/consent/consentStore.js'
|
||
import { COOKIE_BUTTON_AVOID, CookieButton } from '../src/modules/consent/CookieButton.js'
|
||
import { COOKIE_BUTTON_RESERVE, COOKIE_BUTTON_SPACE_ATTRIBUTE, reserveCookieButtonSpace } from '../src/modules/consent/cookieButtonSpace.js'
|
||
import { CONSENT_FALLBACK } from '../src/modules/consent/getConsentTexts.js'
|
||
import { CONSENT_COOKIE, serializeConsent } from '../src/modules/consent/storage.js'
|
||
|
||
const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement
|
||
|
||
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||
|
||
type Box = { bottom: number; left: number; right: number; top: number }
|
||
const box = (top: number, bottom: number, left = 16, right = 60): Box => ({ bottom, left, right, top })
|
||
const rect = (r: Box) => ({ ...r, height: r.bottom - r.top, width: r.right - r.left, x: r.left, y: r.top }) as DOMRect
|
||
/** The button's place in an 800 px high window: 44 px, 16 px from the bottom and the left. Zone to keep free: 68 px. */
|
||
const REST = box(740, 784)
|
||
const ZONE = 800 - 740 + 8
|
||
const NONE = box(0, 0, 0, 0)
|
||
|
||
/** A fake layout: boxes per element, text boxes per element whose text they are, own bottom padding per element. */
|
||
let boxes: Map<Element, Box>
|
||
let page: { height: number; scrollY: number }
|
||
|
||
const place = (el: Element, r: Box) => (boxes.set(el, r), el)
|
||
const add = (html: string, parent: Element = document.body) => {
|
||
const holder = document.createElement('div')
|
||
holder.innerHTML = html
|
||
const el = holder.firstElementChild!
|
||
parent.appendChild(el)
|
||
return el as HTMLElement
|
||
}
|
||
const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1])
|
||
const clearCookies = () => {
|
||
for (const c of document.cookie.split('; ')) {
|
||
if (c.split('=')[0]) {document.cookie = `${c.split('=')[0]}=;path=/;max-age=0`}
|
||
}
|
||
}
|
||
const decide = () => {
|
||
document.cookie = `${CONSENT_COOKIE}=${serializeConsent({ analytics: false, functional: false, marketing: false, necessary: true })};path=/`
|
||
}
|
||
|
||
beforeEach(() => {
|
||
clearCookies()
|
||
resetConsentStore()
|
||
boxes = new Map()
|
||
page = { height: 3000, scrollY: 2200 } // scrolled to the end: the page ends at y = 800, the window's bottom edge
|
||
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
|
||
// the real button, once React has put it in the page
|
||
if (this.getAttribute('data-ipal') === 'cookie-button') {return rect(REST)}
|
||
// the probe that stands in for a button that is not there yet
|
||
if (!boxes.has(this) && (this as HTMLElement).style?.position === 'fixed') {return rect(REST)}
|
||
return rect(boxes.get(this) ?? NONE)
|
||
})
|
||
vi.spyOn(Range.prototype, 'getClientRects').mockImplementation(function (this: Range) {
|
||
const parent = this.startContainer.parentElement
|
||
return [rect((parent && boxes.get(parent)) ?? NONE)] as unknown as DOMRectList
|
||
})
|
||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800)
|
||
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => page.scrollY)
|
||
vi.spyOn(document.documentElement, 'scrollHeight', 'get').mockImplementation(() => page.height)
|
||
})
|
||
|
||
afterEach(() => {
|
||
reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })
|
||
document.body.innerHTML = ''
|
||
document.body.removeAttribute('style')
|
||
vi.restoreAllMocks()
|
||
})
|
||
|
||
/** A footer whose last row (a link) ends `gap` px above the end of the page, in the button's corner or elsewhere. */
|
||
function footer({ gap = 20, left = 30, padding = '' }: { gap?: number; left?: number; padding?: string } = {}) {
|
||
const el = add(`<footer${padding ? ` style="padding-bottom:${padding}"` : ''}><p>© Example</p><a href="/x">Instagram</a></footer>`)
|
||
place(el, box(500, 800, 0, 390))
|
||
place(el.querySelector('p')!, box(700, 720, 200, 380)) // text elsewhere on the row above
|
||
place(el.querySelector('a')!, box(800 - gap - 20, 800 - gap, left, left + 90))
|
||
return el
|
||
}
|
||
const button = () => place(add('<button style="position:fixed">cookies</button>'), REST) as HTMLElement
|
||
const reserve = (options: object = {}) => reserveCookieButtonSpace({ button: button(), selector: COOKIE_BUTTON_RESERVE, side: 'left', ...options })
|
||
|
||
describe('reserveCookieButtonSpace', () => {
|
||
test('a link in the corner, 20 px above the end of the page: the footer gets the 48 px that are missing', () => {
|
||
const el = footer()
|
||
expect(reserve()).toBe(ZONE - 20)
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(true)
|
||
})
|
||
|
||
test("the footer's own bottom padding counts: only the difference is added, and it is put back on release", () => {
|
||
const el = footer({ gap: 32, padding: '32px' })
|
||
expect(reserve()).toBe(ZONE - 32)
|
||
expect(el.style.paddingBottom).toBe('68px') // 32 own + 36
|
||
expect(reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(0)
|
||
expect(el.style.paddingBottom).toBe('32px')
|
||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||
})
|
||
|
||
test('enough room already (a project with a generous footer): nothing is added, nothing is touched', () => {
|
||
const el = footer({ gap: 80, padding: '80px' })
|
||
expect(reserve()).toBe(0)
|
||
expect(el.style.paddingBottom).toBe('80px')
|
||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||
})
|
||
|
||
test('nothing in the corner (the row is on the other side): no room', () => {
|
||
const el = footer({ left: 250 })
|
||
expect(reserve()).toBe(0)
|
||
expect(el.style.paddingBottom).toBe('')
|
||
})
|
||
|
||
test('side="right": the other corner is measured', () => {
|
||
footer({ left: 250 })
|
||
const right = place(add('<button style="position:fixed">cookies</button>'), box(740, 784, 330, 374)) as HTMLElement
|
||
expect(reserveCookieButtonSpace({ button: right, selector: COOKIE_BUTTON_RESERVE, side: 'right' })).toBe(48)
|
||
})
|
||
|
||
test('called again and again (resize, late content): the same room, never added twice', () => {
|
||
const el = footer()
|
||
const b = button()
|
||
for (let i = 0; i < 4; i++) {expect(reserveCookieButtonSpace({ button: b, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(48)}
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
})
|
||
|
||
test('several footers (an article footer first): the last one on the page', () => {
|
||
const article = place(add('<article><footer><a href="/a">author</a></footer></article>').querySelector('footer')!, box(300, 340, 0, 390)) as HTMLElement
|
||
const el = footer()
|
||
reserve()
|
||
expect(article.style.paddingBottom).toBe('')
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
})
|
||
|
||
test('no footer on the page: <body> gets what its own padding does not cover', () => {
|
||
expect(reserve()).toBe(ZONE)
|
||
expect(document.body.style.paddingBottom).toBe('68px')
|
||
reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })
|
||
expect(document.body.style.paddingBottom).toBe('')
|
||
})
|
||
|
||
test('a selector of your own', () => {
|
||
footer()
|
||
const bar = place(add('<div class="legal"><a href="/t">Terms</a></div>'), box(760, 800, 0, 390)) as HTMLElement
|
||
place(bar.querySelector('a')!, box(770, 790, 20, 80))
|
||
expect(reserve({ selector: '.legal' })).toBe(ZONE - 10)
|
||
expect(bar.style.paddingBottom).toBe('58px')
|
||
expect(document.querySelector('footer')!.style.paddingBottom).toBe('')
|
||
})
|
||
|
||
test('--ipal-cookie-button-space: the project sets the amount; 0 = none', () => {
|
||
const el = footer()
|
||
el.style.setProperty('--ipal-cookie-button-space', '5rem')
|
||
reserve()
|
||
expect(el.style.paddingBottom).toBe('calc(0px + 5rem)')
|
||
el.style.setProperty('--ipal-cookie-button-space', '0px')
|
||
expect(reserve()).toBe(0)
|
||
expect(el.style.paddingBottom).toBe('')
|
||
el.style.setProperty('--ipal-cookie-button-space', '0')
|
||
expect(reserve()).toBe(0)
|
||
})
|
||
|
||
test('a button the project placed in the flow (not fixed) covers nothing: no room', () => {
|
||
const el = footer()
|
||
const inFlow = place(add('<button>cookies</button>'), REST) as HTMLElement
|
||
expect(reserveCookieButtonSpace({ button: inFlow, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(0)
|
||
expect(el.style.paddingBottom).toBe('')
|
||
})
|
||
|
||
test('before the button exists: the default button is measured with a probe that leaves no trace', () => {
|
||
const el = footer()
|
||
const nodes = document.body.childElementCount
|
||
expect(reserveCookieButtonSpace({ selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(48)
|
||
expect(document.body.childElementCount).toBe(nodes)
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
})
|
||
|
||
test('sheet mode (before hydration): the element is not touched; the next plain call moves the room onto it', () => {
|
||
const wrap = add('<div><span>x</span></div>')
|
||
const el = footer()
|
||
wrap.appendChild(el)
|
||
expect(reserveCookieButtonSpace({ selector: COOKIE_BUTTON_RESERVE, sheet: true, side: 'left' })).toBe(48)
|
||
expect(el.getAttribute('style')).toBeNull()
|
||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||
expect(document.adoptedStyleSheets).toHaveLength(1)
|
||
expect(document.adoptedStyleSheets[0].cssRules[0].cssText.replace(/\s+/g, ' ')).toMatch(/^body > div:nth-child\(\d+\) > footer:nth-child\(2\) ?\{ ?padding-bottom: 48px !important;? ?\}$/)
|
||
reserve()
|
||
expect(document.adoptedStyleSheets).toHaveLength(0)
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
})
|
||
})
|
||
|
||
describe('<CookieButton>', () => {
|
||
let container: HTMLDivElement
|
||
let root: Root | undefined
|
||
let errors: ReturnType<typeof vi.spyOn>
|
||
|
||
const cookieButton = () => document.querySelector<HTMLButtonElement>('[data-ipal="cookie-button"]')
|
||
const frame = () => act(() => new Promise((resolve) => setTimeout(resolve, 40)))
|
||
const tree = (props: object = {}, provider: object = {}) => h(ConsentProvider, { texts: CONSENT_FALLBACK, ...provider }, h(CookieButton, props))
|
||
const mount = async (props: object = {}) => {
|
||
act(() => {
|
||
root = createRoot(container)
|
||
root.render(tree(props))
|
||
})
|
||
await frame()
|
||
}
|
||
|
||
beforeEach(() => {
|
||
container = document.createElement('div')
|
||
document.body.appendChild(container)
|
||
errors = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||
})
|
||
|
||
afterEach(() => {
|
||
if (root) {act(() => root!.unmount())}
|
||
root = undefined
|
||
})
|
||
|
||
test('default: fixed in the bottom corner with the safe-area insets, below dialogs, a labelled button', async () => {
|
||
decide()
|
||
await mount()
|
||
const style = cookieButton()!.style
|
||
expect(style.position).toBe('fixed')
|
||
expect(style.bottom).toBe('calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))')
|
||
expect(style.left).toBe('calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-left, 0px))')
|
||
expect(style.zIndex).toBe('var(--ipal-z-header, 40)')
|
||
expect(cookieButton()!.getAttribute('aria-label')).toBe(CONSENT_FALLBACK.settingsTitle)
|
||
expect(cookieButton()!.type).toBe('button')
|
||
})
|
||
|
||
test('it never moves: footer in view, scrolling, the end of the page with a link under it', async () => {
|
||
decide()
|
||
footer()
|
||
await mount()
|
||
for (const y of [0, 1000, 2200]) {
|
||
page.scrollY = y
|
||
window.dispatchEvent(new Event('scroll'))
|
||
window.dispatchEvent(new Event('resize'))
|
||
await frame()
|
||
expect(cookieButton()!.style.transform).toBe('')
|
||
}
|
||
})
|
||
|
||
test('the room is there while the button is shown, and goes when the banner is reopened or the button unmounts', async () => {
|
||
decide()
|
||
const el = footer()
|
||
await mount()
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
act(() => cookieButton()!.click()) // reopens the banner: no button, no room
|
||
expect(cookieButton()).toBeNull()
|
||
expect(el.style.paddingBottom).toBe('')
|
||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||
})
|
||
|
||
test('no decision yet: no button, no room', async () => {
|
||
const el = footer()
|
||
await mount()
|
||
expect(cookieButton()).toBeNull()
|
||
expect(el.style.paddingBottom).toBe('')
|
||
expect(liveCookies()).toEqual([])
|
||
})
|
||
|
||
test('reserve={false}: the button, no room', async () => {
|
||
decide()
|
||
const el = footer()
|
||
await mount({ reserve: false })
|
||
expect(cookieButton()).not.toBeNull()
|
||
expect(el.style.paddingBottom).toBe('')
|
||
})
|
||
|
||
test('avoid={COOKIE_BUTTON_AVOID}: the placement before 1.17.2 — above the footer, and no room', async () => {
|
||
decide()
|
||
const el = footer()
|
||
await mount({ avoid: COOKIE_BUTTON_AVOID })
|
||
expect(cookieButton()!.style.transform).toBe('translateY(-300px)')
|
||
expect(el.style.paddingBottom).toBe('')
|
||
})
|
||
|
||
test('avoid={false} (sites that set it): stays in the corner, with the room', async () => {
|
||
decide()
|
||
const el = footer()
|
||
await mount({ avoid: false })
|
||
expect(cookieButton()!.style.transform).toBe('')
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
})
|
||
|
||
describe('before the first paint (static HTML, the same for every visitor)', () => {
|
||
const scriptOf = (html: string) => /<script[^>]*data-ipal="cookie-button-script"[^>]*>(?<code>.*?)<\/script>/s.exec(html)?.groups?.code
|
||
|
||
test('the server HTML carries a script instead of the button; nonce from the provider', () => {
|
||
const html = renderToString(tree({}, { nonce: 'n-1' }))
|
||
expect(html).not.toContain('data-ipal="cookie-button"')
|
||
expect(html).toMatch(/<script[^>]*nonce="n-1"/)
|
||
expect(scriptOf(html)).toContain('footer, [role=\\"contentinfo\\"]')
|
||
expect(scriptOf(html)).not.toContain('</script')
|
||
})
|
||
|
||
test('no script when there is nothing to prepare: reserve off, old placement, own classes, server-read cookie', () => {
|
||
for (const props of [{ reserve: false }, { avoid: COOKIE_BUTTON_AVOID }, { className: 'mine' }]) {
|
||
expect(renderToString(tree(props))).not.toContain('<script')
|
||
}
|
||
expect(renderToString(tree({}, { cookieValue: null }))).not.toContain('<script')
|
||
})
|
||
|
||
test('a visitor who decided: the room is made by the script, the markup stays as the server sent it; no decision: nothing', () => {
|
||
const html = renderToString(tree())
|
||
const el = footer()
|
||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||
new Function(scriptOf(html)!)()
|
||
expect(document.adoptedStyleSheets).toHaveLength(0)
|
||
decide()
|
||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||
new Function(scriptOf(html)!)()
|
||
expect(document.adoptedStyleSheets).toHaveLength(1)
|
||
expect(document.adoptedStyleSheets[0].cssRules[0].cssText).toContain('48px')
|
||
expect(el.getAttribute('style')).toBeNull()
|
||
})
|
||
|
||
test('hydration: no warning; the room moves from the script’s style sheet onto the footer, the same size', async () => {
|
||
const el = footer()
|
||
decide()
|
||
const node = tree()
|
||
const html = renderToString(node)
|
||
container.innerHTML = html
|
||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||
new Function(scriptOf(html)!)()
|
||
act(() => {
|
||
root = hydrateRoot(container, node)
|
||
})
|
||
await frame()
|
||
expect(errors).not.toHaveBeenCalled()
|
||
expect(cookieButton()).not.toBeNull()
|
||
expect(document.querySelector('[data-ipal="cookie-button-script"]')).toBeNull()
|
||
expect(document.adoptedStyleSheets).toHaveLength(0)
|
||
expect(el.style.paddingBottom).toBe('48px')
|
||
})
|
||
})
|
||
})
|