// @vitest-environment happy-dom /** * Where sits (1.18.0): 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.18.0 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 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(`

© Example

Instagram`) 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(''), 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(''), 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('').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: 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(''), 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(''), 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('
x
') 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('', () => { let container: HTMLDivElement let root: Root | undefined let errors: ReturnType const cookieButton = () => document.querySelector('[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.18.0 — 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) => /]*data-ipal="cookie-button-script"[^>]*>(?.*?)<\/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(/]*nonce="n-1"/) expect(scriptOf(html)).toContain('footer, [role=\\"contentinfo\\"]') expect(scriptOf(html)).not.toContain(' { for (const props of [{ reserve: false }, { avoid: COOKIE_BUTTON_AVOID }, { className: 'mine' }]) { expect(renderToString(tree(props))).not.toContain(' { 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') }) }) })