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
+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')
})
})