feat(theme): 主题三态偏好模型,默认跟随系统自动切换暗黑模式
- 新增 src/lib/theme.ts:三态偏好单一真源
(system/light/dark,无存储值默认跟随系统)
- ThemeToggle 改三态循环(Monitor→Sun→Moon):
实时监听 prefers-color-scheme(仅 system 档生效)
+ storage 跨标签页同步;尺寸位置不变
- layout.tsx FOUC 内联脚本支持 system 档,
首帧前解析避免闪烁
- e2e 视觉回归 L2 改用 test.use({ colorScheme }) 驱动
(事后 setAttribute 存在被挂载效果覆盖的竞态)
- header.test.tsx lucide 白名单补 Monitor
- CLAUDE.md 同步三态语义与 variant 踩坑
- 新增 scripts/audit/theme-system-verify.mjs
(55 断言:首帧无闪烁/循环/实时跟随/旧值兼容/
污染回退/6 路由冒烟)
验证:单测 131 套件 1662 通过 0 失败;
tsc 0 错;eslint 0 错;next build 通过;
运行时 55/55 PASS(dogfood-output/theme-system-verify/)
This commit is contained in:
1 parent
5159862e96
commit
0bd1e9a7e2
9 files changed
+962
-71
No files matched your search
@@ -0,0 +1,182 @@
|
||||
import {
|
||||
THEME_STORAGE_KEY,
|
||||
DEFAULT_PREFERENCE,
|
||||
THEME_CYCLE,
|
||||
SYSTEM_PREFERENCE_QUERY,
|
||||
normalizePreference,
|
||||
getSystemTheme,
|
||||
resolveTheme,
|
||||
nextPreference,
|
||||
applyTheme,
|
||||
persistPreference,
|
||||
readStoredPreference,
|
||||
} from '@/lib/theme';
|
||||
|
||||
/**
|
||||
* jsdom 不实现 matchMedia,jest.setup.js 提供了 matches:false 的全局桩。
|
||||
* 该桩是 writable 但非 configurable(Object.defineProperty 会抛
|
||||
* "Cannot redefine property"),因此这里用直接赋值覆盖,不用 defineProperty。
|
||||
*/
|
||||
function mockMatchMedia(matches: boolean) {
|
||||
window.matchMedia = jest.fn().mockImplementation((query: string) => ({
|
||||
matches,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: jest.fn(),
|
||||
removeListener: jest.fn(),
|
||||
addEventListener: jest.fn(),
|
||||
removeEventListener: jest.fn(),
|
||||
dispatchEvent: jest.fn(),
|
||||
}));
|
||||
}
|
||||
|
||||
/** 模拟 matchMedia 不可用/抛错的受限环境(老浏览器、隐私策略) */
|
||||
function breakMatchMedia(mode: 'missing' | 'throws') {
|
||||
window.matchMedia =
|
||||
mode === 'missing'
|
||||
? (undefined as unknown as typeof window.matchMedia)
|
||||
: (jest.fn().mockImplementation(() => {
|
||||
throw new Error('blocked');
|
||||
}) as unknown as typeof window.matchMedia);
|
||||
}
|
||||
|
||||
describe('theme 偏好模块', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
mockMatchMedia(false);
|
||||
});
|
||||
|
||||
describe('normalizePreference', () => {
|
||||
it('接受三档合法偏好', () => {
|
||||
expect(normalizePreference('system')).toBe('system');
|
||||
expect(normalizePreference('light')).toBe('light');
|
||||
expect(normalizePreference('dark')).toBe('dark');
|
||||
});
|
||||
|
||||
it('拒绝非法值与空值,交由调用方回退默认', () => {
|
||||
expect(normalizePreference(null)).toBeNull();
|
||||
expect(normalizePreference(undefined)).toBeNull();
|
||||
expect(normalizePreference('')).toBeNull();
|
||||
expect(normalizePreference('DARK')).toBeNull();
|
||||
expect(normalizePreference('auto')).toBeNull();
|
||||
expect(normalizePreference(1)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSystemTheme', () => {
|
||||
it('系统偏好深色时返回 dark', () => {
|
||||
mockMatchMedia(true);
|
||||
expect(getSystemTheme()).toBe('dark');
|
||||
});
|
||||
|
||||
it('系统偏好浅色时返回 light', () => {
|
||||
mockMatchMedia(false);
|
||||
expect(getSystemTheme()).toBe('light');
|
||||
});
|
||||
|
||||
it('查询串必须是 prefers-color-scheme: dark', () => {
|
||||
getSystemTheme();
|
||||
expect(window.matchMedia).toHaveBeenCalledWith(SYSTEM_PREFERENCE_QUERY);
|
||||
expect(SYSTEM_PREFERENCE_QUERY).toBe('(prefers-color-scheme: dark)');
|
||||
});
|
||||
|
||||
it('matchMedia 缺失(老浏览器)时回退浅色而不抛错', () => {
|
||||
breakMatchMedia('missing');
|
||||
expect(() => getSystemTheme()).not.toThrow();
|
||||
expect(getSystemTheme()).toBe('light');
|
||||
});
|
||||
|
||||
it('matchMedia 抛错(受限环境)时回退浅色', () => {
|
||||
breakMatchMedia('throws');
|
||||
expect(getSystemTheme()).toBe('light');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveTheme', () => {
|
||||
it('system 档透传系统偏好', () => {
|
||||
expect(resolveTheme('system', 'dark')).toBe('dark');
|
||||
expect(resolveTheme('system', 'light')).toBe('light');
|
||||
});
|
||||
|
||||
it('显式档覆盖系统偏好(双向都要成立)', () => {
|
||||
expect(resolveTheme('light', 'dark')).toBe('light');
|
||||
expect(resolveTheme('dark', 'light')).toBe('dark');
|
||||
});
|
||||
|
||||
it('未传系统偏好时现读 matchMedia', () => {
|
||||
mockMatchMedia(true);
|
||||
expect(resolveTheme('system')).toBe('dark');
|
||||
});
|
||||
});
|
||||
|
||||
describe('nextPreference', () => {
|
||||
it('按 system → light → dark → system 循环', () => {
|
||||
expect(nextPreference('system')).toBe('light');
|
||||
expect(nextPreference('light')).toBe('dark');
|
||||
expect(nextPreference('dark')).toBe('system');
|
||||
});
|
||||
|
||||
it('循环顺序常量与循环函数一致(防止两处定义漂移)', () => {
|
||||
expect([...THEME_CYCLE]).toEqual(['system', 'light', 'dark']);
|
||||
THEME_CYCLE.forEach((pref, index) => {
|
||||
const expectedNext = THEME_CYCLE[(index + 1) % THEME_CYCLE.length];
|
||||
expect(nextPreference(pref)).toBe(expectedNext);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('存储读写', () => {
|
||||
it('persistPreference 写入约定 key', () => {
|
||||
persistPreference('dark');
|
||||
expect(window.localStorage.getItem(THEME_STORAGE_KEY)).toBe('dark');
|
||||
expect(THEME_STORAGE_KEY).toBe('novalon-theme');
|
||||
});
|
||||
|
||||
it('readStoredPreference 读出合法偏好', () => {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, 'system');
|
||||
expect(readStoredPreference()).toBe('system');
|
||||
});
|
||||
|
||||
it('无存储值时返回 null,由调用方回退默认偏好', () => {
|
||||
expect(readStoredPreference()).toBeNull();
|
||||
expect(DEFAULT_PREFERENCE).toBe('system');
|
||||
});
|
||||
|
||||
it('存储值被污染时返回 null 而非抛错', () => {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, '{"bad":1}');
|
||||
expect(readStoredPreference()).toBeNull();
|
||||
});
|
||||
|
||||
it('localStorage 不可用(隐私模式)时读写均静默降级', () => {
|
||||
// jsdom 的 window.localStorage 是 Proxy,jest.spyOn 拿不到 mockImplementation,
|
||||
// 故直接替换 Storage.prototype 上的方法再还原。
|
||||
const proto = Object.getPrototypeOf(window.localStorage) as Storage;
|
||||
const originalGet = proto.getItem;
|
||||
const originalSet = proto.setItem;
|
||||
proto.getItem = () => {
|
||||
throw new Error('denied');
|
||||
};
|
||||
proto.setItem = () => {
|
||||
throw new Error('denied');
|
||||
};
|
||||
|
||||
try {
|
||||
expect(() => persistPreference('dark')).not.toThrow();
|
||||
expect(readStoredPreference()).toBeNull();
|
||||
} finally {
|
||||
proto.getItem = originalGet;
|
||||
proto.setItem = originalSet;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyTheme', () => {
|
||||
it('把解析结果写到 html[data-theme]', () => {
|
||||
applyTheme('dark');
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
|
||||
applyTheme('light');
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* 主题偏好单一真源(暗黑模式基础设施)
|
||||
*
|
||||
* 三档偏好模型:`system` 跟随操作系统、`light` / `dark` 为显式覆盖。
|
||||
* 偏好(用户意图)与主题(实际生效值)分离:偏好持久化为 `data-theme` 之外的独立概念,
|
||||
* 因此 `html[data-theme]` 只是解析结果的输出,不能再被当作偏好读回
|
||||
* —— 否则 system 档在深色系统下会被误读成显式 dark,循环卡死。
|
||||
*
|
||||
* 信源:MDN `prefers-color-scheme` / `Window.matchMedia`
|
||||
* https://developer.mozilla.org/docs/Web/CSS/@media/prefers-color-scheme
|
||||
*/
|
||||
|
||||
/** localStorage 键名。旧版本仅存 'light' | 'dark',本次扩展出 'system',旧值语义保持不变 */
|
||||
export const THEME_STORAGE_KEY = 'novalon-theme';
|
||||
|
||||
/** 用户可选的三档偏好 */
|
||||
export type ThemePreference = 'system' | 'light' | 'dark';
|
||||
|
||||
/** 实际生效的主题(偏好 + 系统偏好解析后的结果) */
|
||||
export type ResolvedTheme = 'light' | 'dark';
|
||||
|
||||
/** 循环顺序:跟随系统 → 浅色 → 深色 → 跟随系统 */
|
||||
export const THEME_CYCLE = ['system', 'light', 'dark'] as const;
|
||||
|
||||
/**
|
||||
* 每一档的下一档。
|
||||
* 用字面量映射而非「数组取模」实现:项目开启了 noUncheckedIndexedAccess,
|
||||
* 数组下标取模会得到 `ThemePreference | undefined`,需要额外的非空断言。
|
||||
*/
|
||||
const NEXT_PREFERENCE: Record<ThemePreference, ThemePreference> = {
|
||||
system: 'light',
|
||||
light: 'dark',
|
||||
dark: 'system',
|
||||
};
|
||||
|
||||
/** 未做过显式选择时的默认偏好 —— 跟随系统 */
|
||||
export const DEFAULT_PREFERENCE: ThemePreference = 'system';
|
||||
|
||||
/** 系统深色偏好查询串,供组件与内联脚本共用 */
|
||||
export const SYSTEM_PREFERENCE_QUERY = '(prefers-color-scheme: dark)';
|
||||
|
||||
export const THEME_PREFERENCE_LABELS: Record<ThemePreference, string> = {
|
||||
system: '跟随系统',
|
||||
light: '浅色',
|
||||
dark: '深色',
|
||||
};
|
||||
|
||||
export const RESOLVED_THEME_LABELS: Record<ResolvedTheme, string> = {
|
||||
light: '浅色',
|
||||
dark: '深色',
|
||||
};
|
||||
|
||||
/** 归一化任意存储值;非法值返回 null,由调用方回退到默认偏好 */
|
||||
export function normalizePreference(value: unknown): ThemePreference | null {
|
||||
return value === 'system' || value === 'light' || value === 'dark' ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取操作系统当前偏好。
|
||||
* matchMedia 缺失(老浏览器)或抛错(受限环境)时回退浅色,保证 SSR 与隐私场景不崩。
|
||||
*/
|
||||
export function getSystemTheme(): ResolvedTheme {
|
||||
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
|
||||
return 'light';
|
||||
}
|
||||
try {
|
||||
return window.matchMedia(SYSTEM_PREFERENCE_QUERY).matches ? 'dark' : 'light';
|
||||
} catch {
|
||||
return 'light';
|
||||
}
|
||||
}
|
||||
|
||||
/** 偏好 + 系统偏好 → 实际生效主题 */
|
||||
export function resolveTheme(
|
||||
preference: ThemePreference,
|
||||
system: ResolvedTheme = getSystemTheme(),
|
||||
): ResolvedTheme {
|
||||
return preference === 'system' ? system : preference;
|
||||
}
|
||||
|
||||
/** 偏好在循环中的下一档 */
|
||||
export function nextPreference(current: ThemePreference): ThemePreference {
|
||||
return NEXT_PREFERENCE[current];
|
||||
}
|
||||
|
||||
/** 把解析结果应用到 DOM,驱动 globals.css 的 `html[data-theme='dark']` 变量覆盖块 */
|
||||
export function applyTheme(theme: ResolvedTheme): void {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
}
|
||||
|
||||
/** 持久化偏好。写入失败(隐私模式)时静默降级为仅本次会话生效 */
|
||||
export function persistPreference(preference: ThemePreference): void {
|
||||
try {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, preference);
|
||||
} catch {
|
||||
/* 隐私模式等写入失败时忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取持久化的偏好;无值或值被污染时返回 null */
|
||||
export function readStoredPreference(): ThemePreference | null {
|
||||
try {
|
||||
return normalizePreference(window.localStorage.getItem(THEME_STORAGE_KEY));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user