feat(ui): 运营后台支持暗色模式与系统自适应切换

This commit is contained in:
yml
2026-11-20 23:12:39 +08:00
parent e6a9c2d81e
commit 7c2e01fb7e
8 changed files with 636 additions and 46 deletions
+16
View File
@@ -12,6 +12,22 @@
<link rel="icon" href="/favicon.ico" sizes="16x16 32x32 48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>运营后台管理中心</title>
<script>
;(function () {
try {
var pref = localStorage.getItem('app-theme-preference')
var isDark =
pref === 'dark' ||
(!pref &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
var theme = isDark ? 'dark' : 'light'
document.documentElement.setAttribute('data-theme', theme)
document.documentElement.classList.toggle('dark', isDark)
document.documentElement.style.colorScheme = theme
} catch (_) {}
})()
</script>
</head>
<body>
<div id="root"></div>
+86
View File
@@ -0,0 +1,86 @@
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import {
applyThemeToDom,
getStoredThemePreference,
getSystemTheme,
resolveEffectiveTheme,
setStoredThemePreference,
type ResolvedTheme,
type ThemePreference,
} from '@/utils/theme-mode'
export interface ThemeContextValue {
preference: ThemePreference
resolvedTheme: ResolvedTheme
isDark: boolean
setPreference: (pref: ThemePreference) => void
}
const ThemeContext = createContext<ThemeContextValue | null>(null)
export function ThemeProvider({ children }: { children: ReactNode }) {
const [preference, setPreferenceState] = useState<ThemePreference>(() =>
getStoredThemePreference(),
)
const [systemTheme, setSystemTheme] = useState<ResolvedTheme>(() => getSystemTheme())
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return
}
const media = window.matchMedia('(prefers-color-scheme: dark)')
const handleChange = (e: MediaQueryListEvent | MediaQueryList) => {
setSystemTheme(e.matches ? 'dark' : 'light')
}
// 初次主动同步一次,避免渲染初始差
setSystemTheme(media.matches ? 'dark' : 'light')
if (typeof media.addEventListener === 'function') {
media.addEventListener('change', handleChange)
return () => media.removeEventListener('change', handleChange)
}
// 兼容 Safari 旧版
media.addListener(handleChange)
return () => media.removeListener(handleChange)
}, [])
const resolvedTheme = resolveEffectiveTheme(preference, systemTheme)
const isDark = resolvedTheme === 'dark'
useEffect(() => {
applyThemeToDom(resolvedTheme)
}, [resolvedTheme])
const setPreference = (newPref: ThemePreference) => {
setStoredThemePreference(newPref)
setPreferenceState(newPref)
}
const value = useMemo(
() => ({
preference,
resolvedTheme,
isDark,
setPreference,
}),
[preference, resolvedTheme, isDark],
)
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
}
export function useThemeMode(): ThemeContextValue {
const context = useContext(ThemeContext)
if (!context) {
const fallbackTheme = resolveEffectiveTheme('system')
return {
preference: 'system',
resolvedTheme: fallbackTheme,
isDark: fallbackTheme === 'dark',
setPreference: () => {},
}
}
return context
}
+39
View File
@@ -6,16 +6,19 @@ import {
BranchesOutlined,
BugOutlined,
DashboardOutlined,
DesktopOutlined,
FileSearchOutlined,
LogoutOutlined,
LineChartOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
MoonOutlined,
OrderedListOutlined,
RobotOutlined,
SafetyCertificateOutlined,
SettingOutlined,
SoundOutlined,
SunOutlined,
TeamOutlined,
ThunderboltOutlined,
TrophyOutlined,
@@ -69,6 +72,8 @@ import {
shouldPrependAdminWorkOrder,
} from '@/utils/admin-realtime-work-orders'
import { useRealtimeEvents, type RealtimeEvent } from '@/hooks/useRealtimeEvents'
import { useThemeMode } from '@/hooks/useThemeMode'
import type { ThemePreference } from '@/utils/theme-mode'
import {
hasRemainingTimerDelay,
MAX_TIMER_DELAY_MS,
@@ -93,6 +98,24 @@ export default function AdminLayout() {
const [soundEnabled, setSoundEnabled] = useState(
() => window.localStorage.getItem(NOTIFICATION_SOUND_KEY) === '1',
)
const {
preference: themePref,
resolvedTheme,
isDark,
setPreference: setThemePref,
} = useThemeMode()
const themeTooltip = useMemo(() => {
if (themePref === 'system') {
return `外观模式:跟随系统 (${isDark ? '深色' : '浅色'})`
}
return themePref === 'dark' ? '外观模式:深色模式' : '外观模式:浅色模式'
}, [themePref, isDark])
const themeIcon = useMemo(() => {
if (themePref === 'system') return <DesktopOutlined />
return isDark ? <MoonOutlined /> : <SunOutlined />
}, [themePref, isDark])
const adminSessionQuery = useQuery({
queryKey: ['admin-session'],
@@ -480,6 +503,22 @@ export default function AdminLayout() {
<Layout className="admin-main-shell">
<Layout.Header className="admin-topbar">
<Space className="admin-user" size={12}>
<Dropdown
menu={{
selectedKeys: [themePref],
items: [
{ key: 'system', icon: <DesktopOutlined />, label: '跟随系统' },
{ key: 'light', icon: <SunOutlined />, label: '浅色模式' },
{ key: 'dark', icon: <MoonOutlined />, label: '深色模式' },
],
onClick: ({ key }) => setThemePref(key as ThemePreference),
}}
placement="bottomRight"
>
<Tooltip title={themeTooltip}>
<Button type="text" aria-label={themeTooltip} icon={themeIcon} />
</Tooltip>
</Dropdown>
<Tooltip title={soundEnabled ? '关闭通知声音' : '开启通知声音'}>
<Button
type="text"
+56 -31
View File
@@ -1,6 +1,6 @@
import React from 'react'
import React, { useMemo } from 'react'
import ReactDOM from 'react-dom/client'
import { App as AntdApp, ConfigProvider } from 'antd'
import { App as AntdApp, ConfigProvider, theme as antdTheme } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import 'antd/dist/reset.css'
@@ -10,6 +10,7 @@ import '@/lib/dayjs'
import App from './App'
import AppErrorBoundary from '@/components/common/AppErrorBoundary'
import { ThemeProvider, useThemeMode } from '@/hooks/useThemeMode'
import { shouldAutoReloadChunkFailure } from '@/utils/chunk-load-error'
import './styles/main.css'
@@ -36,8 +37,41 @@ const queryClient = new QueryClient({
},
})
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
function ThemedConfigProvider({ children }: { children: React.ReactNode }) {
const { isDark } = useThemeMode()
const themeConfig = useMemo(
() => ({
algorithm: isDark ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
token: {
colorPrimary: '#ff6a00',
colorLink: '#ff6a00',
colorInfo: '#ff6a00',
borderRadius: 6,
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
},
components: {
Layout: isDark
? {
bodyBg: '#141414',
headerBg: '#1f1f1f',
siderBg: '#1f1f1f',
}
: {
bodyBg: '#f5f7fb',
headerBg: '#ffffff',
siderBg: '#ffffff',
},
Card: {
borderRadiusLG: 6,
},
},
}),
[isDark],
)
return (
<ConfigProvider
locale={zhCN}
// 全局分页:常开条数切换(ConfigProvider 仅支持 showSizeChanger 等字段)
@@ -46,34 +80,25 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
showSizeChanger: true,
totalBoundaryShowSizeChanger: 0,
}}
theme={{
token: {
colorPrimary: '#ff6a00',
colorLink: '#ff6a00',
colorInfo: '#ff6a00',
borderRadius: 6,
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
},
components: {
Layout: {
bodyBg: '#f5f7fb',
headerBg: '#ffffff',
siderBg: '#ffffff',
},
Card: {
borderRadiusLG: 6,
},
},
}}
theme={themeConfig}
>
<AntdApp>
<QueryClientProvider client={queryClient}>
<AppErrorBoundary>
<App />
</AppErrorBoundary>
</QueryClientProvider>
</AntdApp>
{children}
</ConfigProvider>
)
}
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ThemeProvider>
<ThemedConfigProvider>
<AntdApp>
<QueryClientProvider client={queryClient}>
<AppErrorBoundary>
<App />
</AppErrorBoundary>
</QueryClientProvider>
</AntdApp>
</ThemedConfigProvider>
</ThemeProvider>
</React.StrictMode>,
)
+215 -10
View File
@@ -353,7 +353,7 @@
.admin-sider {
height: 100vh;
overflow: hidden;
border-right: 1px solid #edf0f5;
border-right: 1px solid var(--theme-border-color);
box-shadow: 4px 0 18px rgba(15, 23, 42, 0.04);
z-index: 2;
}
@@ -382,7 +382,7 @@
justify-content: space-between;
gap: 10px;
padding: 12px 14px 12px 18px;
border-bottom: 1px solid #edf0f5;
border-bottom: 1px solid var(--theme-border-color);
}
.admin-brand-copy {
@@ -392,26 +392,26 @@
}
.admin-brand strong {
color: #111827;
color: var(--theme-text-primary);
font-size: 18px;
}
.admin-brand span {
color: #6b7280;
color: var(--theme-text-secondary);
font-size: 12px;
}
.admin-collapse-button {
flex: 0 0 auto;
border-color: #e5e7eb;
border-color: var(--theme-border-color-strong);
}
.admin-sidebar-profile {
margin: 12px 14px 8px;
padding: 12px;
border: 1px solid #edf0f5;
border: 1px solid var(--theme-border-color);
border-radius: 6px;
background: #f8fafc;
background: var(--theme-bg-subtle);
display: grid;
gap: 3px;
line-height: 1.35;
@@ -444,14 +444,14 @@
.admin-menu .ant-menu-item-group-title {
padding: 12px 10px 6px;
color: #9ca3af;
color: var(--theme-text-tertiary);
font-size: 12px;
font-weight: 700;
}
.admin-sider-footer {
padding: 10px 14px 14px;
border-top: 1px solid #edf0f5;
border-top: 1px solid var(--theme-border-color);
}
.admin-sider.ant-layout-sider-collapsed .admin-brand {
@@ -484,7 +484,7 @@
align-items: center;
justify-content: flex-end;
padding: 0 20px;
border-bottom: 1px solid #edf0f5;
border-bottom: 1px solid var(--theme-border-color);
}
.admin-user {
@@ -2406,3 +2406,208 @@
grid-template-columns: 1fr;
}
}
/* ==========================================================================
运营后台暗色模式适配 (Admin Dark Mode Overrides)
========================================================================== */
[data-theme='dark'] .admin-sider {
box-shadow: 4px 0 18px rgba(0, 0, 0, 0.45);
}
[data-theme='dark'] .auth-page {
background:
linear-gradient(135deg, rgba(255, 106, 0, 0.08), transparent 30%),
linear-gradient(315deg, rgba(0, 0, 0, 0.5), transparent 38%), #141414;
}
[data-theme='dark'] .auth-shell {
background: #1f1f1f;
border-color: var(--theme-border-color);
box-shadow: 0 28px 72px rgba(0, 0, 0, 0.6);
}
[data-theme='dark'] .auth-form-side {
background: #1f1f1f;
}
[data-theme='dark'] .auth-form-header h1 {
color: var(--theme-text-primary);
}
[data-theme='dark'] .auth-form-header p {
color: var(--theme-text-secondary);
}
[data-theme='dark'] .auth-mobile-brand strong {
color: var(--theme-text-primary);
}
[data-theme='dark'] .manual-channel-config-item,
[data-theme='dark'] .manual-channel-cost-preview {
border-color: var(--theme-border-color);
background: var(--theme-bg-subtle);
}
[data-theme='dark'] .task-action-group,
[data-theme='dark'] .task-flow-item,
[data-theme='dark'] .task-screenshot-preview,
[data-theme='dark'] .finance-review-evidence,
[data-theme='dark'] .platform-route-rule,
[data-theme='dark'] .field-switch,
[data-theme='dark'] .empty-rule-hint {
border-color: var(--theme-border-color);
background: var(--theme-bg-subtle);
}
[data-theme='dark'] .field-switch span {
color: var(--theme-text-secondary);
}
[data-theme='dark'] .fulfillment-step-card,
[data-theme='dark'] .platform-select-card {
border-color: var(--theme-border-color);
background: var(--theme-bg-container);
}
[data-theme='dark'] .binding-editor-card {
background: #1c1c1c !important;
border-color: var(--theme-border-color) !important;
}
[data-theme='dark'] .binding-editor-card .ant-card-head {
background: #242424;
border-bottom: 1px solid var(--theme-border-color);
}
[data-theme='dark'] .binding-pill-tag {
background: var(--theme-bg-subtle) !important;
border-color: var(--theme-border-color-strong) !important;
color: var(--theme-text-secondary) !important;
}
[data-theme='dark'] .shop-selector-box-inline {
background: var(--theme-bg-subtle);
border-color: var(--theme-border-color-strong);
}
[data-theme='dark'] .shop-selector-box-inline .shop-all-toggle {
border-right-color: var(--theme-border-color);
}
[data-theme='dark'] .product-rules-form-card .ant-card-head,
[data-theme='dark'] .product-rules-list-card .ant-card-head,
[data-theme='dark'] .product-rules-category-tabs-bar {
border-bottom-color: var(--theme-border-color);
}
[data-theme='dark'] .product-rules-sub-category-bar {
background: var(--theme-bg-subtle);
border-color: var(--theme-border-color);
}
[data-theme='dark'] .sub-category-bar-label {
color: var(--theme-text-secondary);
}
[data-theme='dark'] .sub-category-pill {
color: var(--theme-text-secondary);
background: var(--theme-bg-container);
border-color: var(--theme-border-color-strong);
}
[data-theme='dark'] .sub-category-pill .pill-count {
background: rgba(255, 255, 255, 0.08);
color: var(--theme-text-secondary);
}
[data-theme='dark'] .product-rule-row-active > td,
[data-theme='dark'] .product-binding-row-active > td {
background: rgba(255, 106, 0, 0.12) !important;
}
[data-theme='dark'] .product-rule-row-mapped > td {
background: rgba(82, 196, 26, 0.1) !important;
}
[data-theme='dark'] .task-list-row-error > td,
[data-theme='dark'] .admin-share-row-problem > td {
background: rgba(255, 77, 79, 0.14) !important;
}
[data-theme='dark'] .task-list-row-error:hover > td,
[data-theme='dark'] .admin-share-row-problem:hover > td {
background: rgba(255, 77, 79, 0.22) !important;
}
[data-theme='dark'] .admin-share-row-cancelled > td {
color: var(--theme-text-tertiary) !important;
background: rgba(255, 255, 255, 0.03) !important;
}
[data-theme='dark'] .admin-share-row-cancelled:hover > td {
background: rgba(255, 255, 255, 0.06) !important;
}
[data-theme='dark'] .order-service-shell > .ant-card-head {
background: var(--theme-bg-container);
}
[data-theme='dark'] .order-service-sidebar {
background: #181818;
border-right-color: var(--theme-border-color);
border-bottom-color: var(--theme-border-color);
}
[data-theme='dark'] .order-service-sidebar-head {
border-bottom-color: var(--theme-border-color);
}
[data-theme='dark'] .order-service-category-item {
color: var(--theme-text-regular);
}
[data-theme='dark'] .order-service-category-item:hover,
[data-theme='dark'] .order-service-category-item.is-active {
background: var(--theme-bg-elevated);
border-color: var(--theme-primary);
}
[data-theme='dark'] .order-service-section,
[data-theme='dark'] .order-service-status-step-card,
[data-theme='dark'] .order-service-confirmation-editor,
[data-theme='dark'] .order-service-jobs-collapse {
border-color: var(--theme-border-color);
background: var(--theme-bg-container);
}
[data-theme='dark'] .order-service-guide,
[data-theme='dark'] .order-service-confirmation-switch,
[data-theme='dark'] .order-service-field-row {
border-color: var(--theme-border-color);
background: var(--theme-bg-subtle);
}
[data-theme='dark'] .order-service-confirmation-preview {
color: var(--theme-text-regular);
background: var(--theme-bg-container);
border-color: var(--theme-border-color);
}
[data-theme='dark'] .order-service-confirmation-preview-content {
color: var(--theme-text-secondary);
}
[data-theme='dark'] .order-service-confirmation-preview-summary {
color: var(--theme-text-regular);
background: var(--theme-bg-subtle);
border-color: var(--theme-border-color);
}
[data-theme='dark'] .order-service-confirmation-preview-actions {
border-top-color: var(--theme-border-color);
}
[data-theme='dark'] .order-service-save-bar {
background: linear-gradient(180deg, rgba(20, 20, 20, 0) 0%, #141414 28%, #141414 100%);
}
+37 -5
View File
@@ -5,14 +5,46 @@
--theme-primary-soft: #fff3e8;
--theme-primary-soft-hover: #ffe6d1;
--theme-primary-shadow: rgba(255, 106, 0, 0.14);
color: #1f2937;
background: #f5f7fb;
--theme-bg-body: #f5f7fb;
--theme-bg-container: #ffffff;
--theme-bg-elevated: #ffffff;
--theme-bg-subtle: #f8fafc;
--theme-text-primary: #111827;
--theme-text-regular: #1f2937;
--theme-text-secondary: #6b7280;
--theme-text-tertiary: #9ca3af;
--theme-border-color: #edf0f5;
--theme-border-color-split: #f0f0f0;
--theme-border-color-strong: #e5e7eb;
color: var(--theme-text-regular);
background: var(--theme-bg-body);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
[data-theme='dark'],
:root[data-theme='dark'] {
--theme-primary-soft: rgba(255, 106, 0, 0.16);
--theme-primary-soft-hover: rgba(255, 106, 0, 0.24);
--theme-primary-shadow: rgba(255, 106, 0, 0.28);
--theme-bg-body: #141414;
--theme-bg-container: #1f1f1f;
--theme-bg-elevated: #262626;
--theme-bg-subtle: #242424;
--theme-text-primary: rgba(255, 255, 255, 0.95);
--theme-text-regular: rgba(255, 255, 255, 0.85);
--theme-text-secondary: rgba(255, 255, 255, 0.55);
--theme-text-tertiary: rgba(255, 255, 255, 0.35);
--theme-border-color: #303030;
--theme-border-color-split: #303030;
--theme-border-color-strong: #424242;
color: var(--theme-text-regular);
background: var(--theme-bg-body);
color-scheme: dark;
}
* {
box-sizing: border-box;
}
@@ -50,7 +82,7 @@ select {
.page-description {
margin: 6px 0 0;
color: #6b7280;
color: var(--theme-text-secondary);
}
.filter-form {
@@ -64,7 +96,7 @@ select {
}
.muted {
color: #6b7280;
color: var(--theme-text-secondary);
}
.full-width {
@@ -76,7 +108,7 @@ select {
overflow: auto;
margin: 0;
padding: 14px;
border: 1px solid #edf0f5;
border: 1px solid var(--theme-border-color);
border-radius: 6px;
background: #0f172a;
color: #dbeafe;
+71
View File
@@ -0,0 +1,71 @@
export type ThemePreference = 'system' | 'light' | 'dark'
export type ResolvedTheme = 'light' | 'dark'
export const THEME_PREFERENCE_STORAGE_KEY = 'app-theme-preference'
/**
* 读取当前系统级色彩偏好
*/
export function getSystemTheme(): ResolvedTheme {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return 'light'
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
/**
* 读取用户保存的主题喜好设置,默认未设置时为 'system'(跟随系统)
*/
export function getStoredThemePreference(storage?: Storage): ThemePreference {
const targetStorage = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined)
if (!targetStorage) {
return 'system'
}
const value = targetStorage.getItem(THEME_PREFERENCE_STORAGE_KEY)
if (value === 'light' || value === 'dark' || value === 'system') {
return value
}
return 'system'
}
/**
* 保存用户的主题喜好;如为 'system' 则移除自定义项,恢复纯净跟随系统
*/
export function setStoredThemePreference(pref: ThemePreference, storage?: Storage): void {
const targetStorage = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined)
if (!targetStorage) {
return
}
if (pref === 'system') {
targetStorage.removeItem(THEME_PREFERENCE_STORAGE_KEY)
} else {
targetStorage.setItem(THEME_PREFERENCE_STORAGE_KEY, pref)
}
}
/**
* 根据喜好配置计算当前最终生效的明暗主题
*/
export function resolveEffectiveTheme(
preference: ThemePreference,
systemTheme: ResolvedTheme = getSystemTheme(),
): ResolvedTheme {
if (preference === 'system') {
return systemTheme
}
return preference
}
/**
* 将明暗主题属性同步到 DOM 根节点,以激活 CSS 选择器与原生色彩方案
*/
export function applyThemeToDom(theme: ResolvedTheme, doc?: Document): void {
const targetDoc = doc ?? (typeof document !== 'undefined' ? document : undefined)
if (!targetDoc) {
return
}
const root = targetDoc.documentElement
root.setAttribute('data-theme', theme)
root.classList.toggle('dark', theme === 'dark')
root.style.colorScheme = theme
}
+116
View File
@@ -0,0 +1,116 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
applyThemeToDom,
getStoredThemePreference,
resolveEffectiveTheme,
setStoredThemePreference,
THEME_PREFERENCE_STORAGE_KEY,
type ResolvedTheme,
type ThemePreference,
} from '../src/utils/theme-mode.ts'
function createMockStorage(initial: Record<string, string> = {}): Storage {
const store = new Map<string, string>(Object.entries(initial))
return {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => store.set(key, String(value)),
removeItem: (key: string) => store.delete(key),
clear: () => store.clear(),
key: (index: number) => Array.from(store.keys())[index] ?? null,
get length() {
return store.size
},
}
}
test('默认未设置时,主题偏好必须为 system(跟随系统)', () => {
const storage = createMockStorage()
assert.equal(getStoredThemePreference(storage), 'system')
})
test('读取存储的合法主题偏好与非法回退', () => {
const storage = createMockStorage({
[THEME_PREFERENCE_STORAGE_KEY]: 'dark',
})
assert.equal(getStoredThemePreference(storage), 'dark')
storage.setItem(THEME_PREFERENCE_STORAGE_KEY, 'light')
assert.equal(getStoredThemePreference(storage), 'light')
storage.setItem(THEME_PREFERENCE_STORAGE_KEY, 'invalid-value')
assert.equal(getStoredThemePreference(storage), 'system')
})
test('设置与移除主题偏好存储', () => {
const storage = createMockStorage()
setStoredThemePreference('dark', storage)
assert.equal(storage.getItem(THEME_PREFERENCE_STORAGE_KEY), 'dark')
setStoredThemePreference('light', storage)
assert.equal(storage.getItem(THEME_PREFERENCE_STORAGE_KEY), 'light')
// 设置为 system 应当移除 key,恢复纯净跟随系统
setStoredThemePreference('system', storage)
assert.equal(storage.getItem(THEME_PREFERENCE_STORAGE_KEY), null)
})
test('resolveEffectiveTheme 在各种偏好组合下的计算', () => {
// 跟随系统模式
assert.equal(resolveEffectiveTheme('system', 'dark'), 'dark')
assert.equal(resolveEffectiveTheme('system', 'light'), 'light')
// 显式锁定模式
assert.equal(resolveEffectiveTheme('light', 'dark'), 'light')
assert.equal(resolveEffectiveTheme('light', 'light'), 'light')
assert.equal(resolveEffectiveTheme('dark', 'dark'), 'dark')
assert.equal(resolveEffectiveTheme('dark', 'light'), 'dark')
})
test('applyThemeToDom 必须正确设置 data-theme、dark 类名及 colorScheme', () => {
const attributes = new Map<string, string>()
const classes = new Set<string>()
const style: Record<string, string> = {}
const mockDoc = {
documentElement: {
setAttribute: (k: string, v: string) => attributes.set(k, v),
getAttribute: (k: string) => attributes.get(k) ?? null,
classList: {
add: (c: string) => classes.add(c),
remove: (c: string) => classes.delete(c),
toggle: (c: string, force?: boolean) => {
if (force === true) {
classes.add(c)
return true
}
if (force === false) {
classes.delete(c)
return false
}
if (classes.has(c)) {
classes.delete(c)
return false
}
classes.add(c)
return true
},
contains: (c: string) => classes.has(c),
},
style,
},
} as unknown as Document
// 暗色
applyThemeToDom('dark', mockDoc)
assert.equal(attributes.get('data-theme'), 'dark')
assert.equal(classes.has('dark'), true)
assert.equal(style.colorScheme, 'dark')
// 浅色
applyThemeToDom('light', mockDoc)
assert.equal(attributes.get('data-theme'), 'light')
assert.equal(classes.has('dark'), false)
assert.equal(style.colorScheme, 'light')
})