Theme key 'theme', storage keys in the cookie scanner, type in the cookie list

- Theme choice in localStorage under 'theme' (next-themes' key and values)
  instead of 'ipal-theme'. ThemeScript moves an old choice before the first
  paint and removes the old key; useTheme / ThemeSwitcher do the same
  without the script. ipalKit({ theme: { storageKey } }) sets an own key,
  which reaches ThemeScript through getSiteShell().theme and <html
  data-theme-storage>.
- The cookie scanner declares the theme key (Theme choice: local storage,
  necessary, until changed or site data is cleared) when the theme switch
  is on, so Scan cookies finds it without a crawl.
- Cookies -> Cookie list rows get a Type (cookie / local storage / session
  storage, default cookie, shared by every language), filled by scan, review
  and approval. The detailed settings window and <CookieTable> show it with
  English and Polish defaults; the approval page marks storage entries.
- Migration: adds cookie_settings_cookies.storage (DEFAULT 'cookie') and
  cookie_settings_locales.detail_labels_storage, nothing else.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 11:29:56 +01:00
co-authored by Claude Opus 5.5
parent 6998b44431
commit b5368cdc61
35 changed files with 522 additions and 78 deletions
+33
View File
@@ -8,6 +8,39 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## Unreleased
The theme choice moves to the standard `theme` key, the cookie scanner declares the plugin's own browser-storage
key, and the cookie list tells cookies from browser storage.
### Changed
- **Theme key** `ipal-theme` → **`theme`** (`THEME_STORAGE_KEY`), the key and `light` / `dark` values next-themes uses.
Visitors keep their choice: `<ThemeScript>` moves an old `ipal-theme` value to the new key before the first paint
(no flash) and removes the old key; `useTheme` / `<ThemeSwitcher>` do the same on pages without the script
(`migrateThemeStorage`, `LEGACY_THEME_STORAGE_KEY`). A project that also runs next-themes now shares the key —
set `ipalKit({ theme: { storageKey } })` to keep them apart.
### New
- **`theme.storageKey`** option (`ThemeOptions`): `getSiteShell().theme.storageKey` → `<ThemeScript>` →
`<html data-theme-storage>` (`THEME_STORAGE_ATTRIBUTE`) → `useTheme` / `<ThemeSwitcher>`; both also take `storageKey`.
- **Cookie scanner declares browser storage**: the theme choice (*Theme choice*, on when Site settings → Theme →
*Allow theme toggle* is on) as **necessary**, local storage, "until changed or site data is cleared" — so
**Scan cookies** finds it without a crawl.
- **Type in the cookie list**: *Cookies → Cookie list* rows have **Type** (`storage`: cookie · local storage ·
session storage, default cookie, shared by every language), filled by scan, review and approval. The detailed
settings window shows it for storage entries (heading: *Settings window → Cookie list headings → Type*);
`<CookieTable>` adds a **Type** column when the list has a storage entry (`storageColumn`, `storageTypes`,
`COOKIE_STORAGE_LABELS`). `CookieTableRow.storage`, `texts.details.storage` / `.storageTypes`, type `ConsentStorage`.
The approval page marks storage entries.
### What projects must update
1. **Migration (Postgres / SQLite):** `pnpm payload migrate:create cookie-storage-type` — it only adds
`cookie_settings_cookies.storage` (enum, `DEFAULT 'cookie'`) and `cookie_settings_locales.detail_labels_storage`.
Existing rows become *Cookie*: set the type of storage rows by hand. MongoDB: nothing to do.
2. A project that reads `localStorage.getItem('ipal-theme')` itself: use `THEME_STORAGE_KEY` (or `documentThemeStorageKey()`).
3. Cookie list: after the next **Scan cookies**, approve the new *theme* entry; remove an old *ipal-theme* row from
*Cookies → Cookie list* once the site runs this version.
## 1.14.4
Cookie texts in every language without retyping them, and one **Cookies** entry in the admin instead of three.
+2
View File
@@ -983,6 +983,8 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Cookie check (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie check → Warning e-mails to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
| Cookie admin: one *Cookies* entry — review list and site check as tabs, their own entries out of the navigation (pages and API kept) | `cookieScanner.adminLayout: 'separate'` | `addCookieScannerTabs`, `CookieReviewTab`, `CookieSiteCheckTab`; `collectionOverrides` / `crawl.globalOverride` win |
| Theme choice in localStorage under `theme` (next-themes' key); old `ipal-theme` moved before paint; declared to the cookie scanner as necessary local storage | — | `ipalKit({ theme: { storageKey } })`; `<ThemeSwitcher storageKey>` / `useTheme({ storageKey })` |
| Cookie list entries have a **Type** (cookie / local / session storage), filled by the scanner; `<CookieTable>` shows it when needed | `<CookieTable storageColumn={false}>` | `storageColumn`, `storageTypes`, Cookies → Settings window → Cookie list headings → Type |
| Text written in one language fills the empty languages (cookie list, cookie review), never over a language's own text | `fillEmptyLocales: false` | `fillEmptyLocales: { 'cookie-settings': [...], 'cookie-review': [...] }`; `buildFillEmptyLocalesGlobalHook` / `…CollectionHook` for your own globals and collections |
| Cookie approval: one summary + **Approve and add** (editor+), unknown cookies approved as `marketing` + "Needs description", dashboard reminder while cookies wait; nothing reaches the cookie banner before approval | `cookieScanner.approval: false` (per-entry review) | `approval.unknownCategory`, `approval.dashboard: false`; building blocks `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `sameCookie` |
| Cookie review: scan + review editor+, delete admin; Open Cookie Database "Functional" → `functional` | omit `cookieScanner` | `cookieScanner.access`, `collectionOverrides`, `databaseCategories`, `integrations`, `declarations`, `labels`, `syncAccepted: false`; building blocks `runCookieScan`, `collectCookieFindings`, `applyCookieFindings` |
@@ -130,4 +130,4 @@ unknown names to the panel scan above instead of step 2):
table" block on the policy page is a good place — then the editor decides where it appears.
Lifetime: Chrome caps every cookie at max. 400 days (13 months) — the scan shows what
really stays in the browser. localStorage keys (e.g. `ipal-theme` — the chosen theme) are listed separately.
really stays in the browser. localStorage keys (e.g. `theme` — the chosen theme) are listed separately; in the panel they are entries of type *Local storage* (the scanner declares the theme key itself when the theme switch is on). Check that every storage row in *Cookies → Cookie list* has the right **Type** — rows from before the type existed are *Cookie*.
@@ -76,6 +76,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `cookieScanner.crawl.serviceUrl` / `.token` / `.siteUrl` / `.maxPages` / `.acceptSelector` | env URL / env token / `serverURL` → `NEXT_PUBLIC_SERVER_URL` / `20` / `[data-ipal="accept"]` | where the service is, the shared secret, the public origin crawled and called back, pages from the sitemap (max 100), the banner's accept button | options win over env |
| `cookieScanner.crawl.consentMode` / `.trackerHosts` / `.dashboard` / `.globalOverride` | `'advanced'` / `DEFAULT_TRACKER_HOSTS` / `true` / none | `'basic'` also flags Google tag requests before consent; hosts counted as trackers; dashboard warning; changes the `cookie-crawl` global like `globalOverrides` | `(defaults) => [...defaults, 'chat.example']`; `dashboard: false` |
| `cookieScanner.database` / `.databaseCategories` / `.syncAccepted` | `true` / Functional+Personalization → functional, Security+Necessary → necessary / `true` | Open Cookie Database lookup on or off; category map; accepting writes to Cookie banner | `database: false`; `{ Functional: 'necessary' }`; `syncAccepted: false` |
| `theme.storageKey` | `'theme'` | localStorage key of the visitor's light / dark choice (next-themes uses the same key — set your own to keep them apart); via `config.custom.ipal.themeStorageKey` → `getSiteShell().theme.storageKey` → `ThemeScript` → `<html data-theme-storage>` → `useTheme` / `ThemeSwitcher`. An old `ipal-theme` choice moves before the first paint | `{ storageKey: 'acme-theme' }`; check: DevTools → Application → Local storage shows the key after a switch |
| `stats` | off | `stats-visits` collection, `POST /api/ipal/hit`, `/<admin>/stats` view, nav link, dashboard chart | `true` / object |
| `stats.collectionOverrides` | none | changes `stats-visits` like `consentLog.collectionOverrides`; its `access.read` also decides who sees the stats view and dashboard chart | object or function |
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
@@ -113,7 +113,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `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. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Prop `className`. |
| `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, categories?, caption?, classNames? }`; `rows` from `getCookieTable()`. |
| `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). |
| `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`. |
@@ -134,9 +134,9 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildConsentLogCollection()` | `@intecion/ipal-kit` | Consent log collection (id, choices, version, time — no IP/personal data; proof of consent under GDPR Art. 7(1)). The plugin wires it itself with `consentLog: true` — do not call. |
| `buildConsentLogEndpoint({ retentionDays? })` | `@intecion/ipal-kit` | `POST /api/ipal/consent` endpoint that saves decisions and deletes records older than `retentionDays` (default 1095). The plugin wires it itself with `consentLog` — do not call. |
**Built-in texts:** `CONSENT_FALLBACK`, `CONSENT_FALLBACK_PL`, `consentFallback(locale)` (banner defaults by page language), `CONSENT_CATEGORY_LABELS` / `consentCategoryOptions()` (category names `{ en, pl }`), `COOKIE_TABLE_LABELS` (`/rsc`, `<CookieTable locale>` defaults).
**Built-in texts:** `CONSENT_FALLBACK`, `CONSENT_FALLBACK_PL`, `consentFallback(locale)` (banner defaults by page language), `CONSENT_CATEGORY_LABELS` / `consentCategoryOptions()` (category names `{ en, pl }`), `COOKIE_TABLE_LABELS` (`/rsc`, `<CookieTable locale>` defaults), `COOKIE_STORAGE_LABELS` (`/rsc`, type names per language).
**Types:** `ConsentCategory`, `ConsentState`, `ConsentTexts`, `CookieTableRow`, `ConsentLogOptions` (root) — categories, consent state, banner texts, cookie table row, log options; `CookieBannerAction`, `CookieSettingsAction`, `CookieBannerClassNames` (`/client`) — `CookieBanner` buttons and classes; `CookieTableLabels` (`/rsc`) — `CookieTable` column headers.
**Types:** `ConsentCategory`, `ConsentState`, `ConsentStorage` (`'cookie' \| 'localStorage' \| 'sessionStorage'`), `ConsentTexts`, `CookieTableRow`, `ConsentLogOptions` (root) — categories, consent state, banner texts, cookie table row, log options; `CookieBannerAction`, `CookieSettingsAction`, `CookieBannerClassNames` (`/client`) — `CookieBanner` buttons and classes; `CookieTableLabels` (`/rsc`) — `CookieTable` column headers.
## Cookie scanner (`consent/scanner`) — details: `node_modules/@intecion/ipal-kit/docs/cookie-scanner.md`
@@ -682,19 +682,23 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP
| Export | Import from | What it does / when |
|---|---|---|
| `ThemeScript({ allowToggle?, defaultTheme? })` | `@intecion/ipal-kit/rsc` | Inline script that sets `data-theme` on `<html>` before paint (no flash). First in `<body>` or `theme` in `<SiteProviders>`; `<html suppressHydrationWarning>`. |
| `ThemeSwitcher({ label?, classNames?, renderIcon? })` | `@intecion/ipal-kit/client` | Unstyled switcher (`<button role="switch">`, light/dark icons); style the active icon in CSS (`[data-theme=dark]`). |
| `useTheme()` | `@intecion/ipal-kit/client` | Hook `{ theme, setTheme, toggle }`; `theme` = null on the server — do not style from it. |
| `applyTheme(theme, { persist?, transitionMs? })` | `@intecion/ipal-kit/client` | Sets the theme on `<html>` and remembers it in localStorage. |
| `ThemeSwitcher({ label?, classNames?, renderIcon?, storageKey? })` | `@intecion/ipal-kit/client` | Unstyled switcher (`<button role="switch">`, light/dark icons); style the active icon in CSS (`[data-theme=dark]`). |
| `useTheme({ storageKey? })` | `@intecion/ipal-kit/client` | Hook `{ theme, setTheme, toggle }`; `theme` = null on the server — do not style from it. Key: the one on `<html data-theme-storage>`, else `theme`. |
| `applyTheme(theme, { persist?, storageKey?, transitionMs? })` | `@intecion/ipal-kit/client` | Sets the theme on `<html>` and remembers it in localStorage. |
| `documentThemeStorageKey()` | `@intecion/ipal-kit/client` | The key the page uses: `<html data-theme-storage>` (set by `ThemeScript` for a custom key), else `'theme'`. |
| `migrateThemeStorage(key?)` | `@intecion/ipal-kit/client` | Moves an old `ipal-theme` choice to `key` when `key` is empty, removes `ipal-theme`; never throws. `ThemeScript` does it before the first paint. |
| `readDocumentTheme()` | `@intecion/ipal-kit/client` | Current theme from `<html>` or null. |
| `themeConfigFrom(settings)` | `@intecion/ipal-kit` | Theme options from the SiteSettings document (what `getSiteShell(locale).theme` holds). |
| `themeScript({ allowToggle, defaultTheme })` | `@intecion/ipal-kit` | The script content that `ThemeScript` renders — when you insert it yourself. |
| `themeConfigFrom(settings, storageKey?)` | `@intecion/ipal-kit` | Theme options from the SiteSettings document (what `getSiteShell(locale).theme` holds). |
| `themeScript({ allowToggle, defaultTheme, storageKey? })` | `@intecion/ipal-kit` | The script content that `ThemeScript` renders — when you insert it yourself. |
| `isTheme(value)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Type guard `'light' \| 'dark'`. |
| `isThemeSetting(value)` | `@intecion/ipal-kit` | Type guard `'system' \| 'light' \| 'dark'`. |
| `THEME_ATTRIBUTE` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'data-theme'` — attribute on `<html>` (Tailwind `dark` variant). |
| `THEME_STORAGE_KEY` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'ipal-theme'` — localStorage key with the visitor's choice. |
| `THEME_STORAGE_KEY` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'theme'` — default localStorage key with the visitor's choice (the next-themes key; `ipalKit({ theme: { storageKey } })` changes it). |
| `LEGACY_THEME_STORAGE_KEY` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'ipal-theme'` — the key before; a choice under it is moved once. |
| `THEME_STORAGE_ATTRIBUTE` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'data-theme-storage'` — on `<html>` when the key is not the default. |
| `THEME_SWITCHING_ATTRIBUTE` | `@intecion/ipal-kit/client` | `'data-theme-switching'` — briefly on `<html>` while switching (for the colour transition). |
**Types:** `Theme`, `ThemeSetting`, `ThemeConfig` (root, `/client`) — theme, setting from the panel and theme options; `ThemeScriptProps` (`/rsc`), `ThemeSwitcherProps`, `ThemeSwitcherClassNames` (`/client`) — component props.
**Types:** `ThemeOptions` (root, `ipalKit({ theme })`), `Theme`, `ThemeSetting`, `ThemeConfig` (root, `/client`) — theme, setting from the panel and theme options; `ThemeScriptProps` (`/rsc`), `ThemeSwitcherProps`, `ThemeSwitcherClassNames` (`/client`) — component props.
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
+17
View File
@@ -332,6 +332,23 @@ independent consent state).
> The consent mechanism for the locale is also described from the i18n side:
> [i18n.md](./i18n.md#locale-cookie-and-consent-gdpr).
## Cookies and browser storage in one list (type)
*Cookies → Cookie list* holds cookies **and** keys the site keeps in the browser's local or session
storage (the theme choice, a chat widget's state). Each row has a **Type** (`storage`: `cookie` ·
`localStorage` · `sessionStorage`, default `cookie`, shared by every language). The cookie scanner fills it.
| Where | What visitors see |
|---|---|
| `<CookieTable>` (`/rsc`) | a **Type** column when the list has an entry that is not a cookie (`storageColumn: 'auto'`, the default; `true` / `false` to force it). Column heading `labels.storage`, type names `storageTypes` — defaults per `locale`: en *Type* · *Cookie* / *Local storage* / *Session storage*, pl `Rodzaj` · `Plik cookie` / `Pamięć lokalna` / `Pamięć sesji` (`COOKIE_STORAGE_LABELS`) |
| Detailed settings window | a **Type** line under entries that are not cookies: label from *Settings window → Cookie list headings → Type* (empty = default per language), type names from `texts.details.storageTypes` |
| `getCookieTable` / `texts.cookies` | every row has `storage` (`ConsentStorage`); `texts.details.storage` / `.storageTypes` |
**Migration (Postgres / SQLite):** two added columns, nothing dropped — `cookie_settings_cookies.storage`
(enum, `DEFAULT 'cookie'`, so existing rows become *Cookie*) and `cookie_settings_locales.detail_labels_storage`.
Run `pnpm payload migrate:create cookie-storage-type` and commit it. Change the type of existing storage rows
by hand (a scan fills it only for new rows).
## Every language filled (`fillEmptyLocales`)
The cookie list's **Purpose** and **Duration** are per language. Text an editor writes in one language
+11 -3
View File
@@ -109,6 +109,7 @@ integrations switched on in this project are part of a scan:
| Integration | On when | Cookies |
|---|---|---|
| Cookie banner | always | `cookie-consent` (necessary, 6 months) |
| Theme choice | Site settings → Theme → *Allow theme toggle* on | `theme` (or `theme.storageKey`) in **local storage** — necessary (a preference the visitor chose), until changed or site data is cleared, may be set before consent |
| Admin panel login | always | `payload-token` (`<cookiePrefix>-token`, necessary, editors only) |
| Language choice | more than one locale in `i18n` | `NEXT_LOCALE` (functional, session) |
| Built-in statistics | `stats` option | `ipal_vid` (analytics, 6 months) |
@@ -120,9 +121,16 @@ integrations switched on in this project are part of a scan:
| TikTok Pixel | Pixel ID | `_ttp`, `_tt_enable_cookie` |
| Cloudflare Turnstile | both Turnstile keys set | `cf_clearance` (necessary; only when pre-clearance is on in Cloudflare) |
An ID that fails its format check counts as off. The theme switcher (`ipal-theme` in localStorage)
and the accessibility widget (`a11y-prefs`) have no plugin option, so they are not declared: add
them with `declarations` when the site uses them.
An ID that fails its format check counts as off. Declarations cover browser storage too
(`storage: 'localStorage' | 'sessionStorage'`): the theme choice is the plugin's only storage key.
The accessibility widget (`a11y-prefs` cookie) has no plugin option the scan could check, so it is not
declared: add it with `declarations` when the site uses the widget.
Every entry keeps its type (cookie, local storage, session storage) from the scan through the review and
approval into *Cookies → Cookie list* (**Type** column; shared by all languages, default *Cookie*). The
banner's detailed window shows the type for entries that are not cookies, and `<CookieTable>` adds a
**Type** column when the list has one ([consent.md](./consent.md)). A row that was already in the list
keeps the type it has; rows from before the type existed are *Cookie* — set storage rows by hand.
## Open Cookie Database
+21 -7
View File
@@ -9,11 +9,23 @@ widget theme that matches the page.
- Pages are ISR/SSG — one HTML for everyone, so the theme does **not** go into the server HTML.
- `<ThemeScript>` (an inline script, the first child of `<body>`) sets `data-theme="light|dark"` and
`color-scheme` on `<html>` before the first paint.
- Order: the visitor's choice from `localStorage` (key `ipal-theme`, only when "Allow theme toggle" is on)
- Order: the visitor's choice from `localStorage` (key `theme`, only when "Allow theme toggle" is on)
→ Site settings → Default theme → with `System`, the device setting (`prefers-color-scheme`).
- `localStorage`, not a cookie: it is an interface preference, it does not track and needs no consent.
- `localStorage`, not a cookie: it is an interface preference the visitor chose themselves, it does not
track and needs no separate consent (CNIL treats such a preference as strictly necessary). The cookie
scanner declares it as **necessary**, local storage — an editor can change that on review.
- A change in one tab carries over to the others (the `storage` event).
## The storage key (`theme`)
| | |
|---|---|
| Default key | `theme`, values `light` / `dark` — the key and values next-themes uses (`THEME_STORAGE_KEY`) |
| Own key | `ipalKit({ theme: { storageKey: 'acme-theme' } })` → `getSiteShell(locale).theme.storageKey` → `<ThemeScript>` uses it and puts it on `<html data-theme-storage>`, so `useTheme` / `<ThemeSwitcher>` use the same key with no extra prop (`<ThemeSwitcher storageKey>` / `useTheme({ storageKey })` to set it by hand) |
| Old key | before this change the key was `ipal-theme` (`LEGACY_THEME_STORAGE_KEY`). When the current key is empty and `ipal-theme` holds `light` / `dark`, `<ThemeScript>` moves it **before the first paint** (no flash) and removes `ipal-theme`; `useTheme` / `<ThemeSwitcher>` do the same on pages without the script (`migrateThemeStorage(key)`). A choice already under the current key wins; the old key is removed anyway |
| next-themes | a project that also runs next-themes shares the key `theme` with it — one choice for both. To keep them apart, give the plugin its own key (`theme.storageKey`) |
| CSP | the inline script runs with the CSP nonce (`<ThemeScript nonce>`, `SiteProviders` passes it); no script hash to update |
## Site settings → Theme
| Field | Meaning |
@@ -22,7 +34,7 @@ widget theme that matches the page.
| `allowThemeToggle` | show the switcher; the visitor's choice is remembered |
| `themeToggleLabel` | the switcher name for screen readers, e.g. "Tryb ciemny" (localized, since 1.11.1) |
`getSiteShell(locale).theme` → `{ defaultTheme, allowToggle, toggleLabel }` (`themeConfigFrom(settings)` from the root entry).
`getSiteShell(locale).theme` → `{ defaultTheme, allowToggle, toggleLabel, storageKey? }` (`themeConfigFrom(settings, storageKey?)` from the root entry; `storageKey` only when it is not the default).
## Wiring
@@ -60,10 +72,12 @@ import { ThemeSwitcher } from '@intecion/ipal-kit/client'
from the attribute on `<html>` (`dark:`), not React state — nothing jumps after hydration.
Hooks for styling: `data-ipal="theme-switch"`, `data-ipal-theme-icon="light|dark"`.
Custom switcher: `useTheme()` → `{ theme, setTheme, toggle }` (`theme` = `null` on the server);
`applyTheme(theme, { persist, transitionMs })`, `readDocumentTheme()`, the constants `THEME_ATTRIBUTE`,
`THEME_STORAGE_KEY`, `THEME_SWITCHING_ATTRIBUTE`, `isTheme` from `/client`. From the root entry also
`isThemeSetting` and `themeScript({ allowToggle, defaultTheme })` (the script text only).
Custom switcher: `useTheme({ storageKey? })` → `{ theme, setTheme, toggle }` (`theme` = `null` on the server);
`applyTheme(theme, { persist, storageKey, transitionMs })`, `readDocumentTheme()`, `documentThemeStorageKey()`,
`migrateThemeStorage(key)`, the constants `THEME_ATTRIBUTE`, `THEME_STORAGE_KEY`, `LEGACY_THEME_STORAGE_KEY`,
`THEME_STORAGE_ATTRIBUTE`, `THEME_SWITCHING_ATTRIBUTE`, `isTheme` from `/client`. From the root entry also
`isThemeSetting` and `themeScript({ allowToggle, defaultTheme, storageKey })` (the script text only), and the
type `ThemeOptions` (`ipalKit({ theme })`).
## CSS (Tailwind 4)
+10 -1
View File
@@ -93,7 +93,16 @@ export type { NoSnippetProps } from '../modules/seo/NoSnippet.js'
export { PageStats, VISITOR_COOKIE } from '../modules/stats/client.js'
export type { PageStatsProps } from '../modules/stats/client.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { isTheme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from '../modules/theme/theme.js'
export {
documentThemeStorageKey,
isTheme,
LEGACY_THEME_STORAGE_KEY,
migrateThemeStorage,
THEME_ATTRIBUTE,
THEME_STORAGE_ATTRIBUTE,
THEME_STORAGE_KEY,
THEME_SWITCHING_ATTRIBUTE,
} from '../modules/theme/theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from '../modules/theme/theme.js'
export { ThemeSwitcher } from '../modules/theme/ThemeSwitcher.js'
export type { ThemeSwitcherClassNames, ThemeSwitcherProps } from '../modules/theme/ThemeSwitcher.js'
+1 -1
View File
@@ -12,7 +12,7 @@ export type {
EnhanceProps,
RenderBlocksProps,
} from '../modules/blocks/index.js'
export { COOKIE_TABLE_LABELS, CookieTable } from '../modules/consent/CookieTable.js'
export { COOKIE_STORAGE_LABELS, COOKIE_TABLE_LABELS, CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/RenderForm.js'
export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
+23 -1
View File
@@ -169,6 +169,16 @@ export const cookieSettingsFields: Field[] = [
{ name: 'duration', type: 'text', admin: { placeholder: { en: 'Duration', pl: 'Okres' } }, label: { en: 'Duration', pl: 'Okres' }, localized: true },
],
},
{
name: 'storage',
type: 'text',
admin: {
description: { en: 'Shown only for entries kept in browser storage.', pl: 'Widoczne tylko przy wpisach w pamięci przeglądarki.' },
placeholder: { en: 'Type', pl: 'Rodzaj' },
},
label: { en: 'Type', pl: 'Rodzaj' },
localized: true,
},
],
label: { en: 'Cookie list headings', pl: 'Nagłówki listy cookies' },
},
@@ -222,7 +232,18 @@ export const cookieSettingsFields: Field[] = [
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { placeholder: '_ga', width: '40%' }, label: { en: 'Name', pl: 'Nazwa' }, required: true },
{ name: 'provider', type: 'text', admin: { placeholder: 'Google', width: '30%' }, label: { en: 'Provider', pl: 'Dostawca' } },
{
name: 'storage',
type: 'select',
admin: { width: '30%' },
defaultValue: 'cookie',
label: { en: 'Type', pl: 'Rodzaj' },
options: [
{ label: { en: 'Cookie', pl: 'Plik cookie' }, value: 'cookie' },
{ label: { en: 'Local storage', pl: 'Pamięć lokalna' }, value: 'localStorage' },
{ label: { en: 'Session storage', pl: 'Pamięć sesji' }, value: 'sessionStorage' },
],
},
{
name: 'category',
type: 'select',
@@ -234,6 +255,7 @@ export const cookieSettingsFields: Field[] = [
},
],
},
{ name: 'provider', type: 'text', admin: { placeholder: 'Google' }, label: { en: 'Provider', pl: 'Dostawca' } },
{ name: 'purpose', type: 'textarea', label: { en: 'Purpose', pl: 'Cel' }, localized: true },
{
name: 'duration',
+3 -3
View File
@@ -58,7 +58,7 @@ export {
setDefaultConsent,
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentStorage, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
// Cookie scanner — review list, scan, declarations, Open Cookie Database lookup (docs/cookie-scanner.md).
export {
addCookieScannerTabs,
@@ -372,11 +372,11 @@ export type { StatsOptions, StatsPage, StatsVisit } from './modules/stats/index.
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js'
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, themeConfigFrom, themeScript } from './modules/theme/index.js'
export { isTheme, isThemeSetting, LEGACY_THEME_STORAGE_KEY, THEME_ATTRIBUTE, THEME_STORAGE_ATTRIBUTE, THEME_STORAGE_KEY, themeConfigFrom, themeScript } from './modules/theme/index.js'
export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js'
// Imported from the file, not the turnstile barrel — that one re-exports verify,
// which imports 'server-only'.
export { getTurnstileConfig } from './modules/turnstile/config.js'
export type { TurnstileConfig } from './modules/turnstile/config.js'
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export type { IpalOptions, ThemeOptions } from './types.js'
+2
View File
@@ -7,6 +7,7 @@ export const consentTexts = defineTexts({
cookieIntegrationConsent: 'Cookie banner',
cookieIntegrationLocale: 'Language choice',
cookieIntegrationStats: 'Built-in statistics',
cookieIntegrationTheme: 'Theme choice',
cookieSourceProject: 'Project',
},
pl: {
@@ -14,6 +15,7 @@ export const consentTexts = defineTexts({
cookieIntegrationConsent: 'Baner cookies',
cookieIntegrationLocale: 'Wybór języka',
cookieIntegrationStats: 'Wbudowane statystyki',
cookieIntegrationTheme: 'Wybór motywu',
cookieSourceProject: 'Projekt',
},
})
+6
View File
@@ -337,6 +337,12 @@ export function CookieBanner({
<dd>{row.duration}</dd>
</>
)}
{row.storage && row.storage !== 'cookie' && labels.storage && (
<>
<dt>{labels.storage}</dt>
<dd>{labels.storageTypes?.[row.storage] ?? row.storage}</dd>
</>
)}
</dl>
</li>
))}
+25 -5
View File
@@ -1,5 +1,5 @@
import type { CookieTableRow } from './getConsentTexts.js'
import type { ConsentTexts } from './texts.js'
import type { ConsentStorage, ConsentTexts } from './texts.js'
export type CookieTableLabels = {
category: string
@@ -7,12 +7,20 @@ export type CookieTableLabels = {
name: string
provider: string
purpose: string
/** "Type" column (cookie / local storage / session storage). */
storage: string
}
/** Default column headings, per language. */
export const COOKIE_TABLE_LABELS: { en: CookieTableLabels; pl: CookieTableLabels } = {
en: { name: 'Cookie', category: 'Category', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' },
pl: { name: 'Plik cookie', category: 'Kategoria', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel' },
en: { name: 'Cookie', category: 'Category', duration: 'Duration', provider: 'Provider', purpose: 'Purpose', storage: 'Type' },
pl: { name: 'Plik cookie', category: 'Kategoria', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel', storage: 'Rodzaj' },
}
/** Default names of the storage types, per language. */
export const COOKIE_STORAGE_LABELS: { en: Record<ConsentStorage, string>; pl: Record<ConsentStorage, string> } = {
en: { cookie: 'Cookie', localStorage: 'Local storage', sessionStorage: 'Session storage' },
pl: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' },
}
type CookieTableProps = {
@@ -31,6 +39,13 @@ type CookieTableProps = {
locale?: string
/** From getCookieTable({ payload, locale }) — Cookie Settings → Cookies. */
rows: CookieTableRow[]
/**
* The "Type" column. Default `'auto'`: shown when the list has an entry that is
* not a cookie (local / session storage). `true` always, `false` never.
*/
storageColumn?: 'auto' | boolean
/** Names of the types — default per `locale` (e.g. `texts.details.storageTypes`). */
storageTypes?: Partial<Record<ConsentStorage, string>>
}
/**
@@ -42,15 +57,19 @@ type CookieTableProps = {
* const rows = await getCookieTable({ payload, locale })
* <CookieTable rows={rows} locale={locale} categories={texts.categories} /> // labels={…} to change the headings
*/
export function CookieTable({ caption, categories, classNames = {}, labels: given, locale, rows }: CookieTableProps) {
export function CookieTable({ caption, categories, classNames = {}, labels: given, locale, rows, storageColumn = 'auto', storageTypes }: CookieTableProps) {
if (rows.length === 0) {return null}
const labels = { ...(locale?.toLowerCase().startsWith('pl') ? COOKIE_TABLE_LABELS.pl : COOKIE_TABLE_LABELS.en), ...Object.fromEntries(Object.entries(given ?? {}).filter(([, v]) => v)) }
const pl = locale?.toLowerCase().startsWith('pl')
const labels = { ...(pl ? COOKIE_TABLE_LABELS.pl : COOKIE_TABLE_LABELS.en), ...Object.fromEntries(Object.entries(given ?? {}).filter(([, v]) => v)) }
const types = { ...(pl ? COOKIE_STORAGE_LABELS.pl : COOKIE_STORAGE_LABELS.en), ...storageTypes }
const showStorage = storageColumn === 'auto' ? rows.some((r) => r.storage && r.storage !== 'cookie') : storageColumn
return (
<table className={classNames.table}>
{caption ? <caption className={classNames.caption}>{caption}</caption> : null}
<thead>
<tr className={classNames.tr}>
<th className={classNames.th} scope="col">{labels.name}</th>
{showStorage ? <th className={classNames.th} scope="col">{labels.storage}</th> : null}
<th className={classNames.th} scope="col">{labels.provider}</th>
<th className={classNames.th} scope="col">{labels.category}</th>
<th className={classNames.th} scope="col">{labels.purpose}</th>
@@ -61,6 +80,7 @@ export function CookieTable({ caption, categories, classNames = {}, labels: give
{rows.map((row) => (
<tr className={classNames.tr} key={`${row.category}:${row.name}`}>
<td className={classNames.td}><code>{row.name}</code></td>
{showStorage ? <td className={classNames.td}>{types[row.storage ?? 'cookie']}</td> : null}
<td className={classNames.td}>{row.provider ?? ''}</td>
<td className={classNames.td}>{categories?.[row.category]?.title ?? row.category}</td>
<td className={classNames.td}>{row.purpose ?? ''}</td>
+21 -4
View File
@@ -28,7 +28,14 @@ export const CONSENT_FALLBACK: ConsentTexts = {
title: 'Necessary',
},
},
details: { cookies: 'Cookies used', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' },
details: {
cookies: 'Cookies used',
duration: 'Duration',
provider: 'Provider',
purpose: 'Purpose',
storage: 'Type',
storageTypes: { cookie: 'Cookie', localStorage: 'Local storage', sessionStorage: 'Session storage' },
},
message:
'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow.',
privacyLink: null,
@@ -54,7 +61,14 @@ export const CONSENT_FALLBACK_PL: ConsentTexts = {
title: 'Niezbędne',
},
},
details: { cookies: 'Używane cookies', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel' },
details: {
cookies: 'Używane cookies',
duration: 'Okres',
provider: 'Dostawca',
purpose: 'Cel',
storage: 'Rodzaj',
storageTypes: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' },
},
message:
'Używamy plików cookies, aby witryna działała, aby analizować ruch i ulepszać witrynę. Można zaakceptować wszystkie, odrzucić te, które nie są niezbędne, lub wybrać je samodzielnie.',
privacyLink: null,
@@ -79,8 +93,8 @@ type CookieSettingsData = {
savePreferences?: null | string
} & Partial<Omit<ConsentTexts['buttons'], 'save'>>) | null
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
detailLabels?: null | Partial<Record<keyof NonNullable<ConsentTexts['details']>, null | string>>
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string; storage?: null | string }> | null
detailLabels?: null | Partial<Record<Exclude<keyof NonNullable<ConsentTexts['details']>, 'storageTypes'>, null | string>>
eyebrow?: null | string
message?: null | string
policyVersion?: null | number
@@ -192,6 +206,8 @@ export async function getConsentTexts({
duration: g.detailLabels?.duration?.trim() || FALLBACK.details!.duration,
provider: g.detailLabels?.provider?.trim() || FALLBACK.details!.provider,
purpose: g.detailLabels?.purpose?.trim() || FALLBACK.details!.purpose,
storage: g.detailLabels?.storage?.trim() || FALLBACK.details!.storage,
storageTypes: FALLBACK.details!.storageTypes,
},
message: g.message || FALLBACK.message,
privacyLink,
@@ -217,6 +233,7 @@ function toCookieRows(cookies: CookieSettingsData['cookies']): CookieTableRow[]
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
...(c.storage === 'localStorage' || c.storage === 'sessionStorage' ? { storage: c.storage } : { storage: 'cookie' as const }),
}))
}
+1 -1
View File
@@ -23,4 +23,4 @@ export {
readConsentRecord,
serializeConsent,
} from './storage.js'
export type { ConsentTexts } from './texts.js'
export type { ConsentStorage, ConsentTexts } from './texts.js'
@@ -124,6 +124,7 @@ export function CookieApprovalForm({
{p.change === 'new' ? <span className="ipal-badge ipal-badge--new">{t.markerNew}</span> : null}
{p.change === 'changed' ? <span className="ipal-badge ipal-badge--changed">{t.markerChanged}</span> : null}
{p.unknown ? <span className="ipal-badge ipal-badge--unknown">{t.markerUnknown}</span> : null}
{p.storage && p.storage !== 'cookie' ? <span className="ipal-badge">{t[p.storage]}</span> : null}
</div>
</td>
<td>{p.vendor ?? ''}</td>
+5 -1
View File
@@ -3,7 +3,7 @@ import type { BasePayload, Endpoint, PayloadRequest, Where } from 'payload'
import type { ConsentCategory } from '../categories.js'
import type { CookieReviewValues } from './merge.js'
import type { CookieChange } from './scan.js'
import type { CookieScannerOptions } from './types.js'
import type { CookieScannerOptions, CookieStorage } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { CONSENT_CATEGORIES } from '../categories.js'
@@ -30,6 +30,8 @@ export type CookieApprovalItem = {
name: string
purpose: null | string
retention: null | string
/** Cookie, or a key in the browser's local / session storage. */
storage: CookieStorage
/** Nothing knew it: no category or no purpose yet. */
unknown: boolean
vendor: null | string
@@ -53,6 +55,7 @@ type Doc = {
retention?: null | Record<string, null | string> | string
source?: null | string
status?: 'accepted' | 'draft' | 'rejected' | null
storage?: CookieStorage | null
vendor?: null | string
}
@@ -73,6 +76,7 @@ function item(doc: Doc, locale: string): CookieApprovalItem {
change: doc.change ?? null,
purpose,
retention: asText(doc.retention, locale),
storage: doc.storage ?? 'cookie',
unknown: !doc.category || !purpose || doc.source === 'unknown',
vendor: doc.vendor ?? null,
}
@@ -4,6 +4,7 @@ import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './
import { adminTexts } from '../../admin-i18n/texts/index.js'
import { validAnalyticsId } from '../../analytics/idFormats.js'
import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js'
import { THEME_STORAGE_KEY } from '../../theme/theme.js'
import { getTurnstileConfig } from '../../turnstile/config.js'
import { CONSENT_COOKIE } from '../storage.js'
import { textFor } from './merge.js'
@@ -19,6 +20,17 @@ const months = (n: number) => T(`${n} months`, `${n} mies.`)
const YEAR = T('1 year', '1 rok')
const TWO_YEARS = T('2 years', '2 lata')
const SITE = 'This site'
const UNTIL_CHANGED = T('Until changed or site data is cleared', 'Do zmiany lub wyczyszczenia danych witryny')
/** Site Settings → Theme → visitors may switch: only then is the choice stored. */
async function themeToggleOn(ctx: CookieScanContext): Promise<boolean> {
try {
const settings = (await ctx.payload.findGlobal({ slug: 'site-settings' as never, depth: 0 })) as { allowThemeToggle?: boolean }
return settings.allowThemeToggle === true
} catch {
return false
}
}
/** A name from the shared admin texts, in every admin language the plugin ships. */
const A = (key: AdminTextKey) => ({ en: adminTexts.en[key], pl: adminTexts.pl[key] })
@@ -47,6 +59,24 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [
key: 'consent',
label: A('cookieIntegrationConsent'),
},
{
// Browser storage, not a cookie: the light / dark choice the visitor made themselves —
// a preference they asked for, so necessary (no separate consent); editable in review.
declarations: (ctx) => [
{
name: ctx.plugin.themeStorageKey || THEME_STORAGE_KEY,
category: 'necessary',
purpose: T('Remembers the light or dark theme you chose.', 'Zapamiętuje wybrany motyw: jasny lub ciemny.'),
retention: UNTIL_CHANGED,
setBeforeConsent: true,
storage: 'localStorage',
vendor: SITE,
},
],
isEnabled: themeToggleOn,
key: 'theme',
label: A('cookieIntegrationTheme'),
},
{
declarations: (ctx) => [
{
+11 -2
View File
@@ -11,9 +11,10 @@ type Row = {
name?: null | string
provider?: null | string
purpose?: null | string
storage?: null | string
}
type Entry = { name: string } & CookieReviewValues
type Entry = { name: string; storage?: null | string } & CookieReviewValues
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
@@ -64,6 +65,7 @@ export async function addToCookieList({
duration: text(entry.retention, locale),
provider: entry.vendor ?? null,
purpose: text(entry.purpose, locale),
storage: entry.storage ?? 'cookie',
})
changed = true
result = 'added'
@@ -74,7 +76,14 @@ export async function addToCookieList({
changed = true
}
}
if (i === 0) {fill('provider', entry.vendor)}
if (i === 0) {
fill('provider', entry.vendor)
// A row from before the type existed has none; the type is shared by every language.
if (empty(row.storage) && entry.storage) {
row.storage = entry.storage
changed = true
}
}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
if (changed && result === 'unchanged') {result = 'filled'}
+2 -1
View File
@@ -38,7 +38,8 @@ export type CookieScanContext = {
language?: string
payload: BasePayload
/** Plugin options that switch modules on. */
plugin: { localeCount: number; stats: boolean }
/** Plugin options that switch modules on; `themeStorageKey` = `ipalKit({ theme: { storageKey } })`. */
plugin: { localeCount: number; stats: boolean; themeStorageKey?: string }
}
/**
+9
View File
@@ -1,5 +1,8 @@
import type { ConsentCategory } from './categories.js'
/** Where an entry of the cookie list is kept in the browser. */
export type ConsentStorage = 'cookie' | 'localStorage' | 'sessionStorage'
export type ConsentTexts = {
/** Badge next to the necessary category (e.g. "Always active"). Empty = no badge. */
alwaysActiveLabel?: string
@@ -26,6 +29,10 @@ export type ConsentTexts = {
duration: string
provider: string
purpose: string
/** Label of the type line, e.g. "Type" — shown for entries that are not cookies. */
storage?: string
/** Names of the types, e.g. { cookie: 'Cookie', localStorage: 'Local storage', … }. */
storageTypes?: Record<ConsentStorage, string>
}
/** Small label above the banner title (e.g. "Privacy & cookies"). Empty = not shown. */
eyebrow?: string
@@ -48,4 +55,6 @@ export type CookieTableRow = {
name: string
provider?: string
purpose?: string
/** Cookie (default) or a browser-storage key. */
storage?: ConsentStorage
}
+1 -1
View File
@@ -833,7 +833,7 @@ export function createContentHelpers({
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
lightboxTexts: notifications.lightbox,
settings: settings ?? {},
theme: themeConfigFrom(settings),
theme: themeConfigFrom(settings, (payload.config.custom as { ipal?: { themeStorageKey?: string } } | undefined)?.ipal?.themeStorageKey),
turnstileSiteKey: turnstile.siteKey,
}
})
+3 -3
View File
@@ -5,7 +5,7 @@ import { themeScript } from './theme.js'
export type ThemeScriptProps = {
/** CSP nonce (createProxy `csp` → `x-nonce` header) — needed when the policy uses nonces. */
nonce?: string
} & Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
} & Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme' | 'storageKey'>>
/**
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
@@ -15,7 +15,7 @@ export type ThemeScriptProps = {
* const shell = await getSiteShell(locale)
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
*/
export function ThemeScript({ allowToggle = false, defaultTheme = null, nonce }: ThemeScriptProps) {
export function ThemeScript({ allowToggle = false, defaultTheme = null, nonce, storageKey }: ThemeScriptProps) {
// suppressHydrationWarning: browsers hide the nonce attribute from the DOM (nonce hiding).
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} nonce={nonce} suppressHydrationWarning />
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme, storageKey }) }} nonce={nonce} suppressHydrationWarning />
}
+4 -2
View File
@@ -23,6 +23,8 @@ export type ThemeSwitcherProps = {
label?: null | string
/** Your icons. Default lucide Sun / Moon. `null` → no icon. */
renderIcon?: (theme: Theme) => ReactNode
/** localStorage key. Default: the one ThemeScript put on <html> (plugin `theme.storageKey`), else `theme`. */
storageKey?: string
}
/**
@@ -32,8 +34,8 @@ export type ThemeSwitcherProps = {
* server HTML is already right and nothing jumps after hydration.
* Hooks: data-ipal="theme-switch", data-ipal-theme-icon="light|dark".
*/
export function ThemeSwitcher({ classNames: cn = {}, label, renderIcon }: ThemeSwitcherProps) {
const { theme, toggle } = useTheme()
export function ThemeSwitcher({ classNames: cn = {}, label, renderIcon, storageKey }: ThemeSwitcherProps) {
const { theme, toggle } = useTheme({ storageKey })
const icon = (t: Theme) => (renderIcon ? renderIcon(t) : t === 'light' ? <Sun aria-hidden size="1.25em" /> : <Moon aria-hidden size="1.15em" />)
return (
<button
+13 -1
View File
@@ -1,2 +1,14 @@
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE, themeConfigFrom, themeScript } from './theme.js'
export {
documentThemeStorageKey,
isTheme,
isThemeSetting,
LEGACY_THEME_STORAGE_KEY,
migrateThemeStorage,
THEME_ATTRIBUTE,
THEME_STORAGE_ATTRIBUTE,
THEME_STORAGE_KEY,
THEME_SWITCHING_ATTRIBUTE,
themeConfigFrom,
themeScript,
} from './theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from './theme.js'
+47 -7
View File
@@ -12,8 +12,16 @@ export type Theme = 'dark' | 'light'
/** Site Settings → Default theme. 'system' follows the device (prefers-color-scheme). */
export type ThemeSetting = 'system' | Theme
/** localStorage key of the visitor's choice. */
export const THEME_STORAGE_KEY = 'ipal-theme'
/**
* Default localStorage key of the visitor's choice: `theme`, values `light` / `dark` —
* the same key and values as next-themes (a project using both shares one choice).
* Change it with `ipalKit({ theme: { storageKey } })`.
*/
export const THEME_STORAGE_KEY = 'theme'
/** The key before 1.15 — a choice stored under it is moved to the current key once, then removed. */
export const LEGACY_THEME_STORAGE_KEY = 'ipal-theme'
/** Set on <html> by <ThemeScript> when the key is not the default, so useTheme / ThemeSwitcher use the same one. */
export const THEME_STORAGE_ATTRIBUTE = 'data-theme-storage'
/** Attribute on <html>: `[data-theme=dark]`, Tailwind `@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *))`. */
export const THEME_ATTRIBUTE = 'data-theme'
/** Set on <html> for a moment while switching — for a colour transition only then (`[data-theme-switching] * { transition: … }`). */
@@ -28,17 +36,20 @@ export type ThemeConfig = {
allowToggle: boolean
/** null: no Site Settings — no attribute, the base (light) CSS applies. */
defaultTheme: null | ThemeSetting
/** localStorage key of the visitor's choice (`ipalKit({ theme: { storageKey } })`). Default `theme`. */
storageKey?: string
/** Accessible name of the switch, e.g. "Dark mode" (Site Settings → Theme). */
toggleLabel: null | string
}
/** Reads Theme options from a Site Settings document. */
export function themeConfigFrom(settings: unknown): ThemeConfig {
/** Reads Theme options from a Site Settings document (`storageKey` from the plugin's `theme` option). */
export function themeConfigFrom(settings: unknown, storageKey?: string): ThemeConfig {
const s = (settings && typeof settings === 'object' ? settings : {}) as Record<string, unknown>
const label = typeof s.themeToggleLabel === 'string' && s.themeToggleLabel.trim() ? s.themeToggleLabel.trim() : null
return {
allowToggle: s.allowThemeToggle === true,
defaultTheme: isThemeSetting(s.defaultTheme) ? s.defaultTheme : null,
...(storageKey && storageKey !== THEME_STORAGE_KEY ? { storageKey } : {}),
toggleLabel: label,
}
}
@@ -48,13 +59,42 @@ export function themeConfigFrom(settings: unknown): ThemeConfig {
* allowed) → default theme → for 'system' the device setting. Sets
* `data-theme` and `color-scheme` (native controls, scrollbars) on <html>.
*/
export function themeScript({ allowToggle, defaultTheme }: Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>): string {
export function themeScript({ allowToggle, defaultTheme, storageKey = THEME_STORAGE_KEY }: Pick<ThemeConfig, 'allowToggle' | 'defaultTheme' | 'storageKey'>): string {
const key = JSON.stringify(storageKey)
const legacy = JSON.stringify(LEGACY_THEME_STORAGE_KEY)
// A choice under the old key moves to the current one (once), then the old key goes.
const stored = allowToggle
? `try{var s=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});if(s==='light'||s==='dark')t=s}catch(e){}`
? `try{var k=${key},o=${legacy},s=localStorage.getItem(k);if(k!==o){var l=localStorage.getItem(o);` +
`if(l!==null){if(s===null&&(l==='light'||l==='dark')){localStorage.setItem(k,l);s=l}localStorage.removeItem(o)}}` +
`if(s==='light'||s==='dark')t=s}catch(e){}`
: ''
const keyAttribute = storageKey !== THEME_STORAGE_KEY ? `d.setAttribute(${JSON.stringify(THEME_STORAGE_ATTRIBUTE)},${key});` : ''
return (
`(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${stored}` +
`(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${keyAttribute}${stored}` +
`if(t==='system')t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';` +
`if(t==='light'||t==='dark'){d.setAttribute(${JSON.stringify(THEME_ATTRIBUTE)},t);d.style.colorScheme=t}})()`
)
}
/** The key the page uses: <html data-theme-storage> (set by ThemeScript), else the default. Browser only. */
export function documentThemeStorageKey(): string {
if (typeof document === 'undefined') {return THEME_STORAGE_KEY}
return document.documentElement.getAttribute(THEME_STORAGE_ATTRIBUTE) || THEME_STORAGE_KEY
}
/**
* Moves a choice stored under the old `ipal-theme` key to `key` (only when `key`
* is still empty) and removes the old key. ThemeScript does the same before the
* first paint; this covers pages without it. Never throws.
*/
export function migrateThemeStorage(key: string = THEME_STORAGE_KEY): void {
if (key === LEGACY_THEME_STORAGE_KEY) {return}
try {
const old = localStorage.getItem(LEGACY_THEME_STORAGE_KEY)
if (old === null) {return}
if (localStorage.getItem(key) === null && isTheme(old)) {localStorage.setItem(key, old)}
localStorage.removeItem(LEGACY_THEME_STORAGE_KEY)
} catch {
// blocked storage — nothing to move
}
}
+25 -17
View File
@@ -1,8 +1,8 @@
'use client'
import { useCallback, useSyncExternalStore } from 'react'
import { useCallback, useMemo, useSyncExternalStore } from 'react'
import { isTheme, type Theme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from './theme.js'
import { documentThemeStorageKey, isTheme, migrateThemeStorage, type Theme, THEME_ATTRIBUTE, THEME_SWITCHING_ATTRIBUTE } from './theme.js'
/** The theme on <html> (after ThemeScript); null before it ran / without a theme. */
export function readDocumentTheme(): null | Theme {
@@ -16,7 +16,10 @@ export function readDocumentTheme(): null | Theme {
* `data-theme-switching` on <html> for that long — style a colour transition
* with it, so normal hovers stay instant.
*/
export function applyTheme(theme: Theme, { persist = true, transitionMs = 300 }: { persist?: boolean; transitionMs?: number } = {}): void {
export function applyTheme(
theme: Theme,
{ persist = true, storageKey, transitionMs = 300 }: { persist?: boolean; storageKey?: string; transitionMs?: number } = {},
): void {
const root = document.documentElement
if (transitionMs > 0) {
root.setAttribute(THEME_SWITCHING_ATTRIBUTE, '')
@@ -26,23 +29,27 @@ export function applyTheme(theme: Theme, { persist = true, transitionMs = 300 }:
root.style.colorScheme = theme
if (!persist) {return}
try {
localStorage.setItem(THEME_STORAGE_KEY, theme)
localStorage.setItem(storageKey ?? documentThemeStorageKey(), theme)
} catch {
// private mode / blocked storage: the theme works until reload, the choice isn't kept
}
}
// <html data-theme> is external state: ThemeScript sets it, another tab changes it (storage event).
function subscribe(onChange: () => void): () => void {
const observer = new MutationObserver(onChange)
observer.observe(document.documentElement, { attributeFilter: [THEME_ATTRIBUTE], attributes: true })
const onStorage = (event: StorageEvent) => {
if (event.key === THEME_STORAGE_KEY && isTheme(event.newValue)) {applyTheme(event.newValue, { persist: false, transitionMs: 0 })}
}
window.addEventListener('storage', onStorage)
return () => {
observer.disconnect()
window.removeEventListener('storage', onStorage)
function subscribeWith(storageKey: string | undefined) {
return (onChange: () => void): (() => void) => {
const key = storageKey ?? documentThemeStorageKey()
migrateThemeStorage(key) // a page without ThemeScript still moves the old ipal-theme choice
const observer = new MutationObserver(onChange)
observer.observe(document.documentElement, { attributeFilter: [THEME_ATTRIBUTE], attributes: true })
const onStorage = (event: StorageEvent) => {
if (event.key === key && isTheme(event.newValue)) {applyTheme(event.newValue, { persist: false, transitionMs: 0 })}
}
window.addEventListener('storage', onStorage)
return () => {
observer.disconnect()
window.removeEventListener('storage', onStorage)
}
}
}
@@ -54,9 +61,10 @@ const serverSnapshot = (): null | Theme => null
* (`[data-theme=dark] …`, Tailwind `dark:`), not from this value, so nothing
* jumps after hydration.
*/
export function useTheme(): { setTheme: (theme: Theme) => void; theme: null | Theme; toggle: () => void } {
export function useTheme({ storageKey }: { storageKey?: string } = {}): { setTheme: (theme: Theme) => void; theme: null | Theme; toggle: () => void } {
const subscribe = useMemo(() => subscribeWith(storageKey), [storageKey])
const theme = useSyncExternalStore(subscribe, readDocumentTheme, serverSnapshot)
const setTheme = useCallback((next: Theme) => applyTheme(next), [])
const toggle = useCallback(() => applyTheme(readDocumentTheme() === 'dark' ? 'light' : 'dark'), [])
const setTheme = useCallback((next: Theme) => applyTheme(next, { storageKey }), [storageKey])
const toggle = useCallback(() => applyTheme(readDocumentTheme() === 'dark' ? 'light' : 'dark', { storageKey }), [storageKey])
return { setTheme, theme, toggle }
}
+6 -1
View File
@@ -305,6 +305,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config = injectSeoTabs(config, options.seo)
}
// --- theme: the localStorage key of the visitor's choice reaches getSiteShell() through config.custom ---
if (options.theme?.storageKey) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, themeStorageKey: options.theme.storageKey } }
}
// --- forms: apply @payloadcms/plugin-form-builder directly ---
if (options.forms) {
config = await buildFormsPlugin(options.forms)(config)
@@ -371,7 +376,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.collections ?? []),
applyCollectionOverride(hideFromNav(withFillLocales('collection', buildCookieReviewCollection(scannerOptions), fillLocales['cookie-review'])), scannerOptions.collectionOverrides),
]
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats), ...(options.theme?.storageKey ? { themeStorageKey: options.theme.storageKey } : {}) }
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
// One approval for everything found (default on): the "Approve cookies" view and its endpoint.
const approval = scannerOptions.approval === false ? null : (scannerOptions.approval ?? {})
+14
View File
@@ -172,6 +172,14 @@ export type IpalOptions = {
*/
stats?: boolean | StatsOptions
/**
* Light / dark theme. `storageKey`: the localStorage key of the visitor's
* choice — default `theme` (the next-themes key and values, so a project using
* next-themes too shares one choice). getSiteShell().theme passes it to
* <ThemeScript>, which puts it on <html> for useTheme / ThemeSwitcher.
*/
theme?: ThemeOptions
/**
* Two-factor authentication (TOTP), ENFORCED for every user. Wires
* @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every
@@ -260,3 +268,9 @@ export type IpalOptions = {
}
| boolean
}
/** `ipalKit({ theme })` — every key optional. */
export type ThemeOptions = {
/** localStorage key of the visitor's light / dark choice. Default `'theme'`. */
storageKey?: string
}
+3 -2
View File
@@ -88,13 +88,14 @@ afterAll(async () => {
describe('cookie scanner against a real Payload', () => {
test('a scan writes drafts in every locale and publishes nothing', async () => {
const { enabled, summary } = await runCookieScan({ names: ['_hjSessionUser_42', 'mystery'], options: { declarations }, payload, plugin })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'locale', 'stats', 'ga4'])
// Site Settings allow the theme switch by default, so its localStorage key is declared too.
expect(enabled.map((i) => i.key)).toEqual(['consent', 'theme', 'admin', 'locale', 'stats', 'ga4'])
expect(summary).toMatchObject({ unknown: 1, updated: 0 })
const entries = await all()
expect(entries.every((e) => e.status === 'draft')).toBe(true)
expect(entries.map((e) => e.name).sort()).toEqual(
['NEXT_LOCALE', '_ga', '_ga_*', '_hjSessionUser_*', 'cookie-consent', 'ipal_vid', 'mystery', 'payload-token', 'yt-*'].sort(),
['NEXT_LOCALE', '_ga', '_ga_*', '_hjSessionUser_*', 'cookie-consent', 'ipal_vid', 'mystery', 'payload-token', 'theme', 'yt-*'].sort(),
)
expect((await byName('ipal_vid')).purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: expect.stringContaining('Wbudowane') })
expect(await byName('_ga')).toMatchObject({ listed: true, source: 'integration' })
+4
View File
@@ -88,6 +88,10 @@ describe('fill empty locales — cookie list', () => {
await addToCookieList({ entry: { name: 'only_pl', category: 'analytics', purpose: { pl: 'Tylko po polsku' } }, payload })
expect((await row('en', 'only_pl'))?.purpose).toBe('Tylko po polsku')
expect((await row('de', 'only_pl'))?.purpose).toBe('Tylko po polsku')
// The type of entry is stored once for every language.
await addToCookieList({ entry: { name: 'theme', category: 'necessary', purpose: { pl: 'Motyw' }, storage: 'localStorage' }, payload })
expect((await row('en', 'theme')) as unknown as { storage?: string }).toMatchObject({ purpose: 'Motyw', storage: 'localStorage' })
expect(((await row('pl', 'only_pl')) as unknown as { storage?: string }).storage).toBe('cookie')
})
})
+12 -3
View File
@@ -353,13 +353,20 @@ describe('cookie table', () => {
locale: 'pl' as never,
})
expect(await getCookieTable({ locale: 'pl', payload })).toEqual([
{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' },
{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki', storage: 'cookie' },
])
// the same rows feed the detailed settings window, with the page language's default labels until the panel has them
const texts = await getConsentTexts({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, locale: 'pl', payload, privacyPolicy: false })
expect(texts.cookies).toEqual([{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }])
expect(texts.details).toEqual({ cookies: 'Używane cookies', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel' })
expect(texts.cookies).toEqual([{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki', storage: 'cookie' }])
expect(texts.details).toEqual({
cookies: 'Używane cookies',
duration: 'Okres',
provider: 'Dostawca',
purpose: 'Cel',
storage: 'Rodzaj',
storageTypes: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' },
})
await payload.updateGlobal({
slug: 'cookie-settings' as never,
@@ -371,6 +378,8 @@ describe('cookie table', () => {
duration: 'Czas',
provider: 'Dostawca',
purpose: 'Cel',
storage: 'Rodzaj',
storageTypes: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' },
})
})
})
+140
View File
@@ -0,0 +1,140 @@
/**
* The theme's localStorage key: `theme` by default (next-themes), configurable,
* old `ipal-theme` choices moved before the first paint. Plus the scanner's
* declaration of the key and the "Type" column of <CookieTable>.
*/
import type { BasePayload, Config } from 'payload'
import { runInNewContext } from 'node:vm'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { CookieTable } from '../src/modules/consent/CookieTable.js'
import { collectCookieFindings } from '../src/modules/consent/scanner/scan.js'
import {
LEGACY_THEME_STORAGE_KEY,
migrateThemeStorage,
THEME_STORAGE_KEY,
themeConfigFrom,
themeScript,
} from '../src/modules/theme/theme.js'
import { ipalKit } from '../src/plugin.js'
function fakeStorage(initial: Record<string, string> = {}) {
const data = new Map(Object.entries(initial))
return {
data,
getItem: (k: string) => (data.has(k) ? data.get(k)! : null),
removeItem: (k: string) => void data.delete(k),
setItem: (k: string, v: string) => void data.set(k, v),
}
}
/** Runs the pre-paint script against a fake browser; returns storage and the <html> attributes. */
function runScript(script: string, initial: Record<string, string>) {
const localStorage = fakeStorage(initial)
const attrs: Record<string, string> = {}
const documentElement = { setAttribute: (k: string, v: string) => void (attrs[k] = v), style: {} as Record<string, string> }
runInNewContext(script, { document: { documentElement }, localStorage, window: { matchMedia: () => ({ matches: false }) } })
return { attrs, storage: Object.fromEntries(localStorage.data) }
}
describe('theme storage key', () => {
afterEach(() => vi.unstubAllGlobals())
test('default key is next-themes’ "theme"', () => {
expect(THEME_STORAGE_KEY).toBe('theme')
expect(LEGACY_THEME_STORAGE_KEY).toBe('ipal-theme')
})
test('an old ipal-theme choice moves to "theme" before the first paint, then the old key goes', () => {
const { attrs, storage } = runScript(themeScript({ allowToggle: true, defaultTheme: 'light' }), { 'ipal-theme': 'dark' })
expect(attrs['data-theme']).toBe('dark') // no flash: the old choice is applied at once
expect(storage).toEqual({ theme: 'dark' })
})
test('a choice under the new key wins; the old key is still removed', () => {
const { attrs, storage } = runScript(themeScript({ allowToggle: true, defaultTheme: 'light' }), { 'ipal-theme': 'dark', theme: 'light' })
expect(attrs['data-theme']).toBe('light')
expect(storage).toEqual({ theme: 'light' })
})
test('a custom key: used, marked on <html>, old choice moved to it', () => {
const { attrs, storage } = runScript(themeScript({ allowToggle: true, defaultTheme: null, storageKey: 'acme-theme' }), { 'ipal-theme': 'dark' })
expect(attrs['data-theme-storage']).toBe('acme-theme')
expect(storage).toEqual({ 'acme-theme': 'dark' })
})
test('without the toggle nothing is read or moved', () => {
const { attrs, storage } = runScript(themeScript({ allowToggle: false, defaultTheme: 'light' }), { 'ipal-theme': 'dark' })
expect(attrs['data-theme']).toBe('light')
expect(storage).toEqual({ 'ipal-theme': 'dark' })
})
test('migrateThemeStorage (pages without ThemeScript): same rule, never throws', () => {
const storage = fakeStorage({ 'ipal-theme': 'dark' })
vi.stubGlobal('localStorage', storage)
migrateThemeStorage()
expect(Object.fromEntries(storage.data)).toEqual({ theme: 'dark' })
vi.stubGlobal('localStorage', { getItem: () => { throw new Error('blocked') } })
expect(() => migrateThemeStorage()).not.toThrow()
})
test('the plugin option reaches getSiteShell through config.custom; themeConfigFrom carries it', async () => {
const config = await ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, theme: { storageKey: 'acme-theme' }, twoFactor: false })({
collections: [{ slug: 'users', auth: true, fields: [] }],
} as unknown as Config)
expect((config.custom as { ipal: { themeStorageKey: string } }).ipal.themeStorageKey).toBe('acme-theme')
expect(themeConfigFrom({ allowThemeToggle: true }, 'acme-theme').storageKey).toBe('acme-theme')
expect(themeConfigFrom({ allowThemeToggle: true }, 'theme').storageKey).toBeUndefined() // the default needs no attribute
})
})
describe('scanner: the plugin’s own storage keys', () => {
const ctx = (allowThemeToggle: boolean, themeStorageKey?: string) => ({
integrations: {},
payload: {
config: { cookiePrefix: 'payload' },
findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-settings' ? { allowThemeToggle } : {})),
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
} as unknown as BasePayload,
plugin: { localeCount: 1, stats: false, ...(themeStorageKey ? { themeStorageKey } : {}) },
})
test('the theme key is declared as necessary local storage when visitors may switch', async () => {
const { findings } = await collectCookieFindings({ ctx: ctx(true), database: false })
expect(findings.find((f) => f.name === 'theme')).toMatchObject({
category: 'necessary',
purpose: { en: expect.stringContaining('theme'), pl: expect.stringContaining('motyw') },
retention: { en: 'Until changed or site data is cleared', pl: 'Do zmiany lub wyczyszczenia danych witryny' },
setBeforeConsent: true,
storage: 'localStorage',
})
})
test('a custom key is declared under its own name; no toggle → not declared', async () => {
expect((await collectCookieFindings({ ctx: ctx(true, 'acme-theme'), database: false })).findings.map((f) => f.name)).toContain('acme-theme')
expect((await collectCookieFindings({ ctx: ctx(false), database: false })).findings.map((f) => f.name)).not.toContain('theme')
})
})
describe('<CookieTable> type column', () => {
const rows = [
{ name: '_ga', category: 'analytics' as const, storage: 'cookie' as const },
{ name: 'theme', category: 'necessary' as const, storage: 'localStorage' as const },
]
const html = (props: Record<string, unknown>) => renderToStaticMarkup(createElement(CookieTable, { rows, ...props }))
test('shown when an entry is not a cookie, in the page language', () => {
expect(html({ locale: 'pl' })).toContain('<th scope="col">Rodzaj</th>')
expect(html({ locale: 'pl' })).toContain('Pamięć lokalna')
expect(html({ locale: 'en' })).toContain('Local storage')
})
test('hidden for cookies only, or with storageColumn: false; storageTypes override the names', () => {
expect(renderToStaticMarkup(createElement(CookieTable, { locale: 'en', rows: [rows[0]] }))).not.toContain('Type')
expect(html({ locale: 'en', storageColumn: false })).not.toContain('Local storage')
expect(html({ locale: 'en', storageTypes: { localStorage: 'Browser storage' } })).toContain('Browser storage')
})
})