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
+18 -13
View File
@@ -43,21 +43,26 @@ once there are more than 20.
Payload's `payload-locked-documents`.
### Changed
- **What an existing site's visitors see: the "cookie settings" button stays in the bottom corner of the window**
([consent.md → Where the cookie button sits](./consent.md#where-the-cookie-button-sits-1172)). Until now it 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. Now it is in the same corner on every page and at every scroll
position. Only at the very end of the page, where it would keep a footer link or a button covered with no way to
scroll past, it steps up just above it (on the reference site: 71 px on a phone, nothing on desktop). No layout
shift, same look, keyboard and screen-reader access unchanged; the side inset now adds the device's safe-area inset.
**Nothing to do; an existing site gets it by updating.** The placement before:
`<CookieButton avoid={COOKIE_BUTTON_AVOID} />` (on `SiteProviders`: `cookieButton={…}`). A site that already passes
`avoid` (a selector, or `false` = never move) or `className` keeps its behaviour. A project e2e test that expects the
button above the footer needs an update.
- **What an existing site's visitors see: the "cookie settings" button stays in the bottom corner of the window and
never moves; the footer is a little taller while it is shown**
([consent.md → Where the cookie button sits](./consent.md#where-the-cookie-button-sits-1172)). Until now the button
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. Now it is in the same corner on every page and at every scroll
position. So that it covers nothing at the very end of a page, the footer gets bottom padding while the button is
shown — just enough for its last row to end above the button (measured: the footer's own padding counts, an empty
corner gets nothing; on the reference site 42–43 px on phones and desktop). Not before a decision, not while the
banner is open. No layout shift: for a returning visitor the room is made before the first paint. Same look,
keyboard and screen-reader access unchanged; the side inset now adds the device's safe-area inset.
**Nothing to do; an existing site gets it by updating.** No room: `<CookieButton reserve={false} />`; an amount of
your own: `--ipal-cookie-button-space` on the footer (`0` = none, also per breakpoint); the placement before:
`<CookieButton avoid={COOKIE_BUTTON_AVOID} />` (on `SiteProviders`: `cookieButton={…}`). A site that passes a
selector in `avoid` keeps its behaviour. A project e2e test that expects the button above the footer, or an exact
footer height after a decision, needs an update.
### Added
- `CookieButton` prop `clear` (selector of controls freed at the end of the page; `false` = off), `COOKIE_BUTTON_CLEAR`,
`stepAbove` (`/client`).
- `CookieButton` prop `reserve` (the block that gets the room; `false` = off); `COOKIE_BUTTON_RESERVE`,
`COOKIE_BUTTON_SPACE_ATTRIBUTE`, `reserveCookieButtonSpace` (`/client`, type `CookieButtonSpaceOptions`);
`consentDecidedScript` (root); the token `--ipal-cookie-button-space`.
## 1.17.1 — security fixes from the IAWL review; the panel's sign-in look; the sending method is chosen
+1 -1
View File
@@ -1167,7 +1167,7 @@ project → **plugin gap**, not a copy.
|---|---|---|
| Banner, settings, cookie button | `<SiteProviders banner={<CookieBanner …/>}>`, `CookieButton`, `useConsent` | consent.md |
| Compliance defaults (1.17.0): Global Privacy Control honoured (no banner, no tracker request, opt-in from the cookie button wins), "Reject" like "Accept all", consent log on, withdrawal tells Meta / TikTok / Clarity and clears listed storage keys | built in; opt-outs: `SiteProviders gpc="ask"` / `gpc={false}`, `CookieBanner equalChoice={false}`, `iapl({ consentLog: false })` / `logEndpoint={false}`, `maxAgeDays` (re-ask, default 180); building blocks `resolveConsent`, `gpcFromHeaders`, `gpcFromNavigator`, `GPC_CATEGORIES`, `GPC_HEADER`, `CONSENT_LOG_PATH`, `gpcWellKnown` (`/.well-known/gpc.json`), `readEffectiveConsent`, `signalVendors`, `clarityConsent` (`/client`). Check: `iapl-consent-check` (5 runs incl. GPC, equal prominence, withdrawal), `iapl-doctor` (`consent-banner`, `consent-log-migration`) | consent.md → "Compliance defaults", consent-behaviour-spec.md |
| Cookie button placement | built in: bottom corner of the window on every page, never in or above the footer; at the page end it steps above a link it would keep covered. `CookieButton side` / `clear` / `avoid` (`avoid={COOKIE_BUTTON_AVOID}` = above the footer, as before 1.17.2; `false` = never move), tokens `--ipal-cookie-button-offset` / `-inset`. Do not render the button inside the footer or write a scroll handler for it | consent.md → "Where the cookie button sits" |
| Cookie button placement | built in: bottom corner of the window on every page, never moves, never in or above the footer; the footer gets room under its last row while the button is shown, so nothing is covered at the page end. `CookieButton side` / `reserve` (`false` = no room) / `avoid` (`avoid={COOKIE_BUTTON_AVOID}` = above the footer, as before 1.17.2), tokens `--ipal-cookie-button-offset` / `-inset`, amount by hand `--ipal-cookie-button-space` on the footer. Do not render the button inside the footer, write a scroll handler for it, or add bottom padding for it by hand | consent.md → "Where the cookie button sits" |
| Banner at first paint (not after hydration; LCP) | built in: `CookieBanner firstPaint` (default on), `SiteProviders nonce` under a nonce CSP; off: `firstPaint={false}`; server-exact HTML on a dynamic site: `SiteProviders consentCookie` / `ConsentProvider cookieValue`; your own banner: `consentBannerScript`. Check: `curl -s <page> \| grep -c 'data-ipal="banner-script"'` → 1 and the response still has `s-maxage` | consent.md → "First paint" |
| Settings window: in the bar / small / large with cookie details | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — do not build your own window or cookie list | consent.md → "Large window with details" |
| A consent-dependent script | `ConsentScript` | consent.md |
@@ -56,11 +56,13 @@ before analytics or marketing consent — check the project's choice in "Project
decision is from an older Policy version must see it at once. A click on a button before hydration
counts (the checks above click as soon as the button is visible).
7. Cookie button (1.17.2, consent.md → "Where the cookie button sits"): after a decision, on a long page, a short
page and a page with a form, desktop and phone width — the button is in the bottom corner of the window at the
top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it
lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose
corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a
button rendered inside the footer → remove (AGENT.md §7).
page and a page with a form, desktop and phone width (also 360 px) — the button is in the bottom corner of the
window at the top, in the middle, with the footer in view and at the very end: it must not move at all. At the
very end nothing of the footer is under it and the last footer link can be tapped (the footer has grown a little:
`[data-ipal-cookie-space]` on it). Before a decision and while the banner is open the footer has its own padding
only. Tab reaches the button and Enter reopens the banner. A project scroll handler, a button rendered inside
the footer or hand-made bottom padding for it → remove (AGENT.md §7). Too much or too little room:
`--ipal-cookie-button-space` on the footer; none: `reserve={false}`.
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
@@ -168,9 +168,10 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|---|---|---|
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint?, nonce?, cookieValue?, gpc?, maxAgeDays? }` (`gpc`: Global Privacy Control `'honour'` default / `'ask'` / `false`; `maxAgeDays`: re-ask period, default 180; withdrawal also removes the panel's listed storage keys and tells Meta / TikTok / Clarity) (`nonce`: CSP nonce for the banner's first-paint script; `cookieValue`: optional server-read consent cookie → exact HTML, dynamic pages) — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`, `firstPaint` (default `true`: in the server HTML, decided before the first paint by an inline script; pages stay static), `nonce`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Fixed in the bottom corner of the window on every page (1.17.2: it no longer climbs above the footer); at the very end of the page it steps just above a link or button it would keep covered. Props `className`, `side` (`'left' \| 'right'`), `clear` (selector of controls to free at the page end, default `COOKIE_BUTTON_CLEAR`; `false`), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID` = footer; `false` = never move). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Fixed in the bottom corner of the window on every page and never moves (1.17.2: it no longer climbs above the footer). While it is shown the footer gets just enough bottom padding for its last row to end above the button (measured; the footer's own padding counts; nothing where the corner is empty; made before the first paint for a returning visitor). Props `className`, `side` (`'left' \| 'right'`), `reserve` (selector of the block that gets the room, default `COOKIE_BUTTON_RESERVE` = footer; `false` = none), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID`). Amount by hand: `--ipal-cookie-button-space` on the footer (`0` = none). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Footer selector for the placement before 1.17.2 (`<CookieButton avoid={COOKIE_BUTTON_AVOID} />`); pixels the footer covers at the bottom of the screen (how far the button moves up then) |
| `COOKIE_BUTTON_CLEAR`, `stepAbove(button, obstacles, max)` | `@intecion/ipal-kit/client` | Default selector of controls the cookie button frees at the end of the page; how far a box must move up to lie on none of the given boxes (0 = stays, also when no free place within `max`) |
| `COOKIE_BUTTON_RESERVE`, `COOKIE_BUTTON_SPACE_ATTRIBUTE`, `reserveCookieButtonSpace(options)` | `@intecion/ipal-kit/client` | Default selector of the block that gets room for the cookie button (the footer); the attribute that marks it while the room is there; the function that measures and applies (or, with `release: true`, removes) it — options type `CookieButtonSpaceOptions` (`selector`, `side`, `button?`, `release?`, `sheet?`). For a button of your own |
| `consentDecidedScript({ version?, gpc?, cookieName? })` | `@intecion/ipal-kit` | JavaScript statements for an inline script: leave `true` in `d` when the browser holds a current consent decision (as `readConsentRecord` decides). The shared start of the plugin's pre-paint scripts |
| `TOTP_TEXTS`, `TOTP_VIEW_TITLE` | `@intecion/ipal-kit` | en/pl texts of the 2FA screens (`totpPlugin:*`, merged by `twoFactor`) and their tab title |
| `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels?, locale?, categories?, caption?, classNames?, storageColumn?, storageTypes? }`; `rows` from `getCookieTable()`; a **Type** column when a row is local / session storage (`storageColumn: 'auto' \| boolean`). |
+8 -6
View File
@@ -35,12 +35,14 @@ the header, 200 with it. (2) A front end that posted to `/api/form-submissions`
and global its own write rule (`adminOrEditor`). (4) If the project has `tests/routes.ts`: `update`, judge, commit.
**→ 1.17.2, cookie button (CHANGELOG 1.17.2; PROGRAMISTA §6, item 83; consent.md "Where the cookie button sits") — nothing is required:**
visitors now see the "cookie settings" button in the bottom corner of the window on every page; it no longer moves up
above the footer. Look at the end of a page on a phone: the button must lie on no link (it steps up by itself; a
footer corner full of links → `side="right"` or a larger `--ipal-cookie-button-offset`). The placement before:
`cookieButton={<CookieButton avoid={COOKIE_BUTTON_AVOID} />}` on `SiteProviders`. A project that passes `avoid` (a
selector or `false`) or `className` keeps what it had. A project e2e that expects the button above the footer:
update it.
visitors now see the "cookie settings" button in the bottom corner of the window on every page; it never moves and
no longer rides up above the footer. While it is shown the footer is a little taller (about 40 px on the reference
site), so its last row ends above the button. Check the end of a page on a phone and on desktop: nothing under the
button, the last footer link can be tapped. Bottom padding a project added by hand for the button: remove it (the
plugin counts existing padding, so it is not doubled, but it is no longer needed). Amount by hand:
`--ipal-cookie-button-space` on the footer (`0` = none); no room: `reserve={false}`. The placement before:
`cookieButton={<CookieButton avoid={COOKIE_BUTTON_AVOID} />}` on `SiteProviders`. A project e2e that expects the button
above the footer, or an exact footer height after a decision: update it.
**→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with
`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`).
+31 -14
View File
@@ -116,22 +116,37 @@ takes `locale` and optional `labels`; defaults: `COOKIE_TABLE_LABELS` (`@intecio
### Where the cookie button sits (1.17.2)
`CookieButton` is fixed in the **bottom corner of the window** — on every page, long or short, at every scroll
position, on desktop and phone. It is a child of `<body>` (never inside the footer) and it no longer climbs above
the footer when the footer scrolls into view (1.12.x–1.17.1 did that: on a phone with a tall footer the button ended
at the top of the screen, on a short page in the middle of it).
position, on desktop and phone — and it **never moves**. It is a child of `<body>` (never inside the footer) and it
no longer climbs above the footer when the footer scrolls into view (1.12.x–1.17.1 did that: on a phone with a tall
footer the button ended at the top of the screen, on a short page in the middle of it).
One exception keeps every control reachable: **at the very end of the page**, where a visitor cannot scroll a
covered link out from under a fixed button, the button steps up just far enough to lie on no link, button or form
field (`stepAbove`; 8 px gap; never more than half the window, otherwise it stays in the corner). It then usually
rests on plain text of the footer (the copyright line). Anywhere above the end of the page it stays in the corner: a
covered control is one scroll away. The step is a `transform` — no layout shift.
**Room under the footer.** A fixed button would, at the very end of a page, lie on whatever is in that corner — the
first link of the footer's last row — and a visitor could not scroll it free. So while the button is shown, the
plugin gives the page's last block (the footer) **bottom padding: just enough for its last row to end above the
button** (`reserveCookieButtonSpace`). The footer's background continues through it.
| | |
|---|---|
| How much | measured, not fixed: the button's height + its distance from the bottom + the device's safe area + 8 px, **minus what is already free** under the lowest text or control in the button's column. The footer's own bottom padding counts first — never double space. On the reference site: 42–43 px on phones and desktop |
| Where nothing is in the corner | nothing is added (a centred footer on a wide screen, the button on the other side) — so there is no breakpoint to configure |
| When | only while the button is shown: not before a decision, not while the banner is open (the footer is as the project made it), gone when the button is turned off (`cookieButton={false}`) |
| No layout shift | on a static page the HTML carries a small inline script next to the button's place: for a visitor who already decided it makes the room **before the first paint** (in a style sheet, so React hydrates the server's markup untouched), and the button's own measurement after hydration gives the same size. After a click in the banner the room appears with the button. Later changes (fonts, a form that grows, a resize) are followed |
| Which block | the last element matching `reserve` (default `COOKIE_BUTTON_RESERVE` = `'footer, [role="contentinfo"]'`); none on the page → `<body>` |
| Prop | Default | What it does |
|---|---|---|
| `side` | `'left'` | corner: `'left'` or `'right'` |
| `clear` | `COOKIE_BUTTON_CLEAR` (links, buttons, form fields) | CSS selector of controls the button frees at the end of the page; `false` = stay in the corner whatever is under it |
| `avoid` | — | placement before 1.17.2: a CSS selector the button lifts above while it is on screen — `avoid={COOKIE_BUTTON_AVOID}` (`'footer, [role="contentinfo"]'`) is exactly the old default (`bottomOverlap`). `false` = never move at all (also turns `clear` off) |
| `className` | — | replaces the default classes; position is then yours too (the `clear` step applies only while your classes keep it `position: fixed`) |
| `reserve` | `COOKIE_BUTTON_RESERVE` | CSS selector of the block that gets the room (the last match); `false` = no room — the button then covers what is in the corner at the end of the page |
| `avoid` | — | placement before 1.17.2: a CSS selector the button lifts above while it is on screen — `avoid={COOKIE_BUTTON_AVOID}` (`'footer, [role="contentinfo"]'`) is exactly the old default (`bottomOverlap`); no room is reserved then. `false` = the default (kept for sites that set it) |
| `className` | — | replaces the default classes; position is then yours too (room is measured from the real button once it is on the page, and only while it is `position: fixed`) |
**Set the amount yourself:** `--ipal-cookie-button-space` on the footer — any length, added to the footer's own
padding instead of the measured amount; `0` = none, also per breakpoint:
```css
footer { --ipal-cookie-button-space: 4rem; }
@media (min-width: 64rem) { footer { --ipal-cookie-button-space: 0; } } /* nothing on desktop */
```
Position tokens: `--ipal-cookie-button-offset` (from the bottom, default `1rem`), `--ipal-cookie-button-inset`
(from the side, default `1rem`); the device's safe-area insets (bottom and the chosen side) are added. z-index
@@ -139,8 +154,10 @@ Position tokens: `--ipal-cookie-button-offset` (from the bottom, default `1rem`)
Hidden while the banner is showing. Keyboard: a `<button>` in the tab order with an `aria-label` from the panel.
Type `CookieButtonProps`.
A footer that is full of links in that corner: choose `side="right"`, raise `--ipal-cookie-button-offset`, or give
the footer's last row some bottom padding — the button then rests there.
Nonce CSP: the inline script takes the nonce given to `SiteProviders` / `ConsentProvider`; refused, the room is made
when the button appears (a footer pinned to the bottom of a page shorter than the window then moves once).
Building blocks: `reserveCookieButtonSpace({ selector, side, button?, release? })`, `COOKIE_BUTTON_SPACE_ATTRIBUTE`
(`/client`), `consentDecidedScript` (root).
## Compliance defaults (1.17.0)
@@ -471,7 +488,7 @@ New fields in the global = a migration in projects on Postgres/SQLite (`payload
The elements also have stable `data-ipal` handles for CSS and e2e tests (used by
`iapl-consent-check`): `banner` (while it waits for the first-paint script it carries `hidden`; a button clicked before hydration:
`data-ipal-pending`; live: `data-ipal-ready`), `banner-script`, `cookie-button` and the buttons `settings`, `reject`,
`data-ipal-pending`; live: `data-ipal-ready`), `banner-script`, `cookie-button` (`cookie-button-script`: its inline script in the server HTML; `data-ipal-cookie-space` on the footer while it holds the button's room) and the buttons `settings`, `reject`,
`accept`, `back`, `save`; in modal mode also `consent-overlay`, `consent-dialog`, `close`; in detailed mode
additionally `category-<category>` (card) and `cookies` (expandable list).
+1 -1
View File
@@ -690,7 +690,7 @@ Do one item at a time, build, check. Order by importance:
| 80 | **1.17.1 — the sign-in look** — after the update the login and 2FA screens show a dark panel with the logo or the site's name; an editor cannot change the logo or name; forgot / reset password look as before | Nothing required. `whiteLabel: { signIn: false }` (old screens), `{ brandAccess: 'editor' }`, `{ signIn: { logoPlate: true } }` (a dark logo), `{ signIn: { svgLogo: false } }`; the other screens: `signIn: { allScreens: true }` + `pnpm payload generate:importmap`. No `serverURL` → no logo in the link preview: set it | `iapl-upgrade` "→ 1.17.1, the sign-in look", white-label.md "The sign-in screens" |
| 81 | **1.17.1 — proxy matcher** — `iapl-doctor` warns `proxy-matcher`; pages such as `/administracja` or `/apis` get no locale redirect or proxy CSP | `src/proxy.ts`: `matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher") | `iapl-upgrade` "→ 1.17.1" |
| 82 | **1.17.1 — e-mail: "Sending method" is a choice** — Site integrations → E-mail sending shows "IWSN (built-in)", "Own SMTP server" or "Microsoft Graph (deprecated)" as selected; or, on Postgres / SQLite, the start log says the column for `emailMethod` is missing and the Site integrations page does not open; or mail fails with `smtp-incomplete` / `graph-not-set-up` | MongoDB: nothing. Postgres / SQLite: `pnpm payload migrate:create`, commit, apply at start. Nothing changes until another option is picked and saved; a chosen method that cannot be used fails loudly (no other transport): fill in SMTP, set `GRAPH_*`, or pick another method | `iapl-upgrade` "→ 1.17.1, e-mail", email.md "Which transport a send takes" |
| 83 | **1.17.2 — cookie button** — after the update the "cookie settings" button no longer sits above the footer; or at the end of a page on a phone it rests a little above the corner | Intended: it stays in the bottom corner of the window on every page and, at the very end of the page, steps just above a link or button it would keep covered. Nothing to run. The placement before: `<CookieButton avoid={COOKIE_BUTTON_AVOID} />`; never move: `avoid={false}`; other corner: `side="right"`; distance: `--ipal-cookie-button-offset` | consent.md "Where the cookie button sits", `iapl-upgrade` "→ 1.17.2, cookie button" |
| 83 | **1.17.2 — cookie button** — after the update the "cookie settings" button no longer sits above the footer; or the footer is about 40 px taller after a decision | Intended: the button stays in the bottom corner of the window on every page and never moves; while it is shown the footer gets just enough bottom padding for its last row to end above the button (measured; own padding counts; nothing before a decision or while the banner is open). Nothing to run. No room: `<CookieButton reserve={false} />`; amount by hand: `--ipal-cookie-button-space` on the footer; the placement before: `avoid={COOKIE_BUTTON_AVOID}`; other corner: `side="right"`; distance: `--ipal-cookie-button-offset` | consent.md "Where the cookie button sits", `iapl-upgrade` "→ 1.17.2, cookie button" |
After updating the package: `pnpm exec iapl-skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`.
@@ -56,11 +56,13 @@ before analytics or marketing consent — check the project's choice in "Project
decision is from an older Policy version must see it at once. A click on a button before hydration
counts (the checks above click as soon as the button is visible).
7. Cookie button (1.17.2, consent.md → "Where the cookie button sits"): after a decision, on a long page, a short
page and a page with a form, desktop and phone width — the button is in the bottom corner of the window at the
top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it
lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose
corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a
button rendered inside the footer → remove (AGENT.md §7).
page and a page with a form, desktop and phone width (also 360 px) — the button is in the bottom corner of the
window at the top, in the middle, with the footer in view and at the very end: it must not move at all. At the
very end nothing of the footer is under it and the last footer link can be tapped (the footer has grown a little:
`[data-ipal-cookie-space]` on it). Before a decision and while the banner is open the footer has its own padding
only. Tab reaches the button and Enter reopens the banner. A project scroll handler, a button rendered inside
the footer or hand-made bottom padding for it → remove (AGENT.md §7). Too much or too little room:
`--ipal-cookie-button-space` on the footer; none: `reserve={false}`.
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
@@ -165,9 +165,10 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|---|---|---|
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint?, nonce?, cookieValue?, gpc?, maxAgeDays? }` (`gpc`: Global Privacy Control `'honour'` default / `'ask'` / `false`; `maxAgeDays`: re-ask period, default 180; withdrawal also removes the panel's listed storage keys and tells Meta / TikTok / Clarity) (`nonce`: CSP nonce for the banner's first-paint script; `cookieValue`: optional server-read consent cookie → exact HTML, dynamic pages) — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`, `firstPaint` (default `true`: in the server HTML, decided before the first paint by an inline script; pages stay static), `nonce`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Fixed in the bottom corner of the window on every page (1.17.2: it no longer climbs above the footer); at the very end of the page it steps just above a link or button it would keep covered. Props `className`, `side` (`'left' \| 'right'`), `clear` (selector of controls to free at the page end, default `COOKIE_BUTTON_CLEAR`; `false`), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID` = footer; `false` = never move). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Fixed in the bottom corner of the window on every page and never moves (1.17.2: it no longer climbs above the footer). While it is shown the footer gets just enough bottom padding for its last row to end above the button (measured; the footer's own padding counts; nothing where the corner is empty; made before the first paint for a returning visitor). Props `className`, `side` (`'left' \| 'right'`), `reserve` (selector of the block that gets the room, default `COOKIE_BUTTON_RESERVE` = footer; `false` = none), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID`). Amount by hand: `--ipal-cookie-button-space` on the footer (`0` = none). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Footer selector for the placement before 1.17.2 (`<CookieButton avoid={COOKIE_BUTTON_AVOID} />`); pixels the footer covers at the bottom of the screen (how far the button moves up then) |
| `COOKIE_BUTTON_CLEAR`, `stepAbove(button, obstacles, max)` | `@intecion/ipal-kit/client` | Default selector of controls the cookie button frees at the end of the page; how far a box must move up to lie on none of the given boxes (0 = stays, also when no free place within `max`) |
| `COOKIE_BUTTON_RESERVE`, `COOKIE_BUTTON_SPACE_ATTRIBUTE`, `reserveCookieButtonSpace(options)` | `@intecion/ipal-kit/client` | Default selector of the block that gets room for the cookie button (the footer); the attribute that marks it while the room is there; the function that measures and applies (or, with `release: true`, removes) it — options type `CookieButtonSpaceOptions` (`selector`, `side`, `button?`, `release?`, `sheet?`). For a button of your own |
| `consentDecidedScript({ version?, gpc?, cookieName? })` | `@intecion/ipal-kit` | JavaScript statements for an inline script: leave `true` in `d` when the browser holds a current consent decision (as `readConsentRecord` decides). The shared start of the plugin's pre-paint scripts |
| `TOTP_TEXTS`, `TOTP_VIEW_TITLE` | `@intecion/ipal-kit` | en/pl texts of the 2FA screens (`totpPlugin:*`, merged by `twoFactor`) and their tab title |
| `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels?, locale?, categories?, caption?, classNames?, storageColumn?, storageTypes? }`; `rows` from `getCookieTable()`; a **Type** column when a row is local / session storage (`storageColumn: 'auto' \| boolean`). |
@@ -35,12 +35,14 @@ the header, 200 with it. (2) A front end that posted to `/api/form-submissions`
and global its own write rule (`adminOrEditor`). (4) If the project has `tests/routes.ts`: `update`, judge, commit.
**→ 1.17.2, cookie button (CHANGELOG 1.17.2; PROGRAMISTA §6, item 83; consent.md "Where the cookie button sits") — nothing is required:**
visitors now see the "cookie settings" button in the bottom corner of the window on every page; it no longer moves up
above the footer. Look at the end of a page on a phone: the button must lie on no link (it steps up by itself; a
footer corner full of links → `side="right"` or a larger `--ipal-cookie-button-offset`). The placement before:
`cookieButton={<CookieButton avoid={COOKIE_BUTTON_AVOID} />}` on `SiteProviders`. A project that passes `avoid` (a
selector or `false`) or `className` keeps what it had. A project e2e that expects the button above the footer:
update it.
visitors now see the "cookie settings" button in the bottom corner of the window on every page; it never moves and
no longer rides up above the footer. While it is shown the footer is a little taller (about 40 px on the reference
site), so its last row ends above the button. Check the end of a page on a phone and on desktop: nothing under the
button, the last footer link can be tapped. Bottom padding a project added by hand for the button: remove it (the
plugin counts existing padding, so it is not doubled, but it is no longer needed). Amount by hand:
`--ipal-cookie-button-space` on the footer (`0` = none); no room: `reserve={false}`. The placement before:
`cookieButton={<CookieButton avoid={COOKIE_BUTTON_AVOID} />}` on `SiteProviders`. A project e2e that expects the button
above the footer, or an exact footer height after a decision: update it.
**→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with
`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`).
+118 -54
View File
@@ -493,70 +493,134 @@ test('consent: withdrawal — reopen, reject: analytics cookies and listed stora
expect((await consentRecord(context))!.state).toMatchObject({ analytics: false, functional: false, marketing: false })
})
// The "cookie settings" button stays in the bottom corner of the window (1.17.2): it does not climb above the footer.
// At the very end of the page it steps above a link it would keep covered.
// The "cookie settings" button stays in the bottom corner of the window (1.17.2) and never moves: not above the
// footer, not at the end of the page. The footer gets room under its last row while the button is shown, so the
// button covers nothing there (consent.md → "Where the cookie button sits").
const BUTTON_PAGES = ['/pl', '/pl/kontakt', '/en', '/pl/blog', '/pl/regulamin']
const buttonState = () => {
const b = document.querySelector<HTMLElement>('[data-ipal="cookie-button"]')
const footer = [...document.querySelectorAll<HTMLElement>('footer, [role="contentinfo"]')].at(-1)!
if (!b) {return { button: false, room: footer.hasAttribute('data-ipal-cookie-space') }}
const r = b.getBoundingClientRect()
const hits = (q: DOMRect) => q.width > 0 && q.height > 0 && q.right > r.left && q.left < r.right && q.bottom > r.top && q.top < r.bottom
// every piece of footer text and every control of the page that lies under the button
const under: string[] = []
const walker = document.createTreeWalker(footer, NodeFilter.SHOW_TEXT)
const range = document.createRange()
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (!/\S/.test(node.nodeValue ?? '')) {continue}
range.selectNodeContents(node)
if ([...range.getClientRects()].some(hits)) {under.push(`text: ${node.nodeValue!.trim().slice(0, 24)}`)}
}
for (const el of document.querySelectorAll('a[href], button, input, select, textarea, summary')) {
if (el !== b && hits(el.getBoundingClientRect())) {under.push(`control: ${(el.textContent ?? '').trim().slice(0, 24)}`)}
}
return {
button: true,
gap: Math.round(window.innerHeight - r.bottom),
inFooter: !!b.closest('footer'),
left: Math.round(r.left),
position: getComputedStyle(b).position,
room: footer.hasAttribute('data-ipal-cookie-space'),
transform: getComputedStyle(b).transform,
under,
}
}
const CORNER = { button: true, gap: 16, inFooter: false, left: 16, position: 'fixed', transform: 'none' }
for (const device of [
{ name: 'desktop', viewport: { height: 800, width: 1280 } },
{ name: 'phone', viewport: { height: 844, width: 390 } },
{ name: 'small phone', viewport: { height: 640, width: 360 } },
]) {
test(`cookie button, ${device.name}: bottom corner on long and short pages, never on a link at the page end, no layout shift`, async ({ browser }) => {
const context = await browser.newContext({ viewport: device.viewport })
const page = await context.newPage()
await page.addInitScript(() => {
const w = window as unknown as { __cls: number }
w.__cls = 0
new PerformanceObserver((list) => {
for (const entry of list.getEntries() as unknown as { hadRecentInput: boolean; value: number }[]) {
if (!entry.hadRecentInput) {w.__cls += entry.value}
}
}).observe({ buffered: true, type: 'layout-shift' })
})
await page.goto('/pl')
await page.locator('[data-ipal="reject"]').click()
const button = page.locator('[data-ipal="cookie-button"]')
const probe = () =>
button.evaluate((b: HTMLElement) => {
const r = b.getBoundingClientRect()
b.style.pointerEvents = 'none'
const covered = [[r.left + 4, r.top + 4], [r.right - 4, r.top + 4], [r.left + 4, r.bottom - 4], [r.right - 4, r.bottom - 4], [r.left + r.width / 2, r.top + r.height / 2]]
.map(([x, y]) => document.elementFromPoint(x, y)?.closest('a, button, input, select, textarea, summary'))
.filter(Boolean)
.map((el) => (el!.textContent ?? '').trim().slice(0, 30))
b.style.pointerEvents = ''
return { covered, gap: Math.round(window.innerHeight - r.bottom), inFooter: !!b.closest('footer'), left: Math.round(r.left), position: getComputedStyle(b).position }
for (const colorScheme of ['light', 'dark'] as const) {
test(`cookie button, ${device.name}, ${colorScheme}: the corner at every scroll position, nothing under it at the end, no layout shift`, async ({ browser }) => {
const context = await browser.newContext({ colorScheme, hasTouch: device.name !== 'desktop', viewport: device.viewport })
const page = await context.newPage()
await page.addInitScript(() => {
const w = window as unknown as { __cls: number }
w.__cls = 0
new PerformanceObserver((list) => {
for (const entry of list.getEntries() as unknown as { hadRecentInput: boolean; value: number }[]) {
if (!entry.hadRecentInput) {w.__cls += entry.value}
}
}).observe({ buffered: true, type: 'layout-shift' })
})
for (const path of ['/pl', '/pl/regulamin', '/pl/kontakt']) {
await page.goto(path)
await expect(button).toBeVisible()
const shifts = () => page.evaluate(() => (window as unknown as { __cls: number }).__cls)
await page.waitForTimeout(300)
const before = await shifts()
const height = await page.evaluate(() => document.documentElement.scrollHeight)
for (const y of [0, Math.max(0, (height - device.viewport.height) / 2)]) {
await page.evaluate((to) => window.scrollTo(0, to), y)
await page.waitForTimeout(350)
if (y + device.viewport.height < height - 2) {
// anywhere above the end of the page: exactly in the corner, the footer in view or not
expect(await probe(), `${path} at ${Math.round(y)}`).toMatchObject({ gap: 16, inFooter: false, left: 16, position: 'fixed' })
const footerPadding = () => page.evaluate(() => getComputedStyle([...document.querySelectorAll('footer')].at(-1)!).paddingBottom)
// before a decision: no button, the footer as the project made it
await page.goto('/pl')
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
expect(await page.evaluate(buttonState)).toEqual({ button: false, room: false })
const ownPadding = await footerPadding()
await page.locator('[data-ipal="reject"]').click()
const button = page.locator('[data-ipal="cookie-button"]')
for (const path of BUTTON_PAGES) {
// a returning visitor's page load: the room is there from the first paint, so nothing shifts when the button appears
await page.goto(path)
await expect(button).toBeVisible()
await page.waitForTimeout(400)
const height = await page.evaluate(() => document.documentElement.scrollHeight)
const end = Math.max(0, height - device.viewport.height)
for (const y of [0, end / 2, end - 40, end]) {
await page.evaluate((to) => window.scrollTo(0, to), y)
await page.waitForTimeout(250)
expect(await page.evaluate(buttonState), `${path} at ${Math.round(y)} of ${end}`).toMatchObject(CORNER)
}
// the very end of the page (measured now: a form or its Turnstile widget may have grown the page since)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(250)
expect(await page.evaluate(() => Math.round(window.innerHeight + window.scrollY - document.documentElement.scrollHeight)), `${path}: at the end`).toBe(0)
expect(await page.evaluate(buttonState), `${path} at the very end`).toMatchObject(CORNER)
// no footer text and no control under the button
expect((await page.evaluate(buttonState)).under, `${path}: under the button at the end`).toEqual([])
// and every footer link can be clicked (Playwright refuses a click another element would receive)
const links = page.locator('footer a[href]')
const count = await links.count()
expect(count).toBeGreaterThan(3)
for (let i = 0; i < count; i++) {await links.nth(i).click({ timeout: 3000, trial: true })}
expect(await shifts(), `${path}: layout shift from load to the end of the page`).toBeLessThan(0.001)
}
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(450)
const end = await probe()
expect(end, `${path} at the end`).toMatchObject({ covered: [], inFooter: false, left: 16, position: 'fixed' })
expect(end.gap, `${path}: still at the bottom, not above the footer`).toBeLessThan(120)
expect((await shifts()) - before, `${path}: layout shift while scrolling`).toBeLessThan(0.001)
}
// keyboard: reachable and it reopens the banner
await button.focus()
await expect(button).toBeFocused()
await page.keyboard.press('Enter')
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
await expect(button).toHaveCount(0)
await context.close()
})
// keyboard: reachable and it reopens the banner; the room goes with the button
await button.focus()
await expect(button).toBeFocused()
await page.keyboard.press('Enter')
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
expect(await page.evaluate(buttonState)).toEqual({ button: false, room: false })
await page.goto('/pl') // decided again? no: reopening does not undo the stored decision, the button is back
await expect(button).toBeVisible()
await page.locator('[data-ipal="cookie-button"]').click()
expect(await footerPadding(), 'banner open: the footer as before a decision').toBe(ownPadding)
await context.close()
})
}
}
test('cookie button: for a returning visitor the room is there before the page hydrates (no application script)', async ({ browser }) => {
const context = await browser.newContext({ hasTouch: true, viewport: { height: 844, width: 390 } })
const page = await context.newPage()
const padding = () => page.evaluate(() => parseFloat(getComputedStyle([...document.querySelectorAll('footer')].at(-1)!).paddingBottom))
await page.goto('/pl')
const own = await padding()
await page.locator('[data-ipal="reject"]').click()
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
const live = await padding()
expect(live).toBeGreaterThan(own)
// the same page with every application script refused: only the inline script can have made the room
await page.route(isAppScript, (route) => route.abort())
await page.goto('/pl')
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
// the same room, to the pixel or one off: here the web font may not have arrived yet, and the row's text box follows the font
expect(Math.abs((await padding()) - live)).toBeLessThanOrEqual(2)
expect(await padding()).toBeGreaterThan(own + 30)
// the server's markup is untouched (React hydrates it without a mismatch): the room is in a style sheet
expect(await page.evaluate(() => [...document.querySelectorAll('footer')].at(-1)!.getAttribute('style'))).toBeNull()
await context.close()
})
test('admin: sign in through 2FA, agency credit, panel link preview', async ({ page, request }) => {
const head = await (await request.get('/admin/login')).text()
expect(head).toMatch(/noindex/)
+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'
+5 -3
View File
@@ -168,7 +168,7 @@ describe('server render', () => {
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
const html = renderToString(tree({ banner: { firstPaint: false } }))
expect(html).not.toContain('data-ipal="banner"')
expect(html).not.toContain('<script')
expect(html).not.toContain('data-ipal="banner-script"')
})
test('nonce: from the provider, or the banner prop', () => {
@@ -444,9 +444,11 @@ describe('tags: nothing earlier than before', () => {
const pixels = { clarityProjectId: 'clar', consentMode: 'basic', gtmContainerId: 'GTM-TEST', metaPixelId: '123' }
const layer = () => [...((window.dataLayer ?? []))].map((entry) => (Object.prototype.toString.call(entry) === '[object Arguments]' ? Array.from(entry as ArrayLike<unknown>) : entry))
test('the server HTML holds one script, the banner one, and it names no tag', () => {
test("the server HTML holds two scripts, the banner's and the cookie button's (1.17.2), and neither names a tag", () => {
const html = renderToString(tree({ analytics: pixels }))
expect(html.match(/<script/g)).toHaveLength(1)
expect(html.match(/<script[^>]*data-ipal="(?:banner|cookie-button)-script"/g)).toHaveLength(2)
expect(html.match(/<script/g)).toHaveLength(2)
expect(html).not.toMatch(/createElement\(["']script|\.src\s*=|fetch\(|XMLHttpRequest|dataLayer|document\.cookie\s*=[^=]/)
expect(html).not.toMatch(/googletagmanager|facebook|clarity|GTM-TEST/)
})
+283 -125
View File
@@ -1,16 +1,18 @@
// @vitest-environment happy-dom
/**
* Where <CookieButton> sits (1.17.2): the bottom corner of the window, always — it does not climb above the footer.
* Only at the very end of the page it steps above a control it would keep covered. The placement before 1.17.2
* (above the footer) and "never move" stay available.
* 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, type Root } from 'react-dom/client'
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, COOKIE_BUTTON_CLEAR, CookieButton, stepAbove } from '../src/modules/consent/CookieButton.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'
@@ -18,172 +20,328 @@ const h = createElement as unknown as (type: unknown, props?: null | object, ...
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
const box = (top: number, bottom: number, left = 16, right = 60) => ({ bottom, left, right, top })
/** The button's resting place in an 800 px high window: 44 px, 16 px from the bottom and the left. */
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)
describe('stepAbove', () => {
test('nothing under the button: stays', () => {
expect(stepAbove(REST, [], 400)).toBe(0)
expect(stepAbove(REST, [box(700, 730), box(750, 780, 200, 300), box(790, 800)], 400)).toBe(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('a link under it: just above the link, with a gap', () => {
expect(stepAbove(REST, [box(760, 780, 30, 120)], 400)).toBe(784 - 760 + 8)
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('two rows of links: above both, onto text', () => {
// social links at 760–780, legal links at 724–744: clearing the first lands on the second
expect(stepAbove(REST, [box(760, 780, 30, 120), box(724, 744, 30, 200)], 400)).toBe(784 - 724 + 8)
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('no free place within the limit: back to the corner', () => {
const wall = Array.from({ length: 20 }, (_, i) => box(780 - (i + 1) * 30, 780 - i * 30))
expect(stepAbove(REST, wall, 400)).toBe(0)
expect(stepAbove(REST, [box(300, 790)], 400)).toBe(0)
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('the default list of controls', () => {
for (const selector of ['a[href]', 'button', 'input', 'select', 'textarea', 'summary']) {expect(COOKIE_BUTTON_CLEAR).toContain(selector)}
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('placement', () => {
describe('<CookieButton>', () => {
let container: HTMLDivElement
let root: Root
let rects: Map<Element, ReturnType<typeof box>>
let page: { height: number; scrollY: number }
let root: Root | undefined
let errors: ReturnType<typeof vi.spyOn>
const setRect = (el: Element, r: ReturnType<typeof box>) => rects.set(el, r)
const button = () => document.querySelector<HTMLButtonElement>('[data-ipal="cookie-button"]')!
const lift = () => /translateY\(-(?<px>[\d.]+)px\)/.exec(button().style.transform)?.groups?.px ?? '0'
const cookieButton = () => document.querySelector<HTMLButtonElement>('[data-ipal="cookie-button"]')
const frame = () => act(() => new Promise((resolve) => setTimeout(resolve, 40)))
const scrollTo = async (y: number) => {
page.scrollY = y
window.dispatchEvent(new Event('scroll'))
await frame()
}
const add = (html: string) => {
const el = document.createElement('div')
el.innerHTML = html
document.body.appendChild(el)
return el.firstElementChild!
}
const tree = (props: object = {}, provider: object = {}) => h(ConsentProvider, { texts: CONSENT_FALLBACK, ...provider }, h(CookieButton, props))
const mount = async (props: object = {}) => {
act(() => root.render(h(ConsentProvider, { texts: CONSENT_FALLBACK }, h(CookieButton, props))))
setRect(button(), REST)
window.dispatchEvent(new Event('resize'))
act(() => {
root = createRoot(container)
root.render(tree(props))
})
await frame()
}
beforeEach(() => {
resetConsentStore()
document.cookie = `${CONSENT_COOKIE}=${serializeConsent({ analytics: false, functional: false, marketing: false, necessary: true })};path=/`
rects = new Map()
page = { height: 3000, scrollY: 0 }
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
const r = rects.get(this) ?? { bottom: 0, left: 0, right: 0, top: 0 }
// like the browser: the measured box includes the transform the button carries
const moved = this === document.querySelector('[data-ipal="cookie-button"]') ? Number(/translateY\(-([\d.]+)px\)/.exec((this as HTMLElement).style.transform)?.[1] ?? 0) : 0
return { ...r, bottom: r.bottom - moved, height: r.bottom - r.top, top: r.top - moved, width: r.right - r.left, x: r.left, y: r.top - moved } as DOMRect
})
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800)
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => page.scrollY)
vi.spyOn(document.documentElement, 'scrollHeight', 'get').mockImplementation(() => page.height)
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
errors = vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
act(() => root.unmount())
document.body.innerHTML = ''
vi.restoreAllMocks()
if (root) {act(() => root!.unmount())}
root = undefined
})
test('default: fixed in the bottom corner with the safe-area insets, below dialogs', async () => {
test('default: fixed in the bottom corner with the safe-area insets, below dialogs, a labelled button', async () => {
decide()
await mount()
const style = button().style
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(button().getAttribute('aria-label')).toBe(CONSENT_FALLBACK.settingsTitle)
expect(button().type).toBe('button')
expect(cookieButton()!.getAttribute('aria-label')).toBe(CONSENT_FALLBACK.settingsTitle)
expect(cookieButton()!.type).toBe('button')
})
test('side="right": the right corner and its safe-area inset', async () => {
await mount({ side: 'right' })
expect(button().style.right).toBe('calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-right, 0px))')
expect(button().style.left).toBe('')
})
test('default: the footer on screen does not move it (before 1.17.2 it rode up by 300 px here)', async () => {
setRect(add('<footer>company</footer>'), box(500, 1100, 0, 1280))
test('it never moves: footer in view, scrolling, the end of the page with a link under it', async () => {
decide()
footer()
await mount()
await scrollTo(1500)
expect(lift()).toBe('0')
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('avoid={COOKIE_BUTTON_AVOID}: the placement before 1.17.2, above the footer', async () => {
setRect(add('<footer>company</footer>'), box(500, 1100, 0, 1280))
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(lift()).toBe('300')
expect(cookieButton()!.style.transform).toBe('translateY(-300px)')
expect(el.style.paddingBottom).toBe('')
})
test('end of the page, a footer link in the corner: steps just above it; scrolling back up: returns to the corner', async () => {
const link = add('<a href="/x">Instagram</a>')
setRect(link, box(760, 780, 30, 120))
await mount()
await scrollTo(1000) // mid-page: a covered link is one scroll away, the button stays
expect(lift()).toBe('0')
await scrollTo(2200) // 2200 + 800 = the end
expect(lift()).toBe('32')
await scrollTo(2200) // measured again while lifted: the same step, no creeping
expect(lift()).toBe('32')
await scrollTo(1000)
expect(lift()).toBe('0')
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')
})
test('a page shorter than the window is always at its end', async () => {
page.height = 800
setRect(add('<button>Send</button>'), box(750, 790, 20, 140))
await mount()
expect(lift()).toBe('42')
})
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('end of the page, nothing under it (text only): stays in the corner', async () => {
setRect(add('<p>© Example</p>'), box(760, 780, 30, 400))
setRect(add('<a href="/y">Terms</a>'), box(760, 780, 900, 960))
await mount()
await scrollTo(2200)
expect(lift()).toBe('0')
})
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('clear={false} and avoid={false}: never moves', async () => {
setRect(add('<a href="/x">Instagram</a>'), box(760, 780, 30, 120))
setRect(add('<footer>company</footer>'), box(500, 1100, 0, 1280))
await mount({ clear: false })
await scrollTo(2200)
expect(lift()).toBe('0')
act(() => root.render(h(ConsentProvider, { texts: CONSENT_FALLBACK }, h(CookieButton, { avoid: false }))))
await scrollTo(2200)
expect(lift()).toBe('0')
})
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 selector of your own in clear', async () => {
setRect(add('<a href="/x">Instagram</a>'), box(760, 780, 30, 120))
setRect(add('<div class="chat">chat</div>'), box(700, 790, 10, 70))
await mount({ clear: '.chat' })
await scrollTo(2200)
expect(lift()).toBe(String(784 - 700 + 8))
})
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('className (the project positions it, here not fixed): no step', async () => {
setRect(add('<a href="/x">Instagram</a>'), box(760, 780, 30, 120))
await mount({ className: 'in-the-footer' })
expect(button().style.position).toBe('')
await scrollTo(2200)
expect(lift()).toBe('0')
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')
})
})
})