theme.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * theme.js — 换肤引导(须在 <head> 同步加载,早于其他样式与页面渲染)
  3. *
  4. * 读取顺序:localStorage 即时缓存上色(回头客零闪烁)→ 同步 XHR 取 /api/theme 校正
  5. * (首次访问,失败不阻塞页面)→ 页面加载后异步再校验一次(后台改动能传播)。
  6. * 主题落到 :root 的 CSS 变量:--accent / --accent-dark / --accent-soft /
  7. * --accent-on(主色上的文字色)/ --accent-rgb("r,g,b" 供 rgba() 使用)。
  8. * 只换强调色系,中性纸色/墨色在 base.css 里保持不变。
  9. */
  10. (function () {
  11. 'use strict';
  12. const KEY = 'pl.theme.v1';
  13. const URL = '/api/theme';
  14. function apply(t) {
  15. if (!t || !t.accent) return false;
  16. const r = document.documentElement;
  17. r.style.setProperty('--accent', t.accent);
  18. r.style.setProperty('--accent-dark', t.dark);
  19. r.style.setProperty('--accent-soft', t.soft);
  20. r.style.setProperty('--accent-on', t.on || '#fff');
  21. r.style.setProperty('--accent-rgb', t.rgb || '');
  22. r.dataset.theme = t.mode === 'custom' ? 'custom' : (t.mode || 'orange');
  23. return true;
  24. }
  25. function cache(t) { try { localStorage.setItem(KEY, JSON.stringify(t)); } catch (e) {} }
  26. function readCache() {
  27. try { return JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) { return null; }
  28. }
  29. function fetchSync() {
  30. try {
  31. const xhr = new XMLHttpRequest();
  32. xhr.open('GET', URL, false); // parser-blocking 阶段同步拉取,避免首屏旧色闪烁
  33. xhr.timeout = 2500;
  34. xhr.send(null);
  35. if (xhr.status === 200) return JSON.parse(xhr.responseText);
  36. } catch (e) { /* 离线/超时:沿用缓存或 base.css 默认橙 */ }
  37. return null;
  38. }
  39. function revalidate() {
  40. fetch(URL).then(function (r) { return r.json(); }).then(function (t) {
  41. cache(t); apply(t);
  42. document.dispatchEvent(new CustomEvent('pl:theme', { detail: t }));
  43. }).catch(function () {});
  44. }
  45. const cached = readCache();
  46. if (cached) apply(cached);
  47. const fresh = fetchSync();
  48. if (fresh) { cache(fresh); apply(fresh); }
  49. if (document.readyState === 'loading') {
  50. document.addEventListener('DOMContentLoaded', function () { setTimeout(revalidate, 0); });
  51. } else {
  52. setTimeout(revalidate, 0);
  53. }
  54. window.PL = window.PL || {};
  55. window.PL.theme = {
  56. apply: apply,
  57. get: readCache,
  58. revalidate: revalidate,
  59. vars: function (t) {
  60. return {
  61. '--accent': t.accent, '--accent-dark': t.dark, '--accent-soft': t.soft,
  62. '--accent-on': t.on || '#fff', '--accent-rgb': t.rgb || ''
  63. };
  64. }
  65. };
  66. })();