// 皮肤 class 应用器 —— 对称于 useTheme.applyTheme 的 DOM 侧入口。 // 策略:先清掉 上全部 skin-* class,再按解析结果挂当前包。 // 为什么「先清后挂」而不是增量 toggle:皮肤必须能被完全卸载(验收 A2), // 遍历清除不依赖枚举已知包名,动态包(v2)接入时也无需改这里。 import type { SkinBase } from "./contract.js"; import { SKIN_CLASS_PREFIX } from "./contract.js"; import { resolveSkinForBase } from "./registry.js"; import { ensurePixelSkinVarsStyle } from "./pixelSkinStyle.js"; import { normalizeThemePreference, resolveTheme, type Theme } from "@/useTheme.js"; import { applyUiFontSizePx, loadUiFontSizePx } from "@/lib/uiFontSize.js"; // 模块内转出口:消费方(store)只从本文件取皮肤能力,压减调用方 import 行数。 export { loadPersistedSkinId, normalizeSkinId, persistSkinId, } from "./registry.js"; /** * 皮肤基座取「归一化后的主题偏好」:system 先按系统亮暗解析,再映射到 zai-*。 * 与 applyTheme 内部对 appliedTheme 的推导保持同一口径(useTheme.ts:60-65), * 避免两处对「system 现在算亮还是暗」的判断分叉。 */ export function resolveSkinBase(theme: Theme): SkinBase { if (theme === "system") { return resolveTheme(theme) === "dark" ? "zai-dark" : "zai-light"; } return normalizeThemePreference(theme) as SkinBase; } /** * fontGrid 锁定(验收 A4):applyUiFontSizePx 把 --ui-font-size 写成 html 的 * inline style,优先级高于皮肤 class 里的变量值,所以锁定必须在 JS 层每次 * 应用皮肤时重写 inline 值;卸载皮肤时恢复用户在 appearance 设置的字号。 * 这里放在 applySkin 内而不是调用方,保证所有触发路径(切肤/切主题/改字号) * 收敛到同一个执行点。 */ function applyFontGridLock( root: HTMLElement, lockUiFontSize: number | undefined, ): void { if (lockUiFontSize !== undefined) { root.style.setProperty("--ui-font-size", `${lockUiFontSize}px`); return; } // 恢复用户偏好(loadUiFontSizePx 与设置页的持久化同源)。 applyUiFontSizePx(loadUiFontSizePx()); } /** * 把「皮肤 id × 当前主题基座」解析成 上的 skin-* class。 * skinId 为 null / 未注册 / 与当前基座不兼容时,结果都是无皮肤 class。 */ export function applySkin(skinId: string | null, activeBase: SkinBase): void { if (typeof document === "undefined") { return; } const root = document.documentElement; for (const className of Array.from(root.classList)) { if (className.startsWith(SKIN_CLASS_PREFIX)) { root.classList.remove(className); } } const manifest = resolveSkinForBase(skinId, activeBase); if (manifest) { // 生产打包时 Tailwind 会把 styles.css 里主题命名空间(--color-* 等)的 // scoped 重定义整段裁掉(dev 不裁,曾导致「打包版丢皮肤配色/壁纸被盖」), // 所以皮肤变量统一走运行时注入,绕开构建管线(见 pixelSkinStyle.ts)。 ensurePixelSkinVarsStyle(); root.classList.add(SKIN_CLASS_PREFIX + manifest.id); } applyFontGridLock(root, manifest?.tokens.fontGrid?.lockUiFontSize); }