Theme switcher, table of contents, missing-page redirect, form placeholders and time field; audit and revalidate fixes
- buildRevalidateHook skips outside Next (no NEXT_RUNTIME) and with context.disableRevalidate - BuilderForm focuses only on a real step change (no scroll to the form on remount) - mediaImageProps: placeholder colour only for JPEG (placeholderColor); hook stores no colour for transparent images - buildLinkField: interface name per shape (CmsLink, CmsLinkPlain, CmsLinkNoLabel) + interfaceName option - Cookie Settings: buttons.save -> buttons.savePreferences (Mongoose reserved name) - ThemeScript, ThemeSwitcher, useTheme; Site Settings defaultTheme 'system' + themeToggleLabel; Turnstile follows page theme - extractHeadings, RenderRichText headingIds, TableOfContents, buildTableOfContentsField - createPageRoute onMissing: 'redirectHome' - Form builder: localized placeholder on text/email/textarea/number, new time field - ipal-audit: no false positive for object keys between JSX elements; /md route not reported as dynamic Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
23e033d7d7
commit
faa4ad679c
@@ -0,0 +1,17 @@
|
||||
import type { ThemeConfig } from './theme.js'
|
||||
|
||||
import { themeScript } from './theme.js'
|
||||
|
||||
export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
|
||||
|
||||
/**
|
||||
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
|
||||
* theme. Put it first in <body> (or turn on `theme` in <SiteProviders>), and
|
||||
* add `suppressHydrationWarning` to <html>: the attribute differs from the server HTML on purpose.
|
||||
*
|
||||
* const shell = await getSiteShell(locale)
|
||||
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
|
||||
*/
|
||||
export function ThemeScript({ allowToggle = false, defaultTheme = null }: ThemeScriptProps) {
|
||||
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} />
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import { Moon, Sun } from 'lucide-react'
|
||||
|
||||
import type { Theme } from './theme.js'
|
||||
|
||||
import { useTheme } from './useTheme.js'
|
||||
|
||||
export type ThemeSwitcherClassNames = {
|
||||
/** Wrapper of the dark icon. */
|
||||
dark?: string
|
||||
/** Wrapper of the light icon. */
|
||||
light?: string
|
||||
/** The <button>. */
|
||||
root?: string
|
||||
}
|
||||
|
||||
export type ThemeSwitcherProps = {
|
||||
classNames?: ThemeSwitcherClassNames
|
||||
/** Accessible name — Site Settings → Theme → Toggle label (shell.theme.toggleLabel). */
|
||||
label?: null | string
|
||||
/** Your icons. Default lucide Sun / Moon. `null` → no icon. */
|
||||
renderIcon?: (theme: Theme) => ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Light / dark switch with no styles: a <button role="switch"> (checked = dark)
|
||||
* holding a light and a dark icon. Which one looks active is CSS's job — from
|
||||
* the attribute on <html> (`[data-theme=dark] …`, Tailwind `dark:`), so the
|
||||
* 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()
|
||||
const icon = (t: Theme) => (renderIcon ? renderIcon(t) : t === 'light' ? <Sun aria-hidden size="1.25em" /> : <Moon aria-hidden size="1.15em" />)
|
||||
return (
|
||||
<button
|
||||
aria-checked={theme === 'dark'}
|
||||
aria-label={label ?? undefined}
|
||||
className={cn.root}
|
||||
data-ipal="theme-switch"
|
||||
onClick={toggle}
|
||||
role="switch"
|
||||
type="button"
|
||||
>
|
||||
<span className={cn.light} data-ipal-theme-icon="light">{icon('light')}</span>
|
||||
<span className={cn.dark} data-ipal-theme-icon="dark">{icon('dark')}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE, themeConfigFrom, themeScript } from './theme.js'
|
||||
export type { Theme, ThemeConfig, ThemeSetting } from './theme.js'
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Light / dark theme — shared names and the pre-paint script. Pure: safe on the
|
||||
* server and in the browser.
|
||||
*
|
||||
* The theme never reaches the server HTML (pages are ISR/SSG, one HTML for
|
||||
* everyone): <ThemeScript> sets `data-theme` on <html> before the first paint,
|
||||
* from the visitor's choice (localStorage — an interface preference, no cookie,
|
||||
* no tracking, no consent needed) or Site Settings → Theme → Default theme.
|
||||
*/
|
||||
|
||||
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'
|
||||
/** 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: … }`). */
|
||||
export const THEME_SWITCHING_ATTRIBUTE = 'data-theme-switching'
|
||||
|
||||
export const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark'
|
||||
export const isThemeSetting = (value: unknown): value is ThemeSetting => value === 'system' || isTheme(value)
|
||||
|
||||
/** Theme options from Site Settings — what getSiteShell(locale).theme holds. */
|
||||
export type ThemeConfig = {
|
||||
/** Visitors may switch (and their choice is remembered). */
|
||||
allowToggle: boolean
|
||||
/** null: no Site Settings — no attribute, the base (light) CSS applies. */
|
||||
defaultTheme: null | ThemeSetting
|
||||
/** 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 {
|
||||
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,
|
||||
toggleLabel: label,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The inline script for <ThemeScript>: stored choice (only when the toggle is
|
||||
* 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 {
|
||||
const stored = allowToggle
|
||||
? `try{var s=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});if(s==='light'||s==='dark')t=s}catch(e){}`
|
||||
: ''
|
||||
return (
|
||||
`(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${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}})()`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useSyncExternalStore } from 'react'
|
||||
|
||||
import { isTheme, type Theme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from './theme.js'
|
||||
|
||||
/** The theme on <html> (after ThemeScript); null before it ran / without a theme. */
|
||||
export function readDocumentTheme(): null | Theme {
|
||||
if (typeof document === 'undefined') {return null}
|
||||
const value = document.documentElement.getAttribute(THEME_ATTRIBUTE)
|
||||
return isTheme(value) ? value : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a theme on <html> and remembers the choice. `transitionMs` keeps
|
||||
* `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 {
|
||||
const root = document.documentElement
|
||||
if (transitionMs > 0) {
|
||||
root.setAttribute(THEME_SWITCHING_ATTRIBUTE, '')
|
||||
window.setTimeout(() => root.removeAttribute(THEME_SWITCHING_ATTRIBUTE), transitionMs)
|
||||
}
|
||||
root.setAttribute(THEME_ATTRIBUTE, theme)
|
||||
root.style.colorScheme = theme
|
||||
if (!persist) {return}
|
||||
try {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, 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)
|
||||
}
|
||||
}
|
||||
|
||||
const serverSnapshot = (): null | Theme => null
|
||||
|
||||
/**
|
||||
* The current theme and a setter. `theme` is null on the server and during
|
||||
* hydration of a page without a theme — style the switch from CSS
|
||||
* (`[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 } {
|
||||
const theme = useSyncExternalStore(subscribe, readDocumentTheme, serverSnapshot)
|
||||
const setTheme = useCallback((next: Theme) => applyTheme(next), [])
|
||||
const toggle = useCallback(() => applyTheme(readDocumentTheme() === 'dark' ? 'light' : 'dark'), [])
|
||||
return { setTheme, theme, toggle }
|
||||
}
|
||||
Reference in New Issue
Block a user