| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- /**
- * theme.js — 换肤引导(须在 <head> 同步加载,早于其他样式与页面渲染)
- *
- * 读取顺序:localStorage 即时缓存上色(回头客零闪烁)→ 同步 XHR 取 /api/theme 校正
- * (首次访问,失败不阻塞页面)→ 页面加载后异步再校验一次(后台改动能传播)。
- * 主题落到 :root 的 CSS 变量:--accent / --accent-dark / --accent-soft /
- * --accent-on(主色上的文字色)/ --accent-rgb("r,g,b" 供 rgba() 使用)。
- * 只换强调色系,中性纸色/墨色在 base.css 里保持不变。
- */
- (function () {
- 'use strict';
- const KEY = 'pl.theme.v1';
- const URL = '/api/theme';
- function apply(t) {
- if (!t || !t.accent) return false;
- const r = document.documentElement;
- r.style.setProperty('--accent', t.accent);
- r.style.setProperty('--accent-dark', t.dark);
- r.style.setProperty('--accent-soft', t.soft);
- r.style.setProperty('--accent-on', t.on || '#fff');
- r.style.setProperty('--accent-rgb', t.rgb || '');
- r.dataset.theme = t.mode === 'custom' ? 'custom' : (t.mode || 'orange');
- return true;
- }
- function cache(t) { try { localStorage.setItem(KEY, JSON.stringify(t)); } catch (e) {} }
- function readCache() {
- try { return JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) { return null; }
- }
- function fetchSync() {
- try {
- const xhr = new XMLHttpRequest();
- xhr.open('GET', URL, false); // parser-blocking 阶段同步拉取,避免首屏旧色闪烁
- xhr.timeout = 2500;
- xhr.send(null);
- if (xhr.status === 200) return JSON.parse(xhr.responseText);
- } catch (e) { /* 离线/超时:沿用缓存或 base.css 默认橙 */ }
- return null;
- }
- function revalidate() {
- fetch(URL).then(function (r) { return r.json(); }).then(function (t) {
- cache(t); apply(t);
- document.dispatchEvent(new CustomEvent('pl:theme', { detail: t }));
- }).catch(function () {});
- }
- const cached = readCache();
- if (cached) apply(cached);
- const fresh = fetchSync();
- if (fresh) { cache(fresh); apply(fresh); }
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', function () { setTimeout(revalidate, 0); });
- } else {
- setTimeout(revalidate, 0);
- }
- window.PL = window.PL || {};
- window.PL.theme = {
- apply: apply,
- get: readCache,
- revalidate: revalidate,
- vars: function (t) {
- return {
- '--accent': t.accent, '--accent-dark': t.dark, '--accent-soft': t.soft,
- '--accent-on': t.on || '#fff', '--accent-rgb': t.rgb || ''
- };
- }
- };
- })();
|