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