Files
ipal-kit/test/themeStorage.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 b5368cdc61 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]>
2026-10-29 11:29:56 +01:00

141 lines
6.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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')
})
})