Files
Reims-Go/frontend/src/lib/themeEngine.ts
T
Nwflower ceeb483cfb fix(i18n,plugin,ui): harden PR #10 redaction, trust boundaries, ICU limits, and UI contrast
Follow-up hardening from PR #10 review:
- Redact quoted/space-containing SMC OSKs, hyphenated MACs, and extended token keys without corrupting benign 'serial ...' messages; make RawDetail truncation UTF-8-safe and register reims.RedactText in CLI
- Enforce trust boundaries so unprivileged community language packs cannot hijack built-in zh-CN/en-US catalogs or overwrite target-owned plugin metadata/messages
- Avoid triggering inUseChecker/Sidecar wake-ups inside Registry.OnChange (ResolvedLocalePacks) and Broker.AllowRate; bound Sidecar NotifyIfRunning with a 500ms timeout; add l10nCache generation counter and syncLocales broadcast
- Cap ICU nesting depth (16) and template size (16 KiB) in Go & TS; reserve built-in anchors in 8-hop FallbackChain; fix C.UTF-8 detection, zero-var fault isolation, and PseudoLocalize brace escaping
- Fix pluginsdk Server.T apostrophe/contraction handling, defensive cloning, and sequential plugin/localeChanged dispatch
- Fix WCAG 2.1 AA contrast for --accent-soft-text, prevent PluginPanelFrame RPC hang on locale switch, guard setPluginLocales re-renders, and fix <=768px drawer & RTL toast swipe-out CSS
2026-11-30 00:26:14 -07:00

640 lines
23 KiB
TypeScript

// Three-tier Theme Engine (docs/plugin-architecture.md §5.1):
// - Builtin theme: zero extra CSS injected, zero UI SDK loaded (§8.1).
// - Tier 1 (Token theme): seed colors + declarative lightness/chroma/alpha derivation,
// bundled fonts, brand mark, background, and event sounds.
// - Tier 2 (Style theme): sanitized stylesheet wrapped in `@layer theme` +
// declarative state-driven slot decorations.
// - Tier 3 (Interactive theme): lazy-loads `./uiSdk` only when a trusted `ui_script_url` is active.
import { UI_CONTRACT_TOKENS } from '../styles/ui-contract'
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
const THEME_CACHE_KEY = 'reims-go-theme-tokens-v2'
const PREPAINT_EL_ID = 'rg-theme-prepaint'
const STYLE_EL_ID = 'rg-active-theme-style'
const FONT_EL_ID = 'rg-active-theme-fonts'
const ALLOWED_CONTRACT_TOKENS = new Set<string>(UI_CONTRACT_TOKENS)
const RE_FONT_WEIGHT = /^[0-9a-zA-Z -]+$/
const RE_FONT_STYLE = /^(normal|italic|oblique( +-?[0-9]+(\.[0-9]+)?deg)?)$/
const RE_UNICODE_RANGE = /^[U+0-9a-fA-F?, -]+$/
const RE_SAFE_ASSET_REL = /^[a-zA-Z0-9._/@ -]+$/
const RE_ASSET_BASE_URL = /^\/plugin-assets\/[a-f0-9]+\/[a-z0-9][a-z0-9._-]*\/$/
const RE_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/
const FORBIDDEN_FOCUS_RING_VALUES = new Set(['none', '0', '0px', 'transparent', 'initial', 'unset', 'revert', 'revert-layer'])
interface ThemeTokenCache {
themeId: string
activeScheme: string
light?: Record<string, string>
dark?: Record<string, string>
}
export interface UIStateSnapshot {
appearance: 'light' | 'dark'
motion: 'full' | 'reduced'
locale: string
dir: 'ltr' | 'rtl'
view: string
vmName: string
vmState: string
busy: boolean
hasError: boolean
sidebarCollapsed: boolean
safeMode: boolean
vms: Array<{ name: string; state: string }>
}
export interface ThemeSDKHostActions {
toggleSidebar: () => void
openSettings: () => void
focusVMWindow: (name: string) => void
}
let activeUIScriptCleanup: (() => void) | null = null
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
let activeUIScriptURL = ''
let applyGeneration = 0
function decodeCSSEscapes(s: string): string {
if (!s.includes('\\')) return s
let out = ''
for (let i = 0; i < s.length; ) {
if (s[i] === '\\' && i + 1 < s.length) {
i++
const hexMatch = /^[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?/.exec(s.slice(i))
if (hexMatch) {
const cp = parseInt(hexMatch[0].trim(), 16)
out += cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : '\uFFFD'
i += hexMatch[0].length
} else {
out += s[i]
i++
}
} else {
out += s[i]
i++
}
}
return out
}
/** Validates a token key+value against the UI Contract whitelist and CSS injection rules (B5). */
export function sanitizeTokenValue(key: string, value: string): string | null {
if (!ALLOWED_CONTRACT_TOKENS.has(key)) return null
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed || /[\r\n\0{};]/.test(trimmed) || trimmed.endsWith('\\')) return null
if (trimmed.includes('/*') || trimmed.includes('*/')) return null
const decoded = decodeCSSEscapes(trimmed).toLowerCase()
if (/[\r\n\0{};]/.test(decoded)) return null
for (const bad of ['</style', 'url(', 'src(', 'image-set(', '-webkit-image-set(', 'expression(', '@import', 'javascript:', 'data:', 'http://', 'https://', '//']) {
if (decoded.includes(bad)) return null
}
if (key === '--focus-ring' && (FORBIDDEN_FOCUS_RING_VALUES.has(decoded) || /\btransparent\b/.test(decoded))) {
return null
}
return trimmed
}
function sanitizeRelativeAssetPath(rel: string): string | null {
if (typeof rel !== 'string') return null
const cleaned = rel.trim().replace(/^\/+/, '')
if (!cleaned || /["'\\;{}()\r\n\0]/.test(cleaned) || !RE_SAFE_ASSET_REL.test(cleaned)) return null
if (RE_SCHEME.test(cleaned)) return null
for (const seg of cleaned.split('/')) {
if (seg === '..') return null
}
return cleaned
}
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme` (B5). */
export function isBalancedThemeCSS(css: string): boolean {
if (css.toLowerCase().includes('</style')) return false
let depth = 0
const n = css.length
for (let i = 0; i < n; ) {
const c = css[i]
if (c === '/' && i + 1 < n && css[i + 1] === '*') {
const end = css.indexOf('*/', i + 2)
if (end < 0) return false
i = end + 2
continue
}
if (c === '"' || c === "'") {
const q = c
i++
let closed = false
while (i < n) {
if (css[i] === '\\') {
i += 2
continue
}
if (css[i] === '\n' || css[i] === '\r') return false
if (css[i] === q) {
i++
closed = true
break
}
i++
}
if (!closed) return false
continue
}
if (c === '\\') {
// Backslash escapes the next char (e.g. `\{` or `\}`) outside strings so it cannot affect brace depth.
if (i + 1 >= n) return false
i += 2
continue
}
if (c === '{') depth++
else if (c === '}') {
depth--
if (depth < 0) return false
}
i++
}
return depth === 0
}
function resolveInitialAppearance(): 'light' | 'dark' {
try {
const saved = localStorage.getItem('reims-go-theme')
if (saved === 'dark' || saved === 'light') return saved
} catch {
// ignore storage errors
}
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
function clearLegacyInlineCache(): void {
try {
const raw = localStorage.getItem(LEGACY_CACHE_KEY)
if (raw) {
const prev = JSON.parse(raw) as Record<string, string>
if (prev && typeof prev === 'object') {
for (const k of Object.keys(prev)) {
if (k.startsWith('--')) document.documentElement.style.removeProperty(k)
}
}
localStorage.removeItem(LEGACY_CACHE_KEY)
}
} catch {
// ignore
}
}
function buildTokenVarLines(tokens: Record<string, string>): string {
const lines: string[] = []
for (const [k, v] of Object.entries(tokens)) {
const safe = sanitizeTokenValue(k, v)
if (safe) lines.push(` ${k}: ${safe};`)
}
return lines.join('\n')
}
/**
* Applies cached theme tokens via a `@layer theme` `<style>` element (never
* inline `element.style`, B8) keyed by appearance to avoid FOUC (§5.1).
*/
export function applyCachedThemeTokensSync(): void {
clearLegacyInlineCache()
try {
const raw = localStorage.getItem(THEME_CACHE_KEY)
if (!raw) return
const cache = JSON.parse(raw) as ThemeTokenCache
if (!cache || typeof cache !== 'object') return
const appearance = resolveInitialAppearance()
const tokens = cache[appearance]
if (!tokens || typeof tokens !== 'object') return
const varLines = buildTokenVarLines(tokens)
if (!varLines) return
let el = document.getElementById(PREPAINT_EL_ID) as HTMLStyleElement | null
if (!el) {
el = document.createElement('style')
el.id = PREPAINT_EL_ID
document.head.appendChild(el)
}
el.textContent = `@layer theme {\n:root {\n${varLines}\n}\n}`
} catch {
// ignore corrupt cache
}
}
function clearDynamicThemeStyles(): void {
document.getElementById(PREPAINT_EL_ID)?.remove()
document.getElementById(STYLE_EL_ID)?.remove()
document.getElementById(FONT_EL_ID)?.remove()
clearLegacyInlineCache()
try {
localStorage.removeItem(THEME_CACHE_KEY)
} catch {
// ignore
}
}
const RE_VALID_HEX = /^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
/** Parses a #RGB or #RRGGBB hex string into [h (0..360), s (0..1), l (0..1)]. */
function hexToHSL(hex: string): [number, number, number] | null {
const clean = hex.trim().replace(/^#/, '')
if (!RE_VALID_HEX.test(clean)) return null
let r = 0, g = 0, b = 0
if (clean.length === 3) {
r = parseInt(clean[0] + clean[0], 16) / 255
g = parseInt(clean[1] + clean[1], 16) / 255
b = parseInt(clean[2] + clean[2], 16) / 255
} else {
r = parseInt(clean.slice(0, 2), 16) / 255
g = parseInt(clean.slice(2, 4), 16) / 255
b = parseInt(clean.slice(4, 6), 16) / 255
}
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
const l = (max + min) / 2
if (max === min) return [0, 0, l]
const d = max - min
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
let h = 0
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6
else if (max === g) h = ((b - r) / d + 2) / 6
else h = ((r - g) / d + 4) / 6
return [h * 360, s, l]
}
function clamp01(x: number): number {
return Math.max(0, Math.min(1, x))
}
function srgbChannelToLinear(c: number): number {
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
}
/** Computes WCAG 2.1 relative luminance (0..1) for a #RGB or #RRGGBB hex string. */
function hexRelativeLuminance(hex: string): number | null {
const clean = hex.trim().replace(/^#/, '')
if (!RE_VALID_HEX.test(clean)) return null
let r = 0, g = 0, b = 0
if (clean.length === 3) {
r = parseInt(clean[0] + clean[0], 16) / 255
g = parseInt(clean[1] + clean[1], 16) / 255
b = parseInt(clean[2] + clean[2], 16) / 255
} else {
r = parseInt(clean.slice(0, 2), 16) / 255
g = parseInt(clean.slice(2, 4), 16) / 255
b = parseInt(clean.slice(4, 6), 16) / 255
}
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
return 0.2126 * srgbChannelToLinear(r) + 0.7152 * srgbChannelToLinear(g) + 0.0722 * srgbChannelToLinear(b)
}
function hslRelativeLuminance(hDeg: number, s: number, l: number): number {
const c = (1 - Math.abs(2 * l - 1)) * s
const hp = ((hDeg % 360) + 360) % 360 / 60
const x = c * (1 - Math.abs((hp % 2) - 1))
let r1 = 0, g1 = 0, b1 = 0
if (hp < 1) [r1, g1, b1] = [c, x, 0]
else if (hp < 2) [r1, g1, b1] = [x, c, 0]
else if (hp < 3) [r1, g1, b1] = [0, c, x]
else if (hp < 4) [r1, g1, b1] = [0, x, c]
else if (hp < 5) [r1, g1, b1] = [x, 0, c]
else [r1, g1, b1] = [c, 0, x]
const m = l - c / 2
return (
0.2126 * srgbChannelToLinear(clamp01(r1 + m)) +
0.7152 * srgbChannelToLinear(clamp01(g1 + m)) +
0.0722 * srgbChannelToLinear(clamp01(b1 + m))
)
}
function contrastRatio(lumA: number, lumB: number): number {
const hi = Math.max(lumA, lumB)
const lo = Math.min(lumA, lumB)
return (hi + 0.05) / (lo + 0.05)
}
function pickAccessibleSoftAccentText(h: number, s: number, l: number, appearance: 'light' | 'dark'): string {
// Target surface luminance: light canvas/soft (~0.92), dark surface (~0.015 for #1d1e23).
const surfaceLum = appearance === 'dark' ? 0.015 : 0.92
const targetRatio = 4.6
let candidateL = appearance === 'dark' ? Math.max(l, 0.66) : Math.min(l, 0.42)
if (contrastRatio(hslRelativeLuminance(h, s, candidateL), surfaceLum) < targetRatio) {
let lo = appearance === 'dark' ? candidateL : 0
let hi = appearance === 'dark' ? 1 : candidateL
for (let i = 0; i < 16; i++) {
const mid = (lo + hi) / 2
const ok = contrastRatio(hslRelativeLuminance(h, s, mid), surfaceLum) >= targetRatio
if (appearance === 'dark') {
if (ok) hi = mid
else lo = mid
} else {
if (ok) lo = mid
else hi = mid
}
}
candidateL = appearance === 'dark' ? hi : lo
}
return `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(candidateL) * 100)}%)`
}
function pickHighContrastAccentText(hex: string): string {
const lum = hexRelativeLuminance(hex)
if (lum === null) return '#ffffff'
const whiteContrast = 1.05 / (lum + 0.05)
const darkInkLum = 0.0123 // #1d1d1f
const darkContrast = (lum + 0.05) / (darkInkLum + 0.05)
return darkContrast > whiteContrast ? '#1d1d1f' : '#ffffff'
}
/** Derives CSS variable values from seed colors using declarative rules (§5.1). */
export function deriveTokensFromSeeds(
seeds: Record<string, string>,
rules: TokenDeriveRule[] | undefined,
appearance: 'light' | 'dark',
): Record<string, string> {
const out: Record<string, string> = {}
if (seeds.accent) {
const hsl = hexToHSL(seeds.accent)
out['--accent'] = seeds.accent
if (hsl) {
const [h, s, l] = hsl
out['--accent-text'] = pickHighContrastAccentText(seeds.accent)
out['--accent-hover'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(l + (appearance === 'dark' ? 0.06 : -0.06)) * 100)}%)`
out['--accent-soft'] = `hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.2 : 0.12})`
out['--accent-soft-text'] = pickAccessibleSoftAccentText(h, s, l, appearance)
out['--focus-ring'] = `0 0 0 3px hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.45 : 0.30})`
}
}
if (seeds.surface) {
out['--surface-0'] = seeds.surface
out['--surface-canvas'] = seeds.surface
}
if (seeds.text) {
out['--text'] = seeds.text
}
for (const rule of rules ?? []) {
if (rule.appearance && rule.appearance !== appearance) continue
if (!ALLOWED_CONTRACT_TOKENS.has(rule.token)) continue
const seedVal = seeds[rule.fromSeed]
if (!seedVal) continue
const hsl = hexToHSL(seedVal)
if (!hsl) continue
const h = Math.round(hsl[0])
const s = Math.round(clamp01(rule.chroma && rule.chroma > 0 ? hsl[1] * rule.chroma : hsl[1]) * 100)
const l = Math.round(clamp01(hsl[2] + (rule.lightness ?? 0)) * 100)
if (rule.alpha && rule.alpha > 0 && rule.alpha < 1) {
out[rule.token] = `hsla(${h}, ${s}%, ${l}%, ${rule.alpha.toFixed(3)})`
} else {
out[rule.token] = `hsl(${h} ${s}% ${l}%)`
}
}
return out
}
/** Evaluates a declarative ThemeDecoration state expression (e.g. "vmState==running"). */
export function matchDecorationState(
decoration: ThemeDecoration,
snap: UIStateSnapshot,
): ThemeDecorationState | null {
let fallback: ThemeDecorationState | null = null
for (const st of decoration.states ?? []) {
const expr = (st.when || '').trim()
if (!expr || expr === 'default') {
fallback = st
continue
}
const [rawKey, rawVal] = expr.split('==').map((s) => s.trim())
if (!rawKey) continue
const map: Record<string, string> = {
vmState: snap.vmState,
view: snap.view,
theme: snap.appearance,
busy: String(snap.busy),
hasError: String(snap.hasError),
sidebarCollapsed: String(snap.sidebarCollapsed),
}
if (map[rawKey] === rawVal) return st
}
return fallback
}
/** Applies the active theme payload to the document, tearing down any previous theme first. */
export async function applyActiveTheme(
payload: ActiveThemePayload | null,
appearance: 'light' | 'dark',
getState: () => UIStateSnapshot,
actions: ThemeSDKHostActions,
): Promise<void> {
const gen = ++applyGeneration
// Always drop prepaint & legacy inline tokens so live theme/builtin always wins (B8).
document.getElementById(PREPAINT_EL_ID)?.remove()
clearLegacyInlineCache()
// Always tear down previous interactive theme script if URL changed or disabled.
const nextScriptURL = payload?.ui_script_url ?? ''
if (activeUIScriptCleanup && activeUIScriptURL !== nextScriptURL) {
try { activeUIScriptCleanup() } catch {}
activeUIScriptCleanup = null
activeUIScriptURL = ''
}
// Builtin default theme (or safe mode) -> zero extra CSS injected (§8.1).
if (!payload || !payload.theme || payload.theme_id === 'builtin.theme.default') {
clearDynamicThemeStyles()
return
}
const th = payload.theme
const rawBaseURL = payload.asset_base_url ?? ''
const baseURL = RE_ASSET_BASE_URL.test(rawBaseURL) && !rawBaseURL.includes('..') ? rawBaseURL : ''
// 1. Resolve active seed colors (custom scheme -> built-in scheme -> theme default seeds).
let seeds: Record<string, string> = { ...(th.seeds ?? {}) }
if (payload.active_scheme) {
const custom = (payload.custom_schemes ?? []).find((s) => s.id === payload.active_scheme && s.theme_id === payload.theme_id)
const preset = (th.schemes ?? []).find((s) => s.id === payload.active_scheme)
if (custom?.seeds) seeds = { ...seeds, ...custom.seeds }
else if (preset?.seeds) seeds = { ...seeds, ...preset.seeds }
}
// 2. Compute derived + explicit tokens and filter strictly through UI Contract whitelist (B5).
const rawTokens: Record<string, string> = {
...deriveTokensFromSeeds(seeds, th.deriveRules, appearance),
...(th.tokens ?? {}),
...(appearance === 'dark' ? (th.darkTokens ?? {}) : {}),
}
const sanitizedTokens: Record<string, string> = {}
for (const [k, v] of Object.entries(rawTokens)) {
const safe = sanitizeTokenValue(k, v)
if (safe) sanitizedTokens[k] = safe
}
// 3. Inject validated bundled @font-face declarations (B5).
let fontCSS = ''
for (const f of th.fonts ?? []) {
const family = typeof f.family === 'string' ? f.family.trim() : ''
if (!family || /["'\\;{}\r\n\0]/.test(family) || family.toLowerCase().includes('</style')) continue
const safeFile = sanitizeRelativeAssetPath(f.file)
if (!safeFile || !baseURL) continue
const safeURL = baseURL + safeFile
const weight = f.weight && RE_FONT_WEIGHT.test(f.weight) ? `font-weight:${f.weight};` : ''
const style = f.style && RE_FONT_STYLE.test(f.style.trim()) ? `font-style:${f.style.trim()};` : ''
const range = f.unicodeRange && RE_UNICODE_RANGE.test(f.unicodeRange) ? `unicode-range:${f.unicodeRange};` : ''
fontCSS += `@font-face{font-family:"${family}";src:url("${safeURL}");font-display:swap;${weight}${style}${range}}\n`
}
if (fontCSS) {
let el = document.getElementById(FONT_EL_ID) as HTMLStyleElement | null
if (!el) {
el = document.createElement('style')
el.id = FONT_EL_ID
document.head.appendChild(el)
}
el.textContent = fontCSS
} else {
document.getElementById(FONT_EL_ID)?.remove()
}
// 4. Write validated token CSS + Tier-2 stylesheet wrapped inside `@layer theme` (§5.1, B5/B7).
const varLines = buildTokenVarLines(sanitizedTokens)
let bgCSS = ''
if (th.background && baseURL) {
const safeBg = sanitizeRelativeAssetPath(th.background)
if (safeBg) {
bgCSS = `.rg-p-shell { background-image: url("${baseURL}${safeBg}"); background-size: cover; }\n`
}
}
const rawThemeCSS = payload.css && isBalancedThemeCSS(payload.css) ? payload.css : ''
const fullCSS = `@layer theme {\n:root {\n${varLines}\n}\n${bgCSS}${rawThemeCSS}\n}`
let styleEl = document.getElementById(STYLE_EL_ID) as HTMLStyleElement | null
if (!styleEl) {
styleEl = document.createElement('style')
styleEl.id = STYLE_EL_ID
document.head.appendChild(styleEl)
}
styleEl.textContent = fullCSS
// Persist appearance-keyed cache for prepaint (B8).
try {
let nextCache: ThemeTokenCache = {
themeId: payload.theme_id,
activeScheme: payload.active_scheme ?? '',
}
const prevRaw = localStorage.getItem(THEME_CACHE_KEY)
if (prevRaw) {
const prev = JSON.parse(prevRaw) as ThemeTokenCache
if (prev && prev.themeId === nextCache.themeId && prev.activeScheme === nextCache.activeScheme) {
nextCache = { ...prev }
}
}
nextCache[appearance] = sanitizedTokens
localStorage.setItem(THEME_CACHE_KEY, JSON.stringify(nextCache))
} catch {
// ignore storage quota
}
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
try {
const { mountInteractiveThemeScript, notifyThemeSDKState } = await import('./uiSdk')
if (gen !== applyGeneration) return
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
if (gen !== applyGeneration) {
try { cleanup() } catch {}
return
}
activeUIScriptCleanup = () => {
activeUIScriptNotifier = null
cleanup()
}
activeUIScriptNotifier = notifyThemeSDKState
activeUIScriptURL = nextScriptURL
} catch {
if (gen === applyGeneration) {
// Fallback gracefully to the scriptless style/token theme (§4.2).
activeUIScriptCleanup = null
activeUIScriptURL = ''
}
}
}
}
const LOCALE_FONT_EL_ID = 'rg-active-locale-fonts'
const RE_SAFE_FONT_URL = /^\/plugin-assets\/[a-f0-9]+\/[a-z0-9][a-z0-9._-]*\/[a-zA-Z0-9._/@ -]+\.woff2$/i
const RE_SAFE_FONT_FAMILY = /^[\p{L}\p{N} _-]{1,80}$/u
/**
* Injects optional bundled `.woff2` WebFonts declared by the active language pack
* into `--font-locale-pack` (scoped strictly inside `@layer theme`, zero cost when empty).
*/
export function applyActiveLocaleFonts(
fonts: Array<{ family: string; url: string; weight?: string; style?: string; unicodeRange?: string }> | undefined,
): void {
const existing = document.getElementById(LOCALE_FONT_EL_ID)
if (!fonts || fonts.length === 0) {
existing?.remove()
return
}
const rules: string[] = []
const families: string[] = []
for (const f of fonts) {
const fam = (f.family || '').trim()
if (!RE_SAFE_FONT_FAMILY.test(fam) || fam.toLowerCase().includes('</style')) continue
if (!f.url || f.url.includes('..') || !RE_SAFE_FONT_URL.test(f.url)) continue
const weight = f.weight && RE_FONT_WEIGHT.test(f.weight) ? f.weight : '400'
const style = f.style && RE_FONT_STYLE.test(f.style) ? f.style : 'normal'
const ur = f.unicodeRange && RE_UNICODE_RANGE.test(f.unicodeRange) ? `unicode-range: ${f.unicodeRange};` : ''
rules.push(
`@font-face { font-family: "${fam}"; src: url("${f.url}") format("woff2"); font-weight: ${weight}; font-style: ${style}; font-display: swap; ${ur} }`,
)
if (!families.includes(`"${fam}"`)) {
families.push(`"${fam}"`)
}
}
if (rules.length === 0) {
existing?.remove()
return
}
let styleEl = existing as HTMLStyleElement | null
if (!styleEl) {
styleEl = document.createElement('style')
styleEl.id = LOCALE_FONT_EL_ID
document.head.appendChild(styleEl)
}
styleEl.textContent = `@layer theme {\n:root {\n --font-locale-pack: ${families.join(', ')}, ;\n}\n${rules.join('\n')}\n}`
}
/** Tears down injected theme/locale style nodes and active UI scripts on unmount. */
export function disposeActiveThemeAndLocaleFonts(): void {
if (activeUIScriptCleanup) {
try { activeUIScriptCleanup() } catch {}
activeUIScriptCleanup = null
activeUIScriptNotifier = null
activeUIScriptURL = ''
}
clearDynamicThemeStyles()
document.getElementById(LOCALE_FONT_EL_ID)?.remove()
}
export function notifyInteractiveThemeState(snap: UIStateSnapshot): void {
activeUIScriptNotifier?.(snap)
}
/** Plays a theme-configured sound for an event if present (fail-silent). */
export function playThemeSound(payload: ActiveThemePayload | null, eventName: string): void {
const file = payload?.theme?.sounds?.[eventName]
if (!file || !payload?.asset_base_url) return
const safe = sanitizeRelativeAssetPath(file)
if (!safe) return
try {
const audio = new Audio(payload.asset_base_url + safe)
audio.volume = 0.35
void audio.play().catch(() => {})
} catch {
// ignore audio decode/autoplay errors
}
}