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:
co-authored by
Claude Opus 5.5
parent
6998b44431
commit
b5368cdc61
@@ -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 />
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user