/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { colord, extend } from 'colord'; import mixPlugin from 'colord/plugins/mix'; import { getPreset, DEFAULT_PRESET_KEY } from '../styles/presets'; extend([mixPlugin]); const CACHE_KEY = 'theme-config'; const PRESETS_CACHE_KEY = 'theme-presets'; const STYLE_ID_LIGHT = 'theme-tokens-light'; const STYLE_ID_DARK = 'theme-tokens-dark'; const STYLE_ID_SEMI_LIGHT = 'theme-semi-light'; const STYLE_ID_SEMI_DARK = 'theme-semi-dark'; // 下次启动时供 index.html 头部内联脚本同步注入,避免首屏 splash 用兜底色刷一遍再跳到品牌色。 const CSS_CACHE_KEY = 'theme-css-cache'; const STYLE_ID_PRESPLASH = 'theme-presplash'; // 管理员对内置预设的覆盖(仅浅色 token,目前 8 个可编辑:brand-primary, // brand-gradient-from/via/to, bg-glow-from/to, accent-blue, accent-emerald)。 // 模块级单例,供 getEffectivePreset 读取。 // 形如 { ocean: { light: { 'brand-primary': '#xxx', ... } }, ... } let presetOverrides = {}; /** 安全解析 ThemeConfig JSON。任意失败都回落到默认预设。 */ function parseConfig(jsonString) { if (!jsonString) return { preset: DEFAULT_PRESET_KEY }; try { const parsed = JSON.parse(jsonString); if (parsed && typeof parsed === 'object') return parsed; } catch { /* ignore */ } return { preset: DEFAULT_PRESET_KEY }; } /** * 设置预设覆盖(管理员编辑过的预设模板)。在 applyTheme 之前调用才生效。 * @param jsonString 后端 theme_presets 字段 * @param persist 是否写 localStorage(默认 true,供下次 FOUC 同步注入) */ export function setPresetOverrides(jsonString, { persist = true } = {}) { try { presetOverrides = jsonString && typeof jsonString === 'string' ? JSON.parse(jsonString) : {}; if (!presetOverrides || typeof presetOverrides !== 'object') { presetOverrides = {}; } } catch { presetOverrides = {}; } if (!persist) return; try { window.localStorage.setItem( PRESETS_CACHE_KEY, jsonString || '{}', ); } catch { /* ignore */ } } /** * 由浅色 token 自动派生暗色 token(管理员只编辑浅色,暗色由此生成)。 * 规则:在暗背景上需要更亮的主色,故整体提亮;soft 用半透明叠加。 * * Exported so SettingsTheme.jsx 的"派生到深色"按钮可复用同一套规则, * 保持自定义模式与编辑预设模板的光暗联动逻辑一致。 */ export function deriveDarkTokens(light) { const lift = (hex, amt) => { try { return colord(hex).lighten(amt).toHex(); } catch { return hex; } }; const softOf = (hex) => { try { return colord(hex).lighten(0.12).alpha(0.18).toRgbString(); } catch { return 'rgba(129, 140, 248, 0.18)'; } }; return { // primary 只轻抬一档 —— 暗色实色按钮用白字需足够对比度; // 抬太多(旧 0.12/0.22)会让按钮底太浅、白字看不清。装饰类(gradient/glow/accent)仍可多抬。 'brand-primary': lift(light['brand-primary'], 0.04), 'brand-primary-hover': lift(light['brand-primary'], 0.14), 'brand-primary-soft': softOf(light['brand-primary']), 'brand-gradient-from': lift(light['brand-gradient-from'], 0.08), 'brand-gradient-via': lift(light['brand-gradient-via'], 0.1), 'brand-gradient-to': lift(light['brand-gradient-to'], 0.1), // 页面背景晕染 —— 管理员只编辑浅色,暗色统一上抬一档 'bg-glow-from': lift(light['bg-glow-from'], 0.08), 'bg-glow-to': lift(light['bg-glow-to'], 0.1), 'accent-blue': lift(light['accent-blue'], 0.12), 'accent-teal': lift(light['accent-teal'], 0.12), 'accent-emerald': lift(light['accent-emerald'], 0.12), }; } // 派生 token 的"反向依赖" —— 描述某个浅色 token 改变后会牵动哪些暗色 token。 // 大多数 token 是一对一映射;brand-primary 因为衍生 hover/soft,多带 2 个。 // getEffectivePreset 和 SettingsTheme 的"派生到深色"按钮都用这张表精确派生 // "实际被覆盖的项",避免覆盖管理员在 presets.js 中手调的、未触动的 dark token。 export const DARK_DERIVE_DEPS = { 'brand-primary': [ 'brand-primary', 'brand-primary-hover', 'brand-primary-soft', ], 'brand-gradient-from': ['brand-gradient-from'], 'brand-gradient-via': ['brand-gradient-via'], 'brand-gradient-to': ['brand-gradient-to'], 'bg-glow-from': ['bg-glow-from'], 'bg-glow-to': ['bg-glow-to'], 'accent-blue': ['accent-blue'], 'accent-teal': ['accent-teal'], 'accent-emerald': ['accent-emerald'], }; /** * 取生效后的预设:内置默认 ∪ 管理员覆盖(浅色),暗色随覆盖**精准派生**。 * 未被编辑的预设原样返回内置定义。 * * 精准派生(vs 旧版全量覆盖): * 只对 ov.light 中**实际被覆盖**的 token 派生对应的 dark token, * 保留预设手调的、未被触动的 dark 值(例如 mono 预设手调的 slate-300)。 * brand-primary 一次性带 hover/soft 三件套,靠 DARK_DERIVE_DEPS 映射。 */ export function getEffectivePreset(key) { const base = getPreset(key); const ov = presetOverrides[key]; if (!ov || !ov.light || Object.keys(ov.light).length === 0) return base; const light = { ...base.light, ...ov.light }; const derived = deriveDarkTokens(light); const dark = { ...base.dark }; for (const changedKey of Object.keys(ov.light)) { const deps = DARK_DERIVE_DEPS[changedKey]; if (!deps) continue; for (const dep of deps) { if (dep in derived) dark[dep] = derived[dep]; } } return { ...base, light, dark }; } /** * 在 React 渲染前同步执行 —— 从 localStorage 命中上次的主题立即注入, * 避免"默认色 → 服务器色"的首屏闪烁。 * * 首次访问(cache 空)时 tokens.css 的默认值作为兜底,仍只在首次有闪烁。 */ export function applyThemeFromCache() { if (typeof window === 'undefined') return; try { // 先恢复预设覆盖,再应用主题,确保 getEffectivePreset 拿到编辑后的预设 const cachedPresets = window.localStorage.getItem(PRESETS_CACHE_KEY); if (cachedPresets) setPresetOverrides(cachedPresets, { persist: false }); const cached = window.localStorage.getItem(CACHE_KEY); if (cached) { doApply(parseConfig(cached)); // 本路径来源就是已持久化的 theme-config,对 presplash CSS 缓存做一次刷新即可, // 同时自愈 theme-css-cache 被清掉的情况(下次刷新就不再有兜底色跳变) cachePresplashCSS(); } } catch { /* localStorage 不可用时静默 */ } } /** * 完整应用主题:注入 CSS + 写回 cache。 * * 调用时机: * - PageLayout loadStatus 拿到 theme_config 后(默认 persist=true,刷新后保留) * - SettingsTheme.jsx 保存成功后(默认 persist=true) * * options.persist:是否写入 localStorage(默认 true)。 * 预览场景(管理员点选预设但未保存)应传 false, * 避免未保存的预览值污染 cache,导致刷新后看到预览色再闪回 server 真实色。 */ export function applyTheme(jsonString, { persist = true } = {}) { const config = parseConfig(jsonString); doApply(config); if (!persist) return; try { window.localStorage.setItem(CACHE_KEY, jsonString || JSON.stringify(config)); } catch { /* ignore */ } // 关键:cachePresplashCSS 必须挂在 persist 的同一道闸门后, // 否则预览模式(persist=false)会把预览的 CSS 写进 presplash 缓存, // 下次刷新时 splash 闪一下"未保存的预览色"再回弹到真实色。 cachePresplashCSS(); } /** 清缓存,下次启动回落到默认预设。仅供调试用。 */ export function resetTheme() { try { window.localStorage.removeItem(CACHE_KEY); // 同步清掉 presplash CSS 缓存,否则下次刷新 splash 还是用旧色(即便 theme-config 已清) window.localStorage.removeItem(CSS_CACHE_KEY); } catch { /* ignore */ } } /* ============= 内部实现 ============= */ function doApply(config) { disableTransitionsBriefly(); // 用生效后的预设(含管理员对预设模板的编辑),再叠加 ThemeConfig 的自定义覆盖 const preset = getEffectivePreset(config.preset); const lightTokens = { ...preset.light, ...(config.lightTokens || {}) }; const darkTokens = { ...preset.dark, ...(config.darkTokens || {}) }; // 1. 自定义品牌 token(hex + RGB 三元组) injectTokens(STYLE_ID_LIGHT, ':root', withRgbTriplets(lightTokens)); injectTokens( STYLE_ID_DARK, 'html.dark, body[theme-mode="dark"]', withRgbTriplets(darkTokens), ); // 2. Semi 派生色(19 个变量 × 浅/暗 = 38 个)。 // info 单独传 accent-blue,保留"信息=蓝"语义;primary/link/focus 跟随 brand-primary。 // 浅色选择器必须包含 body:Semi 把浅色主题变量声明在 body 上,CSS 变量继承取最近祖先, // 只注入 :root 会被 Semi 的 body 级默认值(蓝色)覆盖,表现为浅色模式下 // Checkbox/Link 等原生 Semi 组件不跟随主题色(暗色注入 body[theme-mode=dark] 无此问题)。 injectSemiVars( STYLE_ID_SEMI_LIGHT, ':root, body', lightTokens['brand-primary'], false, lightTokens['accent-blue'], ); injectSemiVars( STYLE_ID_SEMI_DARK, 'html.dark, body[theme-mode="dark"]', darkTokens['brand-primary'], true, darkTokens['accent-blue'], ); // 3. 一次性清理掉本次启动时 index.html 注入的 presplash style——它的内容已经被 // 上面 4 个 style tag 覆盖,多留着只是占 DOM,无功能影响。 // 注意:presplash CSS 缓存(theme-css-cache)不在 doApply 写,而是在 applyTheme(persist=true) // 与 applyThemeFromCache 两条"承诺持久化"的入口里写。否则预览(persist=false)会污染缓存。 const pre = document.getElementById(STYLE_ID_PRESPLASH); if (pre && pre.parentNode) pre.parentNode.removeChild(pre); // 通知运行时读取 CSS 变量的消费方(如 vchart 图表的系列色)预设已切换。 // Semi 明暗切换有 initVChartSemiTheme 的 watcher,但预设注入只改 CSS 变量, // 不改 theme-mode,watcher 感知不到,必须靠这个事件补。 try { window.dispatchEvent(new CustomEvent('theme-tokens-applied')); } catch { /* CustomEvent 不可用时静默 */ } } function cachePresplashCSS() { try { const ids = [STYLE_ID_LIGHT, STYLE_ID_DARK, STYLE_ID_SEMI_LIGHT, STYLE_ID_SEMI_DARK]; const css = ids .map((id) => { const el = document.getElementById(id); return el ? el.textContent : ''; }) .filter(Boolean) .join('\n'); if (css) window.localStorage.setItem(CSS_CACHE_KEY, css); } catch { /* localStorage 写失败(隐私模式/超配额)静默:splash 仍能用 CSS var 兜底色 */ } } /** * 派生 Semi primary 系列 + info + link + focus-border (D1=B 路线)。 * * primary / link / focus-border 跟随 brand-primary; * info 单独跟随 infoHex(accent-blue)—— 保留"信息=蓝"的语义惯例, * 避免森林/日落等非蓝主题下出现绿色/橙色的 info 提示。infoHex 缺省回落到 primary。 * * isDark 决定 hover/active 是 darken 还是 lighten。 */ function buildSemiRules(baseHex, isDark, infoHex) { const base = colord(baseHex); const info = colord(infoHex || baseHex); const step = (c, n) => isDark ? c.lighten(n).toHex() : c.darken(n).toHex(); const alphaSoft = (c, a) => c.alpha(a).toRgbString(); // 浅暗模式 light 系列透明度策略略不同(参考 Semi 默认) const softDefault = isDark ? 0.2 : 0.12; const softHover = isDark ? 0.3 : 0.16; const softActive = isDark ? 0.4 : 0.2; const infoHexNorm = (infoHex || baseHex); return { /* primary(7 个)—— 跟随 brand-primary */ 'semi-color-primary': baseHex, 'semi-color-primary-hover': step(base, 0.05), 'semi-color-primary-active': step(base, 0.1), 'semi-color-primary-disabled': alphaSoft(base, 0.4), 'semi-color-primary-light-default': alphaSoft(base, softDefault), 'semi-color-primary-light-hover': alphaSoft(base, softHover), 'semi-color-primary-light-active': alphaSoft(base, softActive), /* info(7 个)—— 跟随 accent-blue,保留"信息=蓝"语义 */ 'semi-color-info': infoHexNorm, 'semi-color-info-hover': step(info, 0.05), 'semi-color-info-active': step(info, 0.1), 'semi-color-info-disabled': alphaSoft(info, 0.4), 'semi-color-info-light-default': alphaSoft(info, softDefault), 'semi-color-info-light-hover': alphaSoft(info, softHover), 'semi-color-info-light-active': alphaSoft(info, softActive), /* link(4 个)—— 跟随 brand-primary */ 'semi-color-link': baseHex, 'semi-color-link-hover': step(base, 0.05), 'semi-color-link-active': step(base, 0.1), 'semi-color-link-visited': baseHex, /* focus-border(1 个) */ 'semi-color-focus-border': baseHex, }; } function injectSemiVars(styleId, selector, baseHex, isDark, infoHex) { if (!baseHex) return; const rules = buildSemiRules(baseHex, isDark, infoHex); injectTokens(styleId, selector, rules); } /** * 给一组 hex token 追加 -rgb 三元组版本("R G B" 空格分隔)。 * * 用途:Tailwind 配置用 `rgb(var(--brand-primary-rgb) / )` 模式 * 才能让 `bg-brand-primary/20` 等带透明度的类正常工作。 * * 兼容 6 位(#RRGGBB)与 8 位(#RRGGBBAA)hex —— 三元组只取 RGB, * 不含 alpha(Tailwind 的透明度由工具类 /N 控制;token 自身的 alpha * 通过 var(--brand-*) 直接使用时生效)。非 hex 值(rgba 等)跳过。 */ const HEX_RE = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; function withRgbTriplets(tokens) { const out = { ...tokens }; for (const [k, v] of Object.entries(tokens)) { const s = String(v || '').trim(); if (!HEX_RE.test(s)) continue; const c = colord(s); if (!c.isValid()) continue; const { r, g, b } = c.toRgb(); out[`${k}-rgb`] = `${r} ${g} ${b}`; } return out; } /** * Token key/value 注入校验 —— 防 CSS 注入。 * * value 中若含 `;{}` 等 CSS 规则终止符,攻击者可以"逃出"当前 :root 规则 * 注入任意 body { display:none } 之类,导致 defacement。 * 这是最后一道防御,即使前端 UI 校验被绕过(手改 state、导入恶意 JSON) * 也会在注入点拒绝。 * * key 仅允许 ASCII 字母数字与连字符;长度 ≤ 60。 * value 长度 ≤ 200;禁止字符 `;{}`(CSS 规则边界符)。 * 拒绝的条目被静默丢弃,回退到 tokens.css 静态默认。 */ const SAFE_KEY_RE = /^[a-zA-Z][a-zA-Z0-9-]*$/; function isSafeCssKey(k) { if (typeof k !== 'string') return false; if (k.length === 0 || k.length > 60) return false; return SAFE_KEY_RE.test(k); } function isSafeCssValue(v) { if (typeof v !== 'string') return false; if (v.length === 0 || v.length > 200) return false; // CSS 规则终止符:禁止以防止逃出当前 :root 规则 if (/[;{}]/.test(v)) return false; return true; } /** * 用动态