/*
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 React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import {
Button,
Card,
Col,
Form,
Input,
Row,
Tabs,
TabPane,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { colord } from 'colord';
import { API, showError, showSuccess } from '../../../helpers';
import { StatusContext } from '../../../context/Status';
import { PRESETS, DEFAULT_PRESET_KEY } from '../../../styles/presets';
import {
applyTheme,
DARK_DERIVE_DEPS,
deriveDarkTokens,
getEffectivePreset,
setPresetOverrides,
} from '../../../helpers/theme';
const { Text, Title } = Typography;
/**
* 主题色配置(增强版)
*
* 模式:
* - 预设:6 套预设色板,一键切换
* - 自定义:在某个预设基础上微调 6 个核心 token,浅/暗独立编辑
*
* 数据形状:
* ThemeConfig = {
* preset: string, // 基础预设
* lightTokens: { [k]: hex }, // 浅色覆盖(仅与预设不同的项)
* darkTokens: { [k]: hex }, // 暗色覆盖
* }
*
* 实时预览:编辑时立即 applyTheme(persist: false),前端只在当前会话生效;
* 保存后才落库并 persist 到 localStorage。
*/
// 可编辑的核心 token —— 8 个分 3 组:品牌前景 / 页面背景 / 强调辅助。
// 设计要点:「按钮/气泡渐变」与「页面背景晕染」彻底分离,
// 改 brand-gradient-* 只动按钮气泡,改 bg-glow-* 只动页面大底色 / 光晕 blob。
const EDITABLE_TOKENS = [
// —— 品牌(前景:按钮 / 气泡 / 文字渐变) ——
{
key: 'brand-primary',
labelKey: '主品牌色',
descKey: '按钮、链接、激活态',
group: 'brand',
},
{
key: 'brand-gradient-from',
labelKey: '渐变起色',
descKey: '气泡/按钮渐变左侧',
group: 'brand',
},
{
key: 'brand-gradient-via',
labelKey: '渐变中间色',
descKey: '气泡/按钮渐变中段',
group: 'brand',
},
{
key: 'brand-gradient-to',
labelKey: '渐变止色',
descKey: '气泡/按钮渐变右侧',
group: 'brand',
},
// —— 页面背景晕染(大面积底色 / 光晕 blob) ——
// 只 from/to 两 stop,所有页面统一使用同一组刻度,admin 调一处全场生效。
{
key: 'bg-glow-from',
labelKey: '背景晕染起色',
descKey: '页面背景渐变顶部 · 顶部光晕',
group: 'bg',
},
{
key: 'bg-glow-to',
labelKey: '背景晕染止色',
descKey: '页面背景渐变底部 · 底部光晕',
group: 'bg',
},
// —— 强调辅助 ——
{
key: 'accent-blue',
labelKey: '强调蓝',
descKey: '信息提示、维护状态',
group: 'accent',
},
{
key: 'accent-emerald',
labelKey: '强调翠绿',
descKey: '辅助点缀',
group: 'accent',
},
];
// token 分组定义 —— 控制 UI 上的小标题与渲染顺序
const TOKEN_GROUPS = [
{
key: 'brand',
labelKey: '品牌色(按钮 / 气泡 / 文字渐变)',
descKey: '影响前景标识:按钮、气泡、icon 容器、文字渐变',
},
{
key: 'bg',
labelKey: '页面背景晕染(大面积底色 / 光晕)',
descKey:
'影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡',
},
{
key: 'accent',
labelKey: '强调辅助色',
descKey: '信息提示、辅助状态点缀',
},
];
// 接受 6 位(#RRGGBB)或 8 位(#RRGGBBAA 带透明度)hex
const HEX_RE = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
// 合法的 light token key(即 EDITABLE_TOKENS 的 8 个)
// 用于 handleSave 过滤老数据中残留的、已删除的 token key(如 bg-glow-via),
// 防止 stale 数据在服务器永久残留。
const VALID_LIGHT_TOKEN_KEYS = new Set(EDITABLE_TOKENS.map((t) => t.key));
// 合法的 dark token key —— 比 light 多 3 个派生项(hover/soft/accent-teal),
// 由 handleDeriveToDark 写入。soft 是 rgba 实际不会落入 customDark,但保留在
// 集合里以便未来扩展不被误删。
const VALID_DARK_TOKEN_KEYS = new Set([
...VALID_LIGHT_TOKEN_KEYS,
'brand-primary-hover',
'brand-primary-soft',
'accent-teal',
]);
/** 大小写不敏感的 hex 颜色等值比较:内置预设 hex 一律小写,但用户输入大小写不定。
* 非 hex 退化为 `===`,保留 rgba()/字面字符串等的精确比较。 */
function hexEqual(a, b) {
if (a === b) return true;
if (typeof a !== 'string' || typeof b !== 'string') return false;
if (HEX_RE.test(a) && HEX_RE.test(b)) {
return a.toLowerCase() === b.toLowerCase();
}
return false;
}
/** 取某预设的内置(出厂)浅色 token,用于"恢复出厂"与 diff 判断。 */
function getPresetBuiltinLight(key) {
return (PRESETS[key] || PRESETS[DEFAULT_PRESET_KEY]).light;
}
/**
* 浅层对象等值比较:键集合相同且每个键对应的值视为相等。
*
* 用于 dirty 判断:
* - 服务端 Go 把 map 序列化时键序不固定,用 JSON.stringify 比对会误报"已修改"。
* - hex 值用大小写不敏感比较,避免用户用大写输入后永远算"已改"。
*/
function shallowObjectEqual(a, b) {
if (a === b) return true;
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length) return false;
for (const k of ka) {
if (a[k] === b[k]) continue;
if (hexEqual(a[k], b[k])) continue;
return false;
}
return true;
}
export default function SettingsTheme(props) {
const { t } = useTranslation();
const [statusState, statusDispatch] = useContext(StatusContext);
const fileInputRef = useRef(null);
const [loading, setLoading] = useState(false);
// 顶层模式:预设 vs 自定义
const [mode, setMode] = useState('preset');
// 自定义模式下编辑浅/暗
const [colorMode, setColorMode] = useState('light');
// 选中的预设(作为自定义的基础)
const [selectedPreset, setSelectedPreset] = useState(DEFAULT_PRESET_KEY);
// 自定义覆盖
const [customLight, setCustomLight] = useState({});
const [customDark, setCustomDark] = useState({});
// 当前已保存到服务器的版本(用于"dirty"判断与"已应用"标记)
const [saved, setSaved] = useState({
preset: DEFAULT_PRESET_KEY,
light: {},
dark: {},
});
/* ===== 编辑预设模板(第三个 Tab)相关 state ===== */
// 已保存到服务器的预设覆盖:{ ocean: { light: {6 token} }, ... }
const [presetOverridesState, setPresetOverridesState] = useState({});
// 正在编辑的预设 key
const [editingPresetKey, setEditingPresetKey] = useState(DEFAULT_PRESET_KEY);
// 编辑中的浅色 token 草稿
const [presetDraft, setPresetDraft] = useState({});
const [presetSaving, setPresetSaving] = useState(false);
// 标记是否已从 props 完成首次解析。在解析前不应让"预览 useEffect"
// 触发 applyTheme,否则会把站点主题闪回 default。
const initializedRef = useRef(false);
// 从 OptionMap 读出预设覆盖(先于 ThemeConfig,确保 getEffectivePreset 正确)
useEffect(() => {
if (!props.options) return;
const raw = props.options.ThemePresets;
let parsed = {};
try {
parsed = raw ? JSON.parse(raw) : {};
if (!parsed || typeof parsed !== 'object') parsed = {};
} catch {
parsed = {};
}
setPresetOverridesState(parsed);
// 同步模块态(persist:false,不覆盖 PageLayout 已写的 cache)
setPresetOverrides(raw || '{}', { persist: false });
}, [props.options]);
// 从 OptionMap 读出 ThemeConfig
useEffect(() => {
if (!props.options || !props.options.ThemeConfig) return;
try {
const cfg = JSON.parse(props.options.ThemeConfig);
const presetKey = cfg.preset || DEFAULT_PRESET_KEY;
const lt = cfg.lightTokens || {};
const dt = cfg.darkTokens || {};
setSelectedPreset(presetKey);
setCustomLight(lt);
setCustomDark(dt);
setSaved({ preset: presetKey, light: lt, dark: dt });
// 若服务器值含自定义覆盖,初始打开自定义模式更直观
if (Object.keys(lt).length || Object.keys(dt).length) {
setMode('custom');
}
initializedRef.current = true;
} catch {
// 解析失败保持默认;仍然标记初始化以允许后续编辑
initializedRef.current = true;
}
}, [props.options]);
// 当前生效的 token(生效预设 + 自定义覆盖),用于预览
// 依赖 presetOverridesState:管理员编辑预设模板后重算
const effectiveLight = useMemo(
() => ({ ...getEffectivePreset(selectedPreset).light, ...customLight }),
[selectedPreset, customLight, presetOverridesState],
);
const effectiveDark = useMemo(
() => ({ ...getEffectivePreset(selectedPreset).dark, ...customDark }),
[selectedPreset, customDark, presetOverridesState],
);
const effectivePalette =
colorMode === 'light' ? effectiveLight : effectiveDark;
// 任何编辑都即时前端预览(不写 cache)。
// 注意:必须等首次 props 解析完成再开启预览,否则挂载瞬间会用 default state
// 调一次 applyTheme,把站点主题闪回默认。
useEffect(() => {
if (!initializedRef.current) return;
applyTheme(
JSON.stringify({
preset: selectedPreset,
lightTokens: customLight,
darkTokens: customDark,
}),
{ persist: false },
);
}, [selectedPreset, customLight, customDark]);
// dirty 判断:当前编辑值 vs 已保存值
// 使用浅层对象等值比较,避免依赖 JSON.stringify 的键序
// (服务器回传的 map 序列化键序可能与前端不同,会让 dirty 永远为 true)
const dirty = useMemo(() => {
if (selectedPreset !== saved.preset) return true;
return (
!shallowObjectEqual(customLight, saved.light) ||
!shallowObjectEqual(customDark, saved.dark)
);
}, [selectedPreset, customLight, customDark, saved]);
/* ============ 预设模式 ============ */
const handleSelectPreset = (key) => {
setSelectedPreset(key);
// 切预设时清空自定义覆盖(用户可以再进自定义模式调整)
setCustomLight({});
setCustomDark({});
};
/* ============ 自定义模式 ============ */
const handleTokenChange = (tokenKey, value) => {
if (colorMode === 'light') {
setCustomLight((prev) => ({ ...prev, [tokenKey]: value }));
} else {
setCustomDark((prev) => ({ ...prev, [tokenKey]: value }));
}
};
const handleTokenReset = (tokenKey) => {
if (colorMode === 'light') {
const { [tokenKey]: _, ...rest } = customLight;
setCustomLight(rest);
} else {
// 暗色重置时连带清掉派生衍生项(例如重置 brand-primary 时一并清 hover/soft),
// 避免"primary 已重置但派生进来的 hover 留下"的不协调状态。
const next = { ...customDark };
delete next[tokenKey];
const deps = DARK_DERIVE_DEPS[tokenKey];
if (deps) {
for (const dep of deps) delete next[dep];
}
setCustomDark(next);
}
};
const handleCopyToOther = () => {
if (colorMode === 'light') {
// 把当前浅色的所有 effective 值固化到自定义暗色(flat copy)
const copy = {};
EDITABLE_TOKENS.forEach((t) => {
copy[t.key] = effectiveLight[t.key];
});
setCustomDark(copy);
} else {
const copy = {};
EDITABLE_TOKENS.forEach((t) => {
copy[t.key] = effectiveDark[t.key];
});
setCustomLight(copy);
}
showSuccess(t('已复制到对侧模式'));
};
/**
* 派生到深色(lift) —— 只在 colorMode === 'light' 时可用。
* 与「编辑预设模板」的光暗联动用同一套规则(deriveDarkTokens + DARK_DERIVE_DEPS),
* 解决自定义 Tab 改浅色后暗色不跟随的体验割裂问题。
*
* 精准派生(B1 修法):
* 只对 customLight 中**实际被覆盖**的浅色 token 派生对应的暗色 token,
* 保留预设手调的、未被触动的 dark 值(如 mono 预设手调的 slate-300)。
*
* 合并不替换(B2 修法):
* merge 到现有 customDark,保留 admin 之前手调的暗色覆盖不被擦掉。
*
* 派生结果若与预设暗色一致则不写覆盖(delete next[dep]),
* 让兜底层处理,customDark 保持最小。
*
* 跳过非 hex(brand-primary-soft 等 rgba):会被 handleSave 的 hex 校验拒绝。
*/
const handleDeriveToDark = () => {
const changedLightKeys = Object.keys(customLight);
if (changedLightKeys.length === 0) {
showError(t('当前浅色无自定义覆盖,请先调整浅色再派生'));
return;
}
// 纯函数计算 next + touched,再一次性 setCustomDark;
// 不在 setState updater 内做副作用,避免严格模式下的双调用 / 重复计数。
const derived = deriveDarkTokens(effectiveLight);
const presetDark = getEffectivePreset(selectedPreset).dark;
const next = { ...customDark };
let touched = 0;
for (const lightKey of changedLightKeys) {
const deps = DARK_DERIVE_DEPS[lightKey] || [lightKey];
for (const dep of deps) {
const v = derived[dep];
if (typeof v !== 'string') continue;
if (!HEX_RE.test(v.trim())) continue; // 跳过 rgba
if (hexEqual(v, presetDark[dep])) {
// 派生值恰好与预设暗色一致 → 删除多余覆盖,让兜底处理
if (dep in next) {
delete next[dep];
touched++;
}
} else if (!hexEqual(next[dep], v)) {
next[dep] = v;
touched++;
}
}
}
setCustomDark(next);
if (touched > 0) {
showSuccess(t('已按规则派生到深色模式'));
} else {
showSuccess(t('派生结果与当前深色一致,无变化'));
}
};
const handleResetCurrentMode = () => {
if (colorMode === 'light') setCustomLight({});
else setCustomDark({});
};
const handleResetAll = () => {
setSelectedPreset(DEFAULT_PRESET_KEY);
setCustomLight({});
setCustomDark({});
};
/* ============ 编辑预设模板 ============ */
// 当前编辑预设的浅色 effective(生效预设浅色 ∪ 草稿)
const presetEditLight = useMemo(() => {
const base = getEffectivePreset(editingPresetKey).light;
return { ...base, ...presetDraft };
}, [editingPresetKey, presetDraft, presetOverridesState]);
// 切换正在编辑的预设:载入其 effective 浅色作为草稿起点
const handleSelectEditingPreset = (key) => {
setEditingPresetKey(key);
setPresetDraft({}); // 清空草稿,presetEditLight 会用该预设的 effective 浅色兜底
};
// 编辑单个 token + 即时整站预览(用临时覆盖 + applyTheme persist:false)
const previewPresetEdit = (nextDraft) => {
const nextLight = {
...getEffectivePreset(editingPresetKey).light,
...nextDraft,
};
const tempOverrides = {
...presetOverridesState,
[editingPresetKey]: { light: nextLight },
};
setPresetOverrides(JSON.stringify(tempOverrides), { persist: false });
applyTheme(JSON.stringify({ preset: editingPresetKey }), {
persist: false,
});
};
const handlePresetTokenChange = (tokenKey, value) => {
setPresetDraft((prev) => {
const next = { ...prev, [tokenKey]: value };
if (HEX_RE.test(value.trim())) previewPresetEdit(next);
return next;
});
};
const handlePresetTokenReset = (tokenKey) => {
// 重置单个 token 回内置默认(从草稿移除 + 用内置浅色补回)
setPresetDraft((prev) => {
const next = { ...prev };
next[tokenKey] = getPresetBuiltinLight(editingPresetKey)[tokenKey];
previewPresetEdit(next);
return next;
});
};
// 保存编辑后的预设模板到后端
const handleSavePreset = async () => {
// 仅校验 EDITABLE_TOKENS(目前 8 个) —— presetEditLight 还含 brand-primary-soft(rgba)
// 等非 hex 的派生 token,不能一并丢进 HEX 校验,否则永远拦下保存。
const invalid = EDITABLE_TOKENS.filter(
(tk) => !HEX_RE.test(String(presetEditLight[tk.key]).trim()),
).map((tk) => tk.key);
if (invalid.length) {
showError(
t('以下 token 不是合法 hex 颜色,请修正后再保存:{{tokens}}', {
tokens: invalid.join(', '),
}),
);
return;
}
setPresetSaving(true);
try {
// 只存与内置不同的 token;若与内置完全一致则视为"出厂",移除该预设覆盖
// 大小写不敏感:admin 用大写输入 hex 时不应被误判为"已修改"。
const builtin = getPresetBuiltinLight(editingPresetKey);
const diff = {};
EDITABLE_TOKENS.forEach((tk) => {
const v = presetEditLight[tk.key];
if (v && !hexEqual(v, builtin[tk.key])) diff[tk.key] = v;
});
const nextOverrides = { ...presetOverridesState };
if (Object.keys(diff).length === 0) {
delete nextOverrides[editingPresetKey];
} else {
nextOverrides[editingPresetKey] = { light: diff };
}
const payload = JSON.stringify(nextOverrides);
const res = await API.put('/api/option/', {
key: 'ThemePresets',
value: payload,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('预设模板已保存'));
setPresetOverrides(payload); // 持久化到 cache + 模块态
setPresetOverridesState(nextOverrides);
setPresetDraft({});
statusDispatch({
type: 'set',
payload: { ...(statusState?.status || {}), theme_presets: payload },
});
if (props.refresh) await props.refresh();
} else {
showError(message || t('保存失败'));
}
} catch {
showError(t('保存失败,请重试'));
} finally {
setPresetSaving(false);
}
};
// 恢复当前预设到出厂默认(移除该预设覆盖)
const handleRestorePreset = async () => {
setPresetSaving(true);
try {
const nextOverrides = { ...presetOverridesState };
delete nextOverrides[editingPresetKey];
const payload = JSON.stringify(nextOverrides);
const res = await API.put('/api/option/', {
key: 'ThemePresets',
value: payload,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('已恢复该预设出厂配色'));
setPresetOverrides(payload);
setPresetOverridesState(nextOverrides);
setPresetDraft({});
applyTheme(JSON.stringify({ preset: editingPresetKey }), {
persist: false,
});
statusDispatch({
type: 'set',
payload: { ...(statusState?.status || {}), theme_presets: payload },
});
if (props.refresh) await props.refresh();
} else {
showError(message || t('保存失败'));
}
} catch {
showError(t('保存失败,请重试'));
} finally {
setPresetSaving(false);
}
};
/* ============ 导入导出 ============ */
const handleExport = () => {
const config = {
preset: selectedPreset,
lightTokens: customLight,
darkTokens: customDark,
};
const blob = new Blob([JSON.stringify(config, null, 2)], {
type: 'application/json',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `theme-${selectedPreset}-${Date.now()}.json`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
showSuccess(t('已导出主题配置'));
};
const handleImportClick = () => fileInputRef.current?.click();
// 仅允许导入这些 token key,其他 key 一律丢弃 —— 防止 CSS 注入或污染 :root
// (恶意 value 会被注入到