Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 43 additions & 44 deletions src/components/site/theme-toggle.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,47 @@
/**
* 主题三档切换(SPEC §3B / §8.3):亮 / 暗 / 自动,默认自动。
* 主题三档单击循环切换:自动 → 亮色 → 暗色 → 自动。
*
* - 偏好只存浏览器本地(localStorage `hub-theme`),本站无登录、无后端。
* - 首屏防闪烁由 BaseLayout `<head>` 里的内联脚本完成(先于绘制应用 class);
* 本 island 只负责交互与「自动档跟随系统实时变化」。
* - 三段用 shadcn/ui DropdownMenu 单选组,键盘可操作。
* - 单击图标按钮直接前进一档,无下拉菜单与浮层;Enter / Space 原生键盘支持。
*/
import { useEffect, useState } from 'react';
import { Monitor, Moon, Sun } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

export const THEME_STORAGE_KEY = 'hub-theme';
export type ThemeMode = 'system' | 'light' | 'dark';

const MODES: { value: ThemeMode; label: string; icon: typeof Sun }[] = [
{ value: 'system', label: '自动(跟随系统)', icon: Monitor },
{ value: 'light', label: '亮色', icon: Sun },
{ value: 'dark', label: '暗色', icon: Moon },
];
export const NEXT_THEME_MODE: Record<ThemeMode, ThemeMode> = {
system: 'light',
light: 'dark',
dark: 'system',
};

const FALLBACK_MODE = { value: 'system' as ThemeMode, label: '自动(跟随系统)', icon: Monitor };
export const THEME_LABELS: Record<ThemeMode, string> = {
system: '自动',
light: '亮色',
dark: '暗色',
};

function readStoredMode(): ThemeMode {
export const THEME_ICONS: Record<ThemeMode, typeof Sun> = {
system: Monitor,
light: Sun,
dark: Moon,
};

export function getNextMode(mode: ThemeMode): ThemeMode {
return NEXT_THEME_MODE[mode] ?? 'system';
}

export function getThemeAriaLabel(currentMode: ThemeMode): string {
const nextMode = getNextMode(currentMode);
return `主题:${THEME_LABELS[currentMode]},点击切换到${THEME_LABELS[nextMode]}`;
}

export function readStoredMode(): ThemeMode {
try {
const stored = window.localStorage.getItem(THEME_STORAGE_KEY);
if (stored === 'light' || stored === 'dark' || stored === 'system') return stored;
Expand Down Expand Up @@ -71,8 +81,8 @@ export default function ThemeToggle() {
return () => media.removeEventListener('change', onChange);
}, [mode]);

const handleChange = (value: string) => {
const next = (value === 'light' || value === 'dark' ? value : 'system') as ThemeMode;
const handleToggle = () => {
const next = getNextMode(mode);
setMode(next);
try {
window.localStorage.setItem(THEME_STORAGE_KEY, next);
Expand All @@ -82,31 +92,20 @@ export default function ThemeToggle() {
applyTheme(next);
};

const current = MODES.find((item) => item.value === mode) ?? FALLBACK_MODE;
const Icon = current.icon;
const currentMode = mode in NEXT_THEME_MODE ? mode : 'system';
const Icon = THEME_ICONS[currentMode];
const label = getThemeAriaLabel(currentMode);

return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" aria-label={`主题:${current.label}`} title="切换主题">
<Icon aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuLabel>主题</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuRadioGroup value={mode} onValueChange={handleChange}>
{MODES.map((item) => {
const ItemIcon = item.icon;
return (
<DropdownMenuRadioItem key={item.value} value={item.value}>
<ItemIcon aria-hidden="true" />
{item.label}
</DropdownMenuRadioItem>
);
})}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<Button
type="button"
variant="ghost"
size="icon"
onClick={handleToggle}
aria-label={label}
title={label}
>
<Icon aria-hidden="true" />
</Button>
);
}
159 changes: 159 additions & 0 deletions tests/theme-toggle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/**
* 主题切换单元测试(单击循环切换:自动 → 亮色 → 暗色 → 自动)。
*/
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { Monitor, Moon, Sun } from 'lucide-react';

import {
NEXT_THEME_MODE,
THEME_ICONS,
THEME_LABELS,
THEME_STORAGE_KEY,
applyTheme,
getNextMode,
getThemeAriaLabel,
readStoredMode,
type ThemeMode,
} from '../src/components/site/theme-toggle.js';

test('存储键常量为 hub-theme', () => {
assert.equal(THEME_STORAGE_KEY, 'hub-theme');
});

test('循环顺序沿用三档:自动(system) → 亮色(light) → 暗色(dark) → 自动(system)', () => {
assert.equal(NEXT_THEME_MODE.system, 'light');
assert.equal(NEXT_THEME_MODE.light, 'dark');
assert.equal(NEXT_THEME_MODE.dark, 'system');

assert.equal(getNextMode('system'), 'light');
assert.equal(getNextMode('light'), 'dark');
assert.equal(getNextMode('dark'), 'system');
// 未知值防御降级到 system
assert.equal(getNextMode('unknown' as unknown as ThemeMode), 'system');
});

test('从任意档连续点击 3 次回到原档', () => {
const modes: ThemeMode[] = ['system', 'light', 'dark'];
for (const start of modes) {
const step1 = getNextMode(start);
const step2 = getNextMode(step1);
const step3 = getNextMode(step2);
assert.equal(step3, start, `从 ${start} 起连续点 3 次应回到 ${start}`);
}
});

test('图标映射与规格一致:自动=Monitor、亮=Sun、暗=Moon', () => {
assert.equal(THEME_ICONS.system, Monitor);
assert.equal(THEME_ICONS.light, Sun);
assert.equal(THEME_ICONS.dark, Moon);
});

test('可达性文案:aria-label 与 title 同时说明当前档与下一档', () => {
assert.equal(THEME_LABELS.system, '自动');
assert.equal(THEME_LABELS.light, '亮色');
assert.equal(THEME_LABELS.dark, '暗色');

assert.equal(getThemeAriaLabel('system'), '主题:自动,点击切换到亮色');
assert.equal(getThemeAriaLabel('light'), '主题:亮色,点击切换到暗色');
assert.equal(getThemeAriaLabel('dark'), '主题:暗色,点击切换到自动');
});

test('readStoredMode:解析合法值,非法值/无值回退 system', () => {
const originalWindow = globalThis.window;
try {
const mockStore: Record<string, string> = {};
globalThis.window = {
localStorage: {
getItem: (k: string) => mockStore[k] ?? null,
},
} as unknown as Window & typeof globalThis;

assert.equal(readStoredMode(), 'system');

mockStore[THEME_STORAGE_KEY] = 'light';
assert.equal(readStoredMode(), 'light');

mockStore[THEME_STORAGE_KEY] = 'dark';
assert.equal(readStoredMode(), 'dark');

mockStore[THEME_STORAGE_KEY] = 'system';
assert.equal(readStoredMode(), 'system');

mockStore[THEME_STORAGE_KEY] = 'invalid-mode';
assert.equal(readStoredMode(), 'system');

// 禁用 localStorage 异常场景(如无痕模式)
globalThis.window = {
localStorage: {
getItem: () => {
throw new Error('SecurityError');
},
},
} as unknown as Window & typeof globalThis;
assert.equal(readStoredMode(), 'system');
} finally {
globalThis.window = originalWindow;
}
});

test('applyTheme:设置 dark class、colorScheme 与 dataset.themeMode', () => {
const originalWindow = globalThis.window;
const originalDocument = globalThis.document;

try {
const classSet = new Set<string>();
const rootElement = {
classList: {
toggle: (cls: string, force: boolean) => {
if (force) classSet.add(cls);
else classSet.delete(cls);
},
},
style: {
colorScheme: '',
},
dataset: {} as Record<string, string>,
};

globalThis.document = {
documentElement: rootElement,
} as unknown as Document;

// 1. light 模式
globalThis.window = {
matchMedia: () => ({ matches: false }),
} as unknown as Window & typeof globalThis;
applyTheme('light');
assert.equal(classSet.has('dark'), false);
assert.equal(rootElement.style.colorScheme, 'light');
assert.equal(rootElement.dataset.themeMode, 'light');

// 2. dark 模式
applyTheme('dark');
assert.equal(classSet.has('dark'), true);
assert.equal(rootElement.style.colorScheme, 'dark');
assert.equal(rootElement.dataset.themeMode, 'dark');

// 3. system 模式(系统为 light)
globalThis.window = {
matchMedia: () => ({ matches: false }),
} as unknown as Window & typeof globalThis;
applyTheme('system');
assert.equal(classSet.has('dark'), false);
assert.equal(rootElement.style.colorScheme, 'light');
assert.equal(rootElement.dataset.themeMode, 'system');

// 4. system 模式(系统为 dark)
globalThis.window = {
matchMedia: () => ({ matches: true }),
} as unknown as Window & typeof globalThis;
applyTheme('system');
assert.equal(classSet.has('dark'), true);
assert.equal(rootElement.style.colorScheme, 'dark');
assert.equal(rootElement.dataset.themeMode, 'system');
} finally {
globalThis.window = originalWindow;
globalThis.document = originalDocument;
}
});
Loading