1495 lines
49 KiB
React
1495 lines
49 KiB
React
/*
|
||
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 <https://www.gnu.org/licenses/>.
|
||
|
||
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 会被注入到 <style> 标签里,可能逃出当前规则破坏页面)
|
||
const ALLOWED_TOKEN_KEYS = new Set(EDITABLE_TOKENS.map((t) => t.key));
|
||
|
||
/** 过滤导入的 tokens,丢弃非白名单 key 与非 hex 值。 */
|
||
const sanitizeImportedTokens = (raw) => {
|
||
if (!raw || typeof raw !== 'object') return {};
|
||
const out = {};
|
||
for (const [k, v] of Object.entries(raw)) {
|
||
if (!ALLOWED_TOKEN_KEYS.has(k)) continue;
|
||
if (typeof v !== 'string') continue;
|
||
if (!HEX_RE.test(v.trim())) continue;
|
||
out[k] = v.trim();
|
||
}
|
||
return out;
|
||
};
|
||
|
||
const handleImportFile = (e) => {
|
||
const file = e.target.files?.[0];
|
||
if (!file) return;
|
||
const reader = new FileReader();
|
||
reader.onload = (ev) => {
|
||
try {
|
||
const cfg = JSON.parse(String(ev.target?.result || ''));
|
||
const presetKey =
|
||
cfg.preset && PRESETS[cfg.preset] ? cfg.preset : DEFAULT_PRESET_KEY;
|
||
const cleanLight = sanitizeImportedTokens(cfg.lightTokens);
|
||
const cleanDark = sanitizeImportedTokens(cfg.darkTokens);
|
||
const droppedLight =
|
||
Object.keys(cfg.lightTokens || {}).length -
|
||
Object.keys(cleanLight).length;
|
||
const droppedDark =
|
||
Object.keys(cfg.darkTokens || {}).length -
|
||
Object.keys(cleanDark).length;
|
||
setSelectedPreset(presetKey);
|
||
setCustomLight(cleanLight);
|
||
setCustomDark(cleanDark);
|
||
if (droppedLight + droppedDark > 0) {
|
||
showSuccess(
|
||
t('已导入,{{n}} 个非法/非白名单 token 已忽略', {
|
||
n: droppedLight + droppedDark,
|
||
}),
|
||
);
|
||
} else {
|
||
showSuccess(t('已导入主题配置'));
|
||
}
|
||
} catch {
|
||
showError(t('JSON 解析失败,请检查文件格式'));
|
||
}
|
||
};
|
||
reader.readAsText(file);
|
||
// 清空 input 以便同一文件可再次选择
|
||
e.target.value = '';
|
||
};
|
||
|
||
/* ============ 保存 ============ */
|
||
/** 校验所有自定义 token:必须是 6 位或 8 位 hex(HEX_RE),否则禁止保存。
|
||
* 这是写入服务端前的第一道防线(防御纵深,最终在 helpers/theme.js
|
||
* 注入点还有第二道)。返回非法 token key 列表,空数组表示全部合法。 */
|
||
const findInvalidTokens = (tokens) =>
|
||
Object.entries(tokens)
|
||
.filter(([_, v]) => typeof v !== 'string' || !HEX_RE.test(v.trim()))
|
||
.map(([k]) => k);
|
||
|
||
/** 过滤掉非法/已废弃的 token key,防止 stale 老数据永久残留服务器。
|
||
* 使用场景:升级后旧 ThemeConfig 可能仍含 bg-glow-via 等已删除的 key。
|
||
* light 用 EDITABLE_TOKENS 白名单;dark 用更宽的集合(含 hover/teal)。 */
|
||
const filterValidKeys = (tokens, validSet) => {
|
||
const out = {};
|
||
for (const k of Object.keys(tokens)) {
|
||
if (validSet.has(k)) out[k] = tokens[k];
|
||
}
|
||
return out;
|
||
};
|
||
|
||
const handleSave = async () => {
|
||
// 先过滤再校验:stale key(如 bg-glow-via)在过滤阶段就被丢弃,
|
||
// 不会因为 stale 是合法 hex 而误以为"无可保存"。
|
||
const cleanLight = filterValidKeys(customLight, VALID_LIGHT_TOKEN_KEYS);
|
||
const cleanDark = filterValidKeys(customDark, VALID_DARK_TOKEN_KEYS);
|
||
const invalidLight = findInvalidTokens(cleanLight);
|
||
const invalidDark = findInvalidTokens(cleanDark);
|
||
if (invalidLight.length || invalidDark.length) {
|
||
const all = [...invalidLight, ...invalidDark];
|
||
showError(
|
||
t('以下 token 不是合法 hex 颜色,请修正后再保存:{{tokens}}', {
|
||
tokens: all.join(', '),
|
||
}),
|
||
);
|
||
return;
|
||
}
|
||
setLoading(true);
|
||
try {
|
||
const payload = JSON.stringify({
|
||
preset: selectedPreset,
|
||
lightTokens: cleanLight,
|
||
darkTokens: cleanDark,
|
||
});
|
||
const res = await API.put('/api/option/', {
|
||
key: 'ThemeConfig',
|
||
value: payload,
|
||
});
|
||
const { success, message } = res.data;
|
||
if (success) {
|
||
showSuccess(t('保存成功'));
|
||
applyTheme(payload);
|
||
// 同步 React state 与 saved 一致 —— 若 stale key 被过滤掉了,
|
||
// customLight/customDark 也回到 clean 版本,dirty 立即归零。
|
||
setCustomLight(cleanLight);
|
||
setCustomDark(cleanDark);
|
||
setSaved({
|
||
preset: selectedPreset,
|
||
light: cleanLight,
|
||
dark: cleanDark,
|
||
});
|
||
// 同步 status(基于 statusState.status 而非 props.options,避免覆盖丢字段)
|
||
statusDispatch({
|
||
type: 'set',
|
||
payload: { ...(statusState?.status || {}), theme_config: payload },
|
||
});
|
||
if (props.refresh) await props.refresh();
|
||
} else {
|
||
showError(message || t('保存失败'));
|
||
}
|
||
} catch {
|
||
showError(t('保存失败,请重试'));
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
/* ============ 渲染 ============ */
|
||
const presetEntries = Object.entries(PRESETS);
|
||
|
||
return (
|
||
<Card>
|
||
<Form.Section
|
||
text={t('主题色配置')}
|
||
extraText={t('选择预设或自定义品牌色,所有用户立即生效')}
|
||
>
|
||
{/* 隐藏文件输入用于导入 */}
|
||
<input
|
||
ref={fileInputRef}
|
||
type='file'
|
||
accept='application/json,.json'
|
||
style={{ display: 'none' }}
|
||
onChange={handleImportFile}
|
||
/>
|
||
|
||
<Tabs
|
||
activeKey={mode}
|
||
onChange={setMode}
|
||
type='button'
|
||
style={{ marginBottom: 16 }}
|
||
>
|
||
<TabPane tab={t('预设色板')} itemKey='preset' />
|
||
<TabPane tab={t('自定义')} itemKey='custom' />
|
||
<TabPane tab={t('编辑预设模板')} itemKey='edit-preset' />
|
||
</Tabs>
|
||
|
||
{mode === 'preset' && (
|
||
<PresetGrid
|
||
presetEntries={presetEntries}
|
||
overridesVersion={presetOverridesState}
|
||
selectedPreset={selectedPreset}
|
||
savedPreset={saved.preset}
|
||
onSelect={handleSelectPreset}
|
||
t={t}
|
||
/>
|
||
)}
|
||
|
||
{mode === 'custom' && (
|
||
<CustomEditor
|
||
colorMode={colorMode}
|
||
setColorMode={setColorMode}
|
||
palette={effectivePalette}
|
||
customOverrides={colorMode === 'light' ? customLight : customDark}
|
||
onChange={handleTokenChange}
|
||
onResetToken={handleTokenReset}
|
||
onCopyToOther={handleCopyToOther}
|
||
onDeriveToDark={handleDeriveToDark}
|
||
onResetMode={handleResetCurrentMode}
|
||
selectedPreset={selectedPreset}
|
||
onChangePreset={setSelectedPreset}
|
||
t={t}
|
||
/>
|
||
)}
|
||
|
||
{mode === 'edit-preset' && (
|
||
<PresetTemplateEditor
|
||
editingPresetKey={editingPresetKey}
|
||
onSelectPreset={handleSelectEditingPreset}
|
||
light={presetEditLight}
|
||
isEdited={!!presetOverridesState[editingPresetKey]}
|
||
saving={presetSaving}
|
||
onTokenChange={handlePresetTokenChange}
|
||
onTokenReset={handlePresetTokenReset}
|
||
onSave={handleSavePreset}
|
||
onRestore={handleRestorePreset}
|
||
t={t}
|
||
/>
|
||
)}
|
||
|
||
{/* 底部操作栏:仅"预设/自定义"模式(编辑预设有自己的保存按钮) */}
|
||
{mode !== 'edit-preset' && (
|
||
<>
|
||
<div
|
||
style={{
|
||
display: 'flex',
|
||
gap: 8,
|
||
marginTop: 24,
|
||
flexWrap: 'wrap',
|
||
alignItems: 'center',
|
||
}}
|
||
>
|
||
<Button
|
||
type='primary'
|
||
theme='solid'
|
||
loading={loading}
|
||
disabled={!dirty}
|
||
onClick={handleSave}
|
||
>
|
||
{t('保存并应用')}
|
||
</Button>
|
||
<Button onClick={handleResetAll}>{t('重置为默认')}</Button>
|
||
<div style={{ flex: 1 }} />
|
||
<Button theme='borderless' onClick={handleExport}>
|
||
{t('导出 JSON')}
|
||
</Button>
|
||
<Button theme='borderless' onClick={handleImportClick}>
|
||
{t('导入 JSON')}
|
||
</Button>
|
||
</div>
|
||
|
||
<div style={{ marginTop: 12 }}>
|
||
<Text type='tertiary' size='small'>
|
||
{t(
|
||
'编辑过程中的颜色仅在当前会话中预览。点击"保存并应用"后,所有用户立即生效。',
|
||
)}
|
||
</Text>
|
||
</div>
|
||
</>
|
||
)}
|
||
</Form.Section>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
/* ============= 预设网格 ============= */
|
||
function PresetGrid({
|
||
presetEntries,
|
||
overridesVersion, // 仅用于在预设覆盖变化时触发重渲染
|
||
selectedPreset,
|
||
savedPreset,
|
||
onSelect,
|
||
t,
|
||
}) {
|
||
return (
|
||
<Row gutter={[16, 16]}>
|
||
{presetEntries.map(([key, preset]) => {
|
||
const isSelected = key === selectedPreset;
|
||
const isSaved = key === savedPreset;
|
||
// 用生效预设的浅色(反映管理员对预设模板的编辑)
|
||
const light = getEffectivePreset(key).light;
|
||
const isEdited = !!(overridesVersion && overridesVersion[key]);
|
||
return (
|
||
<Col key={key} xs={24} sm={12} md={8}>
|
||
<Card
|
||
shadows='hover'
|
||
onClick={() => onSelect(key)}
|
||
style={{
|
||
cursor: 'pointer',
|
||
borderRadius: 10,
|
||
border: isSelected
|
||
? '2px solid var(--semi-color-primary)'
|
||
: '1px solid var(--semi-color-border)',
|
||
transition: 'all 0.2s ease',
|
||
background: 'var(--semi-color-bg-1)',
|
||
}}
|
||
bodyStyle={{ padding: 16 }}
|
||
>
|
||
<div
|
||
style={{
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
gap: 12,
|
||
marginBottom: 12,
|
||
}}
|
||
>
|
||
<div
|
||
style={{
|
||
width: 40,
|
||
height: 40,
|
||
borderRadius: '50%',
|
||
background: light['brand-primary'],
|
||
boxShadow: `0 4px 12px ${light['brand-primary-soft']}`,
|
||
flexShrink: 0,
|
||
}}
|
||
aria-hidden
|
||
/>
|
||
<div
|
||
style={{
|
||
flex: 1,
|
||
height: 12,
|
||
borderRadius: 6,
|
||
background: `linear-gradient(135deg, ${light['brand-gradient-from']}, ${light['brand-gradient-via']}, ${light['brand-gradient-to']})`,
|
||
}}
|
||
aria-hidden
|
||
/>
|
||
</div>
|
||
<div
|
||
style={{
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
justifyContent: 'space-between',
|
||
marginBottom: 4,
|
||
}}
|
||
>
|
||
<Title heading={6} style={{ margin: 0 }}>
|
||
{t(preset.name)}
|
||
{isEdited && (
|
||
<Text
|
||
size='small'
|
||
type='tertiary'
|
||
style={{ marginLeft: 6, fontWeight: 400 }}
|
||
>
|
||
({t('已编辑')})
|
||
</Text>
|
||
)}
|
||
</Title>
|
||
{isSaved && (
|
||
<Text
|
||
size='small'
|
||
style={{ color: 'var(--semi-color-primary)' }}
|
||
>
|
||
{t('已应用')}
|
||
</Text>
|
||
)}
|
||
</div>
|
||
<Text type='secondary' size='small'>
|
||
{t(preset.desc)}
|
||
</Text>
|
||
</Card>
|
||
</Col>
|
||
);
|
||
})}
|
||
</Row>
|
||
);
|
||
}
|
||
|
||
/* ============= 编辑预设模板 ============= */
|
||
function PresetTemplateEditor({
|
||
editingPresetKey,
|
||
onSelectPreset,
|
||
light,
|
||
isEdited,
|
||
saving,
|
||
onTokenChange,
|
||
onTokenReset,
|
||
onSave,
|
||
onRestore,
|
||
t,
|
||
}) {
|
||
const builtin = getPresetBuiltinLight(editingPresetKey);
|
||
return (
|
||
<>
|
||
<div
|
||
style={{
|
||
marginBottom: 12,
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
gap: 8,
|
||
flexWrap: 'wrap',
|
||
}}
|
||
>
|
||
<Text type='secondary' size='small'>
|
||
{t('选择要编辑的预设:')}
|
||
</Text>
|
||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
|
||
{Object.entries(PRESETS).map(([key, p]) => (
|
||
<Button
|
||
key={key}
|
||
size='small'
|
||
theme={key === editingPresetKey ? 'solid' : 'light'}
|
||
type={key === editingPresetKey ? 'primary' : 'tertiary'}
|
||
onClick={() => onSelectPreset(key)}
|
||
>
|
||
{t(p.name)}
|
||
</Button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
|
||
<div style={{ marginBottom: 8 }}>
|
||
<Text type='tertiary' size='small'>
|
||
{t(
|
||
'只编辑浅色 6 个核心色,深色模式自动派生。保存后该预设卡片对所有用户更新。',
|
||
)}
|
||
</Text>
|
||
</div>
|
||
|
||
{/* 浅色预览 */}
|
||
<PreviewMini palette={light} colorMode='light' t={t} />
|
||
|
||
{/* 浅色 token 编辑(按分组渲染) */}
|
||
<div
|
||
style={{
|
||
marginTop: 16,
|
||
border: '1px solid var(--semi-color-border)',
|
||
borderRadius: 8,
|
||
padding: 12,
|
||
background: 'var(--semi-color-bg-1)',
|
||
}}
|
||
>
|
||
<GroupedTokenList
|
||
palette={light}
|
||
isCustomOf={(k) => !hexEqual(light[k], builtin[k])}
|
||
onChange={onTokenChange}
|
||
onReset={onTokenReset}
|
||
t={t}
|
||
/>
|
||
</div>
|
||
|
||
<div
|
||
style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}
|
||
>
|
||
<Button type='primary' theme='solid' loading={saving} onClick={onSave}>
|
||
{t('保存预设模板')}
|
||
</Button>
|
||
<Button disabled={!isEdited || saving} onClick={onRestore}>
|
||
{t('恢复此预设出厂')}
|
||
</Button>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ============= 自定义编辑器 ============= */
|
||
function CustomEditor({
|
||
colorMode,
|
||
setColorMode,
|
||
palette,
|
||
customOverrides,
|
||
onChange,
|
||
onResetToken,
|
||
onCopyToOther,
|
||
onDeriveToDark,
|
||
onResetMode,
|
||
selectedPreset,
|
||
onChangePreset,
|
||
t,
|
||
}) {
|
||
return (
|
||
<>
|
||
{/* 基础预设选择(决定未覆盖 token 的兜底值) */}
|
||
<div
|
||
style={{
|
||
marginBottom: 12,
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
gap: 8,
|
||
}}
|
||
>
|
||
<Text type='secondary' size='small'>
|
||
{t('基础预设:')}
|
||
</Text>
|
||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
|
||
{Object.entries(PRESETS).map(([key, p]) => (
|
||
<Button
|
||
key={key}
|
||
size='small'
|
||
theme={key === selectedPreset ? 'solid' : 'light'}
|
||
type={key === selectedPreset ? 'primary' : 'tertiary'}
|
||
onClick={() => onChangePreset(key)}
|
||
>
|
||
{t(p.name)}
|
||
</Button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
|
||
<Tabs
|
||
activeKey={colorMode}
|
||
onChange={setColorMode}
|
||
type='line'
|
||
style={{ marginBottom: 12 }}
|
||
>
|
||
<TabPane tab={t('浅色模式')} itemKey='light' />
|
||
<TabPane tab={t('深色模式')} itemKey='dark' />
|
||
</Tabs>
|
||
|
||
{/* 实时预览迷你卡 */}
|
||
<PreviewMini palette={palette} colorMode={colorMode} t={t} />
|
||
|
||
{/* token 编辑器(按分组渲染) */}
|
||
<div
|
||
style={{
|
||
marginTop: 16,
|
||
border: '1px solid var(--semi-color-border)',
|
||
borderRadius: 8,
|
||
padding: 12,
|
||
background: 'var(--semi-color-bg-1)',
|
||
}}
|
||
>
|
||
<GroupedTokenList
|
||
palette={palette}
|
||
isCustomOf={(k) => k in customOverrides}
|
||
onChange={onChange}
|
||
onReset={onResetToken}
|
||
t={t}
|
||
/>
|
||
</div>
|
||
|
||
<div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
|
||
<Button size='small' onClick={onCopyToOther}>
|
||
{colorMode === 'light'
|
||
? t('复制当前到深色模式')
|
||
: t('复制当前到浅色模式')}
|
||
</Button>
|
||
{/* 仅 light→dark 方向提供"按规则派生"——与"编辑预设模板"的光暗联动同源 */}
|
||
{colorMode === 'light' && (
|
||
<Button
|
||
size='small'
|
||
onClick={onDeriveToDark}
|
||
title={t(
|
||
'按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致',
|
||
)}
|
||
>
|
||
{t('派生到深色(自动调亮)')}
|
||
</Button>
|
||
)}
|
||
<Button size='small' theme='borderless' onClick={onResetMode}>
|
||
{colorMode === 'light' ? t('重置浅色覆盖') : t('重置深色覆盖')}
|
||
</Button>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ============= token 分组列表 =============
|
||
* 按 TOKEN_GROUPS 顺序渲染,每组前加小标题 + 说明,便于用户辨认
|
||
* 「品牌 vs 背景晕染 vs 强调」三个职责的色板各自影响什么。 */
|
||
function GroupedTokenList({ palette, isCustomOf, onChange, onReset, t }) {
|
||
return (
|
||
<>
|
||
{TOKEN_GROUPS.map((g, gi) => {
|
||
const tokens = EDITABLE_TOKENS.filter((tk) => tk.group === g.key);
|
||
if (tokens.length === 0) return null;
|
||
return (
|
||
<div
|
||
key={g.key}
|
||
style={{
|
||
marginTop: gi === 0 ? 0 : 12,
|
||
paddingTop: gi === 0 ? 0 : 12,
|
||
borderTop:
|
||
gi === 0 ? 'none' : '1px dashed var(--semi-color-border)',
|
||
}}
|
||
>
|
||
<div style={{ marginBottom: 6, padding: '0 4px' }}>
|
||
<div
|
||
style={{
|
||
fontSize: 12,
|
||
fontWeight: 600,
|
||
color: 'var(--semi-color-text-1)',
|
||
}}
|
||
>
|
||
{t(g.labelKey)}
|
||
</div>
|
||
<Text type='tertiary' size='small' style={{ fontSize: 11 }}>
|
||
{t(g.descKey)}
|
||
</Text>
|
||
</div>
|
||
{tokens.map((tok) => (
|
||
<TokenRow
|
||
key={tok.key}
|
||
label={t(tok.labelKey)}
|
||
desc={t(tok.descKey)}
|
||
value={palette[tok.key]}
|
||
isCustom={isCustomOf(tok.key)}
|
||
onChange={(v) => onChange(tok.key, v)}
|
||
onReset={() => onReset(tok.key)}
|
||
/>
|
||
))}
|
||
</div>
|
||
);
|
||
})}
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ============= 单个 token 行(含透明度) =============
|
||
* value 为 #RRGGBB(不透明)或 #RRGGBBAA(带透明度)。
|
||
* 原生取色器只编辑 RGB;透明度由独立滑块控制;合成回 hex。 */
|
||
const CHECKERBOARD =
|
||
'repeating-conic-gradient(#cfcfcf 0% 25%, #ffffff 0% 50%) 50% / 12px 12px';
|
||
|
||
function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
|
||
const c = colord(value || '#000000');
|
||
const valid = c.isValid();
|
||
const rgbHex = valid ? c.toHex().slice(0, 7) : '#000000'; // #RRGGBB 供原生取色器
|
||
const alphaPct = valid ? Math.round(c.alpha() * 100) : 100;
|
||
|
||
// colord.toHex():alpha=1 → 6 位,alpha<1 → 8 位,天然兼容存储格式
|
||
const emit = (hex, pct) =>
|
||
onChange(
|
||
colord(hex)
|
||
.alpha(pct / 100)
|
||
.toHex(),
|
||
);
|
||
|
||
return (
|
||
<div
|
||
style={{
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
gap: 10,
|
||
padding: '8px 4px',
|
||
borderBottom: '1px solid var(--semi-color-fill-0)',
|
||
}}
|
||
>
|
||
{/* 色块(棋盘垫底显示透明度,点击触发 native picker 改 RGB) */}
|
||
<label
|
||
style={{
|
||
position: 'relative',
|
||
width: 36,
|
||
height: 36,
|
||
flexShrink: 0,
|
||
cursor: 'pointer',
|
||
borderRadius: 8,
|
||
background: CHECKERBOARD,
|
||
border: '1px solid var(--semi-color-border)',
|
||
boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
|
||
overflow: 'hidden',
|
||
}}
|
||
aria-label={label}
|
||
>
|
||
<span
|
||
style={{
|
||
position: 'absolute',
|
||
inset: 0,
|
||
background: valid ? c.toRgbString() : '#000',
|
||
}}
|
||
/>
|
||
<input
|
||
type='color'
|
||
value={rgbHex}
|
||
onChange={(e) => emit(e.target.value, alphaPct)}
|
||
style={{
|
||
position: 'absolute',
|
||
inset: 0,
|
||
opacity: 0,
|
||
cursor: 'pointer',
|
||
border: 'none',
|
||
}}
|
||
/>
|
||
</label>
|
||
|
||
{/* 描述 */}
|
||
<div style={{ flex: 1, minWidth: 0 }}>
|
||
<div style={{ fontWeight: 500, fontSize: 13 }}>{label}</div>
|
||
<Text
|
||
type='tertiary'
|
||
size='small'
|
||
style={{ fontSize: 11, display: 'block' }}
|
||
>
|
||
{desc}
|
||
</Text>
|
||
</div>
|
||
|
||
{/* 透明度滑块 + 百分比 */}
|
||
<div
|
||
style={{ display: 'flex', alignItems: 'center', gap: 6, width: 130 }}
|
||
title={t_alpha(alphaPct)}
|
||
>
|
||
<input
|
||
type='range'
|
||
min={0}
|
||
max={100}
|
||
step={1}
|
||
value={alphaPct}
|
||
onChange={(e) => emit(rgbHex, Number(e.target.value))}
|
||
style={{
|
||
flex: 1,
|
||
accentColor: 'var(--brand-primary)',
|
||
cursor: 'pointer',
|
||
}}
|
||
aria-label={`${label} alpha`}
|
||
/>
|
||
<span
|
||
style={{
|
||
width: 34,
|
||
textAlign: 'right',
|
||
fontSize: 11,
|
||
fontVariantNumeric: 'tabular-nums',
|
||
color: 'var(--semi-color-text-2)',
|
||
}}
|
||
>
|
||
{alphaPct}%
|
||
</span>
|
||
</div>
|
||
|
||
{/* hex 输入(6 或 8 位) */}
|
||
<Input
|
||
size='small'
|
||
value={value || ''}
|
||
onChange={(v) => onChange(v.trim())}
|
||
style={{ width: 104, fontFamily: 'monospace' }}
|
||
placeholder='#RRGGBBAA'
|
||
validateStatus={value && !HEX_RE.test(value) ? 'error' : 'default'}
|
||
/>
|
||
|
||
{/* 重置(只在自定义覆盖时显示) */}
|
||
<Button
|
||
size='small'
|
||
theme='borderless'
|
||
disabled={!isCustom}
|
||
onClick={onReset}
|
||
style={{ opacity: isCustom ? 1 : 0.3 }}
|
||
>
|
||
↺
|
||
</Button>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 透明度 tooltip 文案(避免在子组件再取 t,用纯函数生成) */
|
||
function t_alpha(pct) {
|
||
return `透明度 ${pct}%`;
|
||
}
|
||
|
||
/* ============= 迷你预览 =============
|
||
* 上排:品牌前景元素(按钮 / 链接 / 气泡 / 滚动条 / 强调色),走 brand-* 色族。
|
||
* 下排:页面背景晕染示例(顶部→底部渐变 + 顶/底小光晕),独立走 bg-glow-* 色族,
|
||
* 让用户能直观对比两组色板互不影响。 */
|
||
function PreviewMini({ palette, colorMode, t }) {
|
||
const isDark = colorMode === 'dark';
|
||
return (
|
||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||
{/* —— 前景:按钮 / 气泡 / 强调色 —— */}
|
||
<div
|
||
style={{
|
||
padding: 16,
|
||
borderRadius: 10,
|
||
border: '1px solid var(--semi-color-border)',
|
||
background: isDark ? '#101014' : '#f6f8fb',
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
gap: 16,
|
||
flexWrap: 'wrap',
|
||
}}
|
||
>
|
||
<div
|
||
style={{
|
||
padding: '8px 16px',
|
||
borderRadius: 8,
|
||
color: '#fff',
|
||
fontWeight: 500,
|
||
fontSize: 13,
|
||
background: `linear-gradient(135deg, ${palette['brand-gradient-from']} 0%, ${palette['brand-gradient-via']} 50%, ${palette['brand-gradient-to']} 100%)`,
|
||
boxShadow: `0 4px 12px ${palette['brand-primary-soft'] || 'rgba(0,0,0,0.1)'}`,
|
||
}}
|
||
>
|
||
{t('主按钮')}
|
||
</div>
|
||
|
||
<a
|
||
style={{
|
||
color: palette['brand-primary'],
|
||
textDecoration: 'underline',
|
||
fontSize: 13,
|
||
}}
|
||
>
|
||
{t('链接示例')}
|
||
</a>
|
||
|
||
<div
|
||
style={{
|
||
padding: '8px 14px',
|
||
borderRadius: '14px 14px 4px 14px',
|
||
color: '#fff',
|
||
fontSize: 12,
|
||
background: `linear-gradient(135deg, ${palette['brand-gradient-from']} 0%, ${palette['brand-gradient-via']} 50%, ${palette['brand-gradient-to']} 100%)`,
|
||
}}
|
||
>
|
||
{t('聊天气泡')}
|
||
</div>
|
||
|
||
<div
|
||
style={{
|
||
width: 120,
|
||
height: 8,
|
||
borderRadius: 4,
|
||
background: `linear-gradient(180deg, color-mix(in srgb, ${palette['brand-primary']} 25%, transparent), color-mix(in srgb, ${palette['brand-primary']} 15%, transparent))`,
|
||
}}
|
||
title={t('滚动条')}
|
||
/>
|
||
|
||
<div style={{ display: 'flex', gap: 6 }}>
|
||
<div
|
||
style={{
|
||
width: 24,
|
||
height: 24,
|
||
borderRadius: '50%',
|
||
background: palette['accent-blue'],
|
||
}}
|
||
title={t('强调蓝')}
|
||
/>
|
||
<div
|
||
style={{
|
||
width: 24,
|
||
height: 24,
|
||
borderRadius: '50%',
|
||
background: palette['accent-emerald'],
|
||
}}
|
||
title={t('强调翠绿')}
|
||
/>
|
||
</div>
|
||
|
||
<Text type='tertiary' size='small' style={{ marginLeft: 'auto' }}>
|
||
{t('前景:brand-*')}
|
||
</Text>
|
||
</div>
|
||
|
||
{/* —— 背景晕染:模拟一个页面背景 —— */}
|
||
<div
|
||
style={{
|
||
position: 'relative',
|
||
height: 96,
|
||
borderRadius: 10,
|
||
border: '1px solid var(--semi-color-border)',
|
||
background: isDark ? '#0a0a0f' : '#f6f8fb',
|
||
overflow: 'hidden',
|
||
}}
|
||
>
|
||
{/* 渐变底层 —— 透明度与 UserCenter 主背景(最先暴露给用户的页面)对齐,
|
||
* 保证 admin 在这里调出的效果就是在 user-center/topup 看到的效果。 */}
|
||
<div
|
||
style={{
|
||
position: 'absolute',
|
||
inset: 0,
|
||
background: isDark
|
||
? `linear-gradient(180deg, color-mix(in srgb, ${palette['bg-glow-from']} 10%, transparent), transparent 50%, color-mix(in srgb, ${palette['bg-glow-to']} 15%, transparent))`
|
||
: `linear-gradient(180deg, color-mix(in srgb, ${palette['bg-glow-from']} 10%, transparent), transparent 50%, color-mix(in srgb, ${palette['bg-glow-to']} 20%, transparent))`,
|
||
}}
|
||
/>
|
||
{/* 右上小光晕 blob —— 与 UserCenter 顶部 blob 一致的 10% */}
|
||
<div
|
||
style={{
|
||
position: 'absolute',
|
||
top: -20,
|
||
right: -20,
|
||
width: 100,
|
||
height: 100,
|
||
borderRadius: '50%',
|
||
background: `color-mix(in srgb, ${palette['bg-glow-from']} 10%, transparent)`,
|
||
filter: 'blur(28px)',
|
||
}}
|
||
/>
|
||
{/* 左下小光晕 blob —— 与 UserCenter 底部 blob 一致的 10% */}
|
||
<div
|
||
style={{
|
||
position: 'absolute',
|
||
bottom: -20,
|
||
left: -20,
|
||
width: 120,
|
||
height: 120,
|
||
borderRadius: '50%',
|
||
background: `color-mix(in srgb, ${palette['bg-glow-to']} 10%, transparent)`,
|
||
filter: 'blur(32px)',
|
||
}}
|
||
/>
|
||
{/* 中心一个模拟内容卡 —— 与全站统一的 .app-card「云平台轻玻璃」对齐
|
||
* (surface-card 80% / 暗 72% + blur(16) saturate(1.4) + border-subtle),
|
||
* 让管理员预览看到的卡片强度 = 实际页面卡片强度,避免预览与实际不符。 */}
|
||
<div
|
||
style={{
|
||
position: 'absolute',
|
||
inset: '18px 24px',
|
||
borderRadius: 8,
|
||
background: isDark
|
||
? 'color-mix(in srgb, var(--surface-card) 72%, transparent)'
|
||
: 'color-mix(in srgb, var(--surface-card) 80%, transparent)',
|
||
border: '1px solid var(--border-subtle)',
|
||
backdropFilter: 'blur(16px) saturate(1.4)',
|
||
WebkitBackdropFilter: 'blur(16px) saturate(1.4)',
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
justifyContent: 'space-between',
|
||
padding: '0 14px',
|
||
}}
|
||
>
|
||
<Text size='small' style={{ fontWeight: 500 }}>
|
||
{t('页面内容示意')}
|
||
</Text>
|
||
<Text type='tertiary' size='small'>
|
||
{t('背景:bg-glow-*')}
|
||
</Text>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|