Merge claude/consent-banner-first-paint-154f9f: the cookie banner is part of the first render
Conflicts in the docs only, both sides kept: changelog lines, AGENT.md checklist rows 12 (banner) and 13 (wrapper order), the two iapl-upgrade blocks, PROGRAMISTA rows 76 (client hints) and 77 (banner, renumbered from 76). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -38,6 +38,18 @@ before analytics or marketing consent — check the project's choice in "Project
|
||||
5. Banner not found (`data-ipal="banner"`) → `<CookieBanner/>` is not
|
||||
rendered, or an older IAPL version without `data-ipal` attributes on the buttons → **iapl-upgrade**.
|
||||
|
||||
6. Banner at first paint (1.17.0, consent.md → "First paint"): the banner is in the server HTML and an inline
|
||||
script shows or hides it before the browser paints; pages stay static.
|
||||
```bash
|
||||
curl -s http://localhost:3000/pl | grep -c 'data-ipal="banner-script"' # 1
|
||||
curl -sI http://localhost:3000/pl | grep -i cache-control # still s-maxage=… (static / ISR)
|
||||
```
|
||||
`0` → `firstPaint={false}`, a custom banner, or a wrapper that renders the banner only after mount
|
||||
(remove it). Under a nonce CSP the browser console must not report the inline script as refused: pass
|
||||
`nonce` to `<SiteProviders>`. A visitor who decided must never see the banner on reload; one whose
|
||||
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).
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -89,6 +89,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| canonical / sitemap with localhost | `NEXT_PUBLIC_SERVER_URL` not set in the build | set it in the build env (not only at runtime) |
|
||||
| `/admin`, `/_next` → 500 or a loop | the proxy matcher is not a literal | inline matcher in `proxy.ts` |
|
||||
| hydration mismatch on the banner | reading cookie/`window` during render | consent only through `CookieBanner`/`useConsentContext`; `Date`, `Math.random` outside render |
|
||||
| banner appears late (after hydration), is the LCP element | `firstPaint={false}`; IAPL older than 1.17.0; a nonce CSP without `<SiteProviders nonce>` (console: the inline script was refused); a custom `classNames.root` is fine | consent.md → "First paint"; check: `curl -s <page> \| grep -c 'data-ipal="banner-script"'` → 1 |
|
||||
| banner flashes for a visitor who already decided | the first-paint script was refused (nonce) and `classNames.root` sets `display` over `[hidden]` (Tailwind 3) | pass the nonce; add `[data-ipal="banner"][hidden] { display: none !important }` |
|
||||
| images do not load (R2) | media domain missing in `images.remotePatterns` / wrong `R2_PUBLIC_URL`; without `R2_PUBLIC_URL`: Media has no `access.read: () => true` → 403 on `/api/media/file/…` | `next.config.ts` + env, or Media access (storage.md) |
|
||||
| 404 page without styles/nav | `not-found.tsx` outside `[locale]` without a layout | pages.md — `not-found` example |
|
||||
|
||||
|
||||
@@ -161,14 +161,15 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint? }` — 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`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
|
||||
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint?, nonce?, cookieValue? }` (`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. Props `className`, `side` (`'left' \| 'right'`), `avoid` (selector it lifts above, default `COOKIE_BUTTON_AVOID` = footer; `false`). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
|
||||
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Default footer selector; pixels the footer covers at the bottom of the screen (how far the button moves up) |
|
||||
| `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`). |
|
||||
| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, acceptAll, rejectAll, savePreferences, reopen }`. Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). |
|
||||
| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, hydrated, serverRead, acceptAll, rejectAll, savePreferences, reopen }` (options: `cookieMap`, `version`, `onDecision`, `cookieValue`). Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). |
|
||||
| `consentBannerScript({ version?, cookieName? })` | `@intecion/ipal-kit` | The inline script `CookieBanner` puts after its markup: before the first paint it removes `hidden` from the banner (no current decision) or sets `display: none` (current decision), and keeps a click made before hydration. For a project's own banner; reads only the consent cookie. Options type: `ConsentBannerScriptOptions`. consent.md → "First paint". |
|
||||
| `useConsentContext()` | `@intecion/ipal-kit/client` | Hook: the `useConsent` value + `texts` from `ConsentProvider` — for your own consent-dependent UI (e.g. `state.marketing`). Throws outside the provider. |
|
||||
| `getConsentTexts({ payload, config, locale?, privacyPolicy?, settingsSlug? })` | `@intecion/ipal-kit` | Server: banner texts from the CookieSettings global (EN fallback per field) + privacy policy link from the system pages → `Promise<ConsentTexts>`; pass to `ConsentProvider texts`. |
|
||||
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookies → Cookie list rows in one language → `Promise<CookieTableRow[]>` (does not throw) — for `CookieTable`. |
|
||||
|
||||
@@ -452,6 +452,7 @@ and `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 with con
|
||||
- `createPageRoute`: `render` (your own view, e.g. an archive), `onMissing: 'redirectHome'`, `jsonLd: false`,
|
||||
`homeAlias: false`, `layoutField`; a fully custom page on `resolveRoute` (pages.md).
|
||||
`generateStaticParams` covers **only the pages collection, up to 1000 per language** — the scope is currently fixed (entries → ISR).
|
||||
- The cookie banner is in the server HTML and painted with the page; pages stay static (consent.md → "First paint"). Do not wrap it in a "mounted" guard. Off: `banner={<CookieBanner firstPaint={false} />}`; nonce CSP: `nonce` on `SiteProviders`; a dynamic site may pass `consentCookie` for server-exact HTML.
|
||||
- `SiteProviders`: `banner={false}` / your own, `cookieButton={false}`, `analytics={false}` / `{{ defer: true }}`,
|
||||
`preconnect={false}`, `jsonLd={[…]}` (adds), `cookieMap`, `theme`, `stats`; `JsonLdGraph` and
|
||||
`TurnstileProvider` currently always (Turnstile turns itself off without keys). A fully custom layout: providers from `/client`
|
||||
|
||||
@@ -566,6 +566,20 @@ PROGRAMISTA §6, item 76; security.md "Client hints") — one line, recommended
|
||||
**Check** (a production build, `pnpm build && pnpm start`): `curl -sI localhost:3000/pl | grep -iE 'accept-ch|critical-ch'` →
|
||||
nothing; `curl -sI localhost:3000/admin/login | grep -iE 'accept-ch|critical-ch'` → both; the panel opens in the browser's
|
||||
light / dark scheme with no flash; `pnpm exec iapl-doctor` has no `client-hints` finding.
|
||||
**→ 1.17.0, cookie banner at first paint (CHANGELOG 1.17.0 "Changed"; PROGRAMISTA §6, item 77; consent.md → "First paint") — nothing is required:**
|
||||
The banner is now in the server HTML and painted with the page (it appeared after hydration and could be the LCP
|
||||
element). Pages stay static; consent, tags, the cookie and the consent log are unchanged.
|
||||
1. Remove a project wrapper that delays the banner (`ConsentWrapper`, a "mounted" guard, `dynamic(…, { ssr: false })`)
|
||||
— it undoes the improvement.
|
||||
2. Nonce CSP (`createProxy({ csp })`): `<SiteProviders nonce={nonce}>` must be set (it already is where the theme
|
||||
script works); by hand: `<ConsentProvider nonce>`. Without it the banner appears after hydration, as before.
|
||||
3. Tailwind 3, or CSS of your own, with `classNames.root` that sets `display`: add
|
||||
`[data-ipal="banner"][hidden] { display: none !important }`.
|
||||
4. E2E tests of the project that expect **no** `[data-ipal="banner"]` element before a decision is read (e.g.
|
||||
`toHaveCount(0)` right after `goto` for a returning visitor) must wait for hydration or assert `toBeHidden()`.
|
||||
5. Keep the old behaviour: `<CookieBanner firstPaint={false} />`.
|
||||
**Check:** `curl -s <page> | grep -c 'data-ipal="banner-script"'` → 1; the response still carries `s-maxage`; first
|
||||
visit: the banner is there before the page's scripts have loaded; after a decision and a reload: never shown.
|
||||
|
||||
**→ 1.17.0, e-mail (the Intecion mail service (IWSN in the panel) is the default transport; Microsoft Graph deprecated; CHANGELOG 1.17.0;
|
||||
PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; read which case the site is:**
|
||||
|
||||
@@ -290,6 +290,101 @@ test('consent: reject sets no analytics, the choice is logged', async ({ page })
|
||||
expect(cookies.some((c) => c.name === 'cookie-consent')).toBe(true)
|
||||
})
|
||||
|
||||
// The banner is part of the first render (consent.md → "First paint"): in the static HTML, shown or kept hidden by
|
||||
// an inline script before the browser paints, live after hydration.
|
||||
const watchBanner = () => {
|
||||
const w = window as unknown as { __bannerFrames: number }
|
||||
w.__bannerFrames = 0
|
||||
const tick = () => {
|
||||
const b = document.querySelector<HTMLElement>('[data-ipal="banner"]')
|
||||
if (b && getComputedStyle(b).display !== 'none' && b.getBoundingClientRect().height > 0) {w.__bannerFrames++}
|
||||
requestAnimationFrame(tick)
|
||||
}
|
||||
requestAnimationFrame(tick)
|
||||
}
|
||||
const isAppScript = (url: URL) => url.pathname.startsWith('/_next/static/') && url.pathname.endsWith('.js')
|
||||
|
||||
for (const l of LOCALES) {
|
||||
test(`${l.code}: consent banner is in the static HTML and painted before the page hydrates`, async ({ page, request }) => {
|
||||
const res = await request.get(l.home)
|
||||
const html = await res.text()
|
||||
expect(html).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
|
||||
expect(html).toMatch(/<\/div><script[^>]*data-ipal="banner-script"/)
|
||||
// the page is still a static one: the banner did not make it depend on a cookie
|
||||
expect(res.headers()['cache-control']).toMatch(/s-maxage=\d+/)
|
||||
expect(res.headers()['set-cookie']).toBeUndefined()
|
||||
const withCookie = await request.get(l.home, { headers: { cookie: 'cookie-consent=anything' } })
|
||||
expect((await withCookie.text()).includes('data-ipal="banner"')).toBe(true)
|
||||
|
||||
// no application script at all: nothing hydrates, the inline script alone decides
|
||||
await page.route(isAppScript, (route) => route.abort())
|
||||
await page.goto(l.home)
|
||||
const banner = page.locator('[data-ipal="banner"]')
|
||||
await expect(banner).toBeVisible()
|
||||
await expect(banner.getByRole('button', { name: /^(Odrzuć|Reject)$/ })).toBeVisible()
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
|
||||
})
|
||||
}
|
||||
|
||||
test('consent: a returning visitor never sees the banner, an old policy version asks again; no console errors', async ({ context, page }) => {
|
||||
const errors: string[] = []
|
||||
page.on('console', (m) => {
|
||||
if (m.type() === 'error' || /hydrat/i.test(m.text())) {errors.push(m.text())}
|
||||
})
|
||||
page.on('pageerror', (e) => errors.push(String(e)))
|
||||
await page.goto('/pl')
|
||||
await page.getByRole('button', { name: 'Odrzuć' }).click()
|
||||
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
||||
const stored = (await context.cookies()).find((c) => c.name === 'cookie-consent')!
|
||||
|
||||
await page.addInitScript(watchBanner)
|
||||
for (const path of ['/pl', '/en', '/pl/regulamin']) {
|
||||
await page.goto(path)
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
||||
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
||||
expect(await page.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames), `${path}: frames with the banner shown`).toBe(0)
|
||||
}
|
||||
// without the application scripts too: the inline script hides it before the first paint
|
||||
const bare = await context.newPage()
|
||||
await bare.addInitScript(watchBanner)
|
||||
await bare.route(isAppScript, (route) => route.abort())
|
||||
await bare.goto('/pl')
|
||||
await bare.waitForTimeout(500)
|
||||
expect(await bare.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames)).toBe(0)
|
||||
await bare.close()
|
||||
|
||||
// the same decision under another policy version: asked again, from the first paint
|
||||
const record = JSON.parse(decodeURIComponent(stored.value)) as { version: number }
|
||||
await context.addCookies([{ ...stored, value: encodeURIComponent(JSON.stringify({ ...record, version: record.version + 1 })) }])
|
||||
await page.goto('/pl')
|
||||
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
|
||||
test('consent: a click on the banner before the page has hydrated is not lost', async ({ context, page }) => {
|
||||
let release: () => void = () => {}
|
||||
const held = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
await page.route(isAppScript, async (route) => {
|
||||
await held
|
||||
await route.continue()
|
||||
})
|
||||
await page.goto('/pl', { waitUntil: 'commit' })
|
||||
const reject = page.locator('[data-ipal="reject"]')
|
||||
await expect(reject).toBeVisible()
|
||||
await reject.click()
|
||||
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(false) // the script itself stores nothing
|
||||
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
|
||||
release()
|
||||
expect((await logged).status()).toBe(201)
|
||||
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
||||
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(true)
|
||||
})
|
||||
|
||||
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/)
|
||||
|
||||
Reference in New Issue
Block a user