# -*- coding: utf-8 -*- """站点换肤:预设主题 + 自定义主色。 主题配置存 settings 表(key=site_theme,JSON),公开接口 GET /api/theme 供所有页面 (含未登录)在渲染前同步读取,应用为 :root 上的 CSS 变量 --accent / --accent-dark / --accent-soft / --accent-rgb / --accent-on。只换强调色系,中性纸色/墨色不动。 """ import json import re from db import get_setting, set_setting SETTING_KEY = "site_theme" CACHE_KEY = "site_theme" # 预设主题:(id, 中文名, 英文名, 主色, 深色, 浅色) PRESETS = [ {"id": "orange", "name": "活力橙", "nameEn": "Vitality Orange", "accent": "#ff5c2b", "dark": "#e64718", "soft": "#ffe0d2"}, {"id": "green", "name": "森系绿", "nameEn": "Forest Green", "accent": "#1e8e5a", "dark": "#146842", "soft": "#dcf2e6"}, {"id": "blue", "name": "靛青蓝", "nameEn": "Indigo Blue", "accent": "#2563eb", "dark": "#1d4ed8", "soft": "#dde8fe"}, {"id": "burgundy", "name": "酒红", "nameEn": "Burgundy", "accent": "#9f2d3f", "dark": "#7c2230", "soft": "#f3dde1"}, {"id": "ink", "name": "墨黑", "nameEn": "Ink Black", "accent": "#17140f", "dark": "#000000", "soft": "#e6e1d6"}, ] DEFAULT_THEME = PRESETS[0] _HEX_RE = re.compile(r"^#?[0-9a-fA-F]{6}$") def _hex_to_rgb(h): h = (h or "").lstrip("#") return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) def _rgb_to_hex(rgb): return "#%02x%02x%02x" % tuple(max(0, min(255, int(round(v)))) for v in rgb) def _mix(h1, h2, t): """h1 向 h2 插值,t=0 全 h1,t=1 全 h2。""" a, b = _hex_to_rgb(h1), _hex_to_rgb(h2) return _rgb_to_hex(tuple(a[i] + (b[i] - a[i]) * t for i in range(3))) def _shade(h, amt): """amt>0 调亮(向白),amt<0 调暗(向黑)。""" return _mix(h, "#ffffff" if amt > 0 else "#000000", abs(amt)) def _relative_luminance(h): def ch(c): c /= 255.0 return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 r, g, b = _hex_to_rgb(h) return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b) def _derive(accent): """只给主色时自动算深色/浅色档与前景文字色。""" return { "accent": accent, "dark": _shade(accent, -0.12), "soft": _mix(accent, "#ffffff", 0.88), } def _on_color(accent): """主色上的文字色:深底白字 / 亮底墨字。""" return "#ffffff" if _relative_luminance(accent) < 0.45 else "#17140f" def preset_by_id(pid): return next((p for p in PRESETS if p["id"] == pid), None) def normalize(raw): """把存储结构规整为完整主题(含派生字段),非法输入回退默认橙。""" try: data = raw if isinstance(raw, dict) else json.loads(raw or "{}") except Exception: data = {} mode = data.get("mode") or "orange" if mode == "custom": accent = str(data.get("accent") or "").strip().lower() if not _HEX_RE.match(accent): accent = DEFAULT_THEME["accent"] if not accent.startswith("#"): accent = "#" + accent if data.get("dark") and _HEX_RE.match(str(data["dark"])): dark = "#" + str(data["dark"]).lstrip("#").lower() else: dark = _derive(accent)["dark"] if data.get("soft") and _HEX_RE.match(str(data["soft"])): soft = "#" + str(data["soft"]).lstrip("#").lower() else: soft = _derive(accent)["soft"] name = "自定义" else: p = preset_by_id(mode) or DEFAULT_THEME accent, dark, soft = p["accent"], p["dark"], p["soft"] name = p["name"] r, g, b = _hex_to_rgb(accent) return { "mode": mode if (mode == "custom" or preset_by_id(mode)) else "orange", "name": name, "accent": accent, "dark": dark, "soft": soft, "on": _on_color(accent), "rgb": "%d,%d,%d" % (r, g, b), } def get_raw_theme(): """后台读到的原始存储对象(区分 dark/soft 是用户显式给的还是派生的)。""" try: data = json.loads(get_setting(SETTING_KEY, "") or "{}") return data if isinstance(data, dict) else {} except Exception: return {} def get_active_theme(): """当前生效主题(Redis 缓存,保存时失效)。""" import cache try: cached = cache.get_json(CACHE_KEY) if cached: return cached except Exception: pass theme = normalize(get_setting(SETTING_KEY, "")) try: cache.set_json(CACHE_KEY, theme, 3600) except Exception: pass return theme def save_theme(payload): """校验并保存后台提交的主题,返回规整后的完整主题。""" if not isinstance(payload, dict): raise ValueError("payload 需为对象") mode = str(payload.get("mode") or "").strip() if mode != "custom" and not preset_by_id(mode): raise ValueError("未知主题") data = {"mode": mode} if mode == "custom": for k in ("accent", "dark", "soft"): v = str(payload.get(k) or "").strip() if v and not _HEX_RE.match(v): raise ValueError("色值需为 #RRGGBB 格式") if v: data[k] = v if v.startswith("#") else "#" + v set_setting(SETTING_KEY, json.dumps(data, ensure_ascii=False)) try: import cache cache.delete(CACHE_KEY) except Exception: pass return get_active_theme()