applySkin.ts 3.2 KB

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