Files
monkey-ai-web/src/components/ui/UiThemeProvider.jsx
T

287 lines
9.8 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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, { useEffect, useLayoutEffect, useMemo, useState } from 'react';
import { App, ConfigProvider, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import zhTW from 'antd/locale/zh_TW';
import enGB from 'antd/locale/en_GB';
import jaJP from 'antd/locale/ja_JP';
import koKR from 'antd/locale/ko_KR';
import viVN from 'antd/locale/vi_VN';
import thTH from 'antd/locale/th_TH';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/zh-tw';
import 'dayjs/locale/en-gb';
import 'dayjs/locale/ja';
import 'dayjs/locale/ko';
import 'dayjs/locale/vi';
import 'dayjs/locale/th';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { useActualTheme } from '../../context/Theme';
import { normalizeLanguage } from '../../i18n/language';
import { colord } from 'colord';
import './antd-v5-compat.css';
// 与下方 Ant Design locale 一一对应的 dayjs 语言(未覆盖语言与 Ant Design 一样回退中文)。
const DAYJS_LOCALES = {
zh: 'zh-cn',
'zh-TW': 'zh-tw',
en: 'en-gb',
ja: 'ja',
ko: 'ko',
vi: 'vi',
th: 'th',
};
// 在线原型暗色:种子 #f2ad41 经 Ant Design 暗色算法推导出主色 #d1963a(悬停 #e8ba65、
// 选中背景 #574222 等)。系统以“最终主色”(--brand-primary) 作为 colorPrimary,
// 算法其余衍生令牌需仍按原型种子推导,否则会从 #d1963a 再推一次而整体偏暗。
const PROTOTYPE_DARK_PRIMARY = '#d1963a';
const PROTOTYPE_DARK_SEED = '#f2ad41';
// v5 used these shadows in both themes; v6 derives white shadows in dark mode.
const v5ShadowTokens = {
...Object.fromEntries(
Object.entries(theme.getDesignToken()).filter(([name]) =>
name.startsWith('boxShadow'),
),
),
boxShadowTertiary:
'0 1px 2px 0 rgba(0,0,0,0.03), 0 1px 6px -1px rgba(0,0,0,0.02), 0 2px 4px 0 rgba(0,0,0,0.02)',
};
// 页面局部“品牌强调色”(原型 --brand):等于当前主题的种子色。
// 浅色与自定义主色时即 colorPrimary;仅默认暗色主色 #d1963a 时回到原型种子 #f2ad41,
// 保证浅色 / 深色 / 自定义主题色三态都只由主题 token 推导,不在页面里另写颜色。
export const brandAccentFromToken = (colorPrimary, dark) =>
dark && colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
? PROTOTYPE_DARK_SEED
: colorPrimary;
export const prototypeTheme = (dark) => ({
algorithm: (seed, map) => {
const derive =
dark && seed.colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
? {
...seed,
colorPrimary: PROTOTYPE_DARK_SEED,
colorInfo: PROTOTYPE_DARK_SEED,
}
: seed;
return {
...(dark ? theme.darkAlgorithm : theme.defaultAlgorithm)(derive, map),
colorPrimary: seed.colorPrimary,
colorInfo: seed.colorInfo,
};
},
token: {
...v5ShadowTokens,
colorPrimary: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508',
colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508',
colorBgLayout: dark ? '#11151c' : '#f4f6f9',
colorBgContainer: dark ? '#1b212b' : '#ffffff',
colorText: dark ? '#e6ebf3' : '#263247',
colorTextSecondary: dark ? '#8e9aaa' : '#7e8998',
colorBorderSecondary: dark ? '#2b333f' : '#e9edf2',
borderRadius: 8,
fontFamily: '"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif',
controlHeight: 34,
},
components: {
Layout: {
headerBg: dark ? '#1b212b' : '#ffffff',
siderBg: dark ? '#1b212b' : '#ffffff',
},
Menu: {
itemHeight: 42,
itemSelectedBg: dark ? '#382b1b' : '#fff3df',
itemSelectedColor: dark ? '#f2ad41' : '#a95d07',
},
Card: { headerFontSize: 15 },
Modal: { borderRadiusLG: 12 },
},
});
// Keep v5 tag borders and overlay masks while inheriting the existing theme.
const v5ComponentDefaults = {
tag: { variant: 'outlined' },
modal: { mask: { blur: false } },
drawer: { mask: { blur: false } },
};
function TokenBridge() {
const { token } = theme.useToken();
useLayoutEffect(() => {
const values = {
'ui-color-white': '#fff',
'ui-color-black': '#000',
...Object.fromEntries(
[0, 1, 2, 3, 4].map((i) => [
`ui-color-bg-${i}`,
i === 0 ? token.colorBgLayout : token.colorBgContainer,
]),
),
...Object.fromEntries(
[
token.colorText,
token.colorTextSecondary,
token.colorTextTertiary,
token.colorTextQuaternary,
].map((v, i) => [`ui-color-text-${i}`, v]),
),
...Object.fromEntries(
[
token.colorFillQuaternary,
token.colorFillTertiary,
token.colorFillSecondary,
].map((v, i) => [`ui-color-fill-${i}`, v]),
),
'ui-color-border': token.colorBorder,
'ui-color-disabled-bg': token.colorBgContainerDisabled,
'ui-color-disabled-text': token.colorTextDisabled,
'ui-color-shadow': token.boxShadow,
'ui-color-link': token.colorLink,
'ui-color-link-hover': token.colorLinkHover,
'ui-color-focus-border': token.colorPrimary,
'ui-color-highlight-bg': token.colorPrimaryBg,
'ui-color-highlight': token.colorPrimaryText,
'ui-color-text': token.colorText,
'ui-color-border-light': token.colorBorderSecondary,
'ui-color-disabled-border': token.colorBorder,
'ui-color-tertiary': token.colorTextTertiary,
'ui-border-radius-small': `${token.borderRadiusSM}px`,
'ui-border-radius-medium': `${token.borderRadius}px`,
'ui-font-family-mono': token.fontFamilyCode,
};
const rgb = (color) => {
const { r, g, b } = colord(color).toRgb();
return `${r}, ${g}, ${b}`;
};
values['ui-color-primary-rgb'] = rgb(token.colorPrimary);
for (const name of [
'blue',
'green',
'purple',
'violet',
'grey',
'primary',
]) {
const color =
name === 'grey'
? token.colorTextSecondary
: name === 'primary'
? token.colorPrimary
: token[`${name === 'violet' ? 'purple' : name}6`];
values[`ui-${name}-5`] = rgb(color);
values[`ui-${name}-0`] = rgb(
name === 'grey' ? token.colorFillQuaternary : token.colorPrimaryBg,
);
values[`ui-${name}-1`] = rgb(
name === 'grey' ? token.colorFillTertiary : token.colorPrimaryBgHover,
);
}
for (const name of ['primary', 'info', 'success', 'warning', 'danger']) {
const antName =
name === 'danger' ? 'Error' : name[0].toUpperCase() + name.slice(1);
for (const [suffix, antSuffix] of Object.entries({
'': '',
'-hover': 'Hover',
'-active': 'Active',
'-disabled': 'Border',
'-light-default': 'Bg',
'-light-hover': 'BgHover',
'-light-active': 'Border',
}))
values[`ui-color-${name}${suffix}`] =
token[`color${antName}${antSuffix}`];
}
for (const [name, value] of Object.entries(values))
if (value != null) document.body.style.setProperty(`--${name}`, value);
}, [token]);
return null;
}
export default function UiThemeProvider({ children }) {
const dark = useActualTheme() === 'dark';
const { i18n } = useTranslation();
const { pathname } = useLocation();
const [revision, setRevision] = useState(0);
useEffect(() => {
const frame = requestAnimationFrame(() =>
setRevision((value) => value + 1),
);
return () => cancelAnimationFrame(frame);
}, [dark]);
useEffect(() => {
const update = () => setRevision((value) => value + 1);
window.addEventListener('theme-tokens-applied', update);
return () => window.removeEventListener('theme-tokens-applied', update);
}, []);
// Re-read the computed brand when the existing CSS theme is applied.
const config = useMemo(() => {
const result = prototypeTheme(dark);
// Keep existing configured brand previews and persistence in helpers/theme.js.
const brand = getComputedStyle(document.body)
.getPropertyValue('--brand-primary')
.trim();
if (brand) result.token.colorPrimary = brand;
return result;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dark, revision]);
const language = normalizeLanguage(i18n.language);
const locale =
{
zh: zhCN,
'zh-TW': zhTW,
en: enGB,
ja: jaJP,
ko: koKR,
vi: viVN,
th: thTH,
}[language] || zhCN;
// 日期面板的星期、月份名称来自 dayjs 全局语言,需与 Ant Design locale 保持一致。
dayjs.locale(DAYJS_LOCALES[language] || 'zh-cn');
useLayoutEffect(() => {
document.body.dataset.uiScope =
pathname.startsWith('/weyai/') || pathname.startsWith('/client/authorize')
? 'external'
: 'admin';
}, [pathname]);
useEffect(() => {
ConfigProvider.config({
holderRender: (nodes) => (
<ConfigProvider {...v5ComponentDefaults} theme={config} locale={locale}>
{nodes}
</ConfigProvider>
),
});
}, [config, locale]);
return (
<ConfigProvider {...v5ComponentDefaults} theme={config} locale={locale}>
<App>
<TokenBridge />
{children}
</App>
</ConfigProvider>
);
}