Files
ipal-kit/test/themeStorage.test.ts
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

141 lines
6.9 KiB
TypeScript
Raw Permalink 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 { iapl } 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 iapl({ 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')
})
})