theme.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # -*- coding: utf-8 -*-
  2. """站点换肤:预设主题 + 自定义主色。
  3. 主题配置存 settings 表(key=site_theme,JSON),公开接口 GET /api/theme 供所有页面
  4. (含未登录)在渲染前同步读取,应用为 :root 上的 CSS 变量 --accent / --accent-dark /
  5. --accent-soft / --accent-rgb / --accent-on。只换强调色系,中性纸色/墨色不动。
  6. """
  7. import json
  8. import re
  9. from db import get_setting, set_setting
  10. SETTING_KEY = "site_theme"
  11. CACHE_KEY = "site_theme"
  12. # 预设主题:(id, 中文名, 英文名, 主色, 深色, 浅色)
  13. PRESETS = [
  14. {"id": "orange", "name": "活力橙", "nameEn": "Vitality Orange",
  15. "accent": "#ff5c2b", "dark": "#e64718", "soft": "#ffe0d2"},
  16. {"id": "green", "name": "森系绿", "nameEn": "Forest Green",
  17. "accent": "#1e8e5a", "dark": "#146842", "soft": "#dcf2e6"},
  18. {"id": "blue", "name": "靛青蓝", "nameEn": "Indigo Blue",
  19. "accent": "#2563eb", "dark": "#1d4ed8", "soft": "#dde8fe"},
  20. {"id": "burgundy", "name": "酒红", "nameEn": "Burgundy",
  21. "accent": "#9f2d3f", "dark": "#7c2230", "soft": "#f3dde1"},
  22. {"id": "ink", "name": "墨黑", "nameEn": "Ink Black",
  23. "accent": "#17140f", "dark": "#000000", "soft": "#e6e1d6"},
  24. ]
  25. DEFAULT_THEME = PRESETS[0]
  26. _HEX_RE = re.compile(r"^#?[0-9a-fA-F]{6}$")
  27. def _hex_to_rgb(h):
  28. h = (h or "").lstrip("#")
  29. return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
  30. def _rgb_to_hex(rgb):
  31. return "#%02x%02x%02x" % tuple(max(0, min(255, int(round(v)))) for v in rgb)
  32. def _mix(h1, h2, t):
  33. """h1 向 h2 插值,t=0 全 h1,t=1 全 h2。"""
  34. a, b = _hex_to_rgb(h1), _hex_to_rgb(h2)
  35. return _rgb_to_hex(tuple(a[i] + (b[i] - a[i]) * t for i in range(3)))
  36. def _shade(h, amt):
  37. """amt>0 调亮(向白),amt<0 调暗(向黑)。"""
  38. return _mix(h, "#ffffff" if amt > 0 else "#000000", abs(amt))
  39. def _relative_luminance(h):
  40. def ch(c):
  41. c /= 255.0
  42. return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
  43. r, g, b = _hex_to_rgb(h)
  44. return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b)
  45. def _derive(accent):
  46. """只给主色时自动算深色/浅色档与前景文字色。"""
  47. return {
  48. "accent": accent,
  49. "dark": _shade(accent, -0.12),
  50. "soft": _mix(accent, "#ffffff", 0.88),
  51. }
  52. def _on_color(accent):
  53. """主色上的文字色:深底白字 / 亮底墨字。"""
  54. return "#ffffff" if _relative_luminance(accent) < 0.45 else "#17140f"
  55. def preset_by_id(pid):
  56. return next((p for p in PRESETS if p["id"] == pid), None)
  57. def normalize(raw):
  58. """把存储结构规整为完整主题(含派生字段),非法输入回退默认橙。"""
  59. try:
  60. data = raw if isinstance(raw, dict) else json.loads(raw or "{}")
  61. except Exception:
  62. data = {}
  63. mode = data.get("mode") or "orange"
  64. if mode == "custom":
  65. accent = str(data.get("accent") or "").strip().lower()
  66. if not _HEX_RE.match(accent):
  67. accent = DEFAULT_THEME["accent"]
  68. if not accent.startswith("#"):
  69. accent = "#" + accent
  70. if data.get("dark") and _HEX_RE.match(str(data["dark"])):
  71. dark = "#" + str(data["dark"]).lstrip("#").lower()
  72. else:
  73. dark = _derive(accent)["dark"]
  74. if data.get("soft") and _HEX_RE.match(str(data["soft"])):
  75. soft = "#" + str(data["soft"]).lstrip("#").lower()
  76. else:
  77. soft = _derive(accent)["soft"]
  78. name = "自定义"
  79. else:
  80. p = preset_by_id(mode) or DEFAULT_THEME
  81. accent, dark, soft = p["accent"], p["dark"], p["soft"]
  82. name = p["name"]
  83. r, g, b = _hex_to_rgb(accent)
  84. return {
  85. "mode": mode if (mode == "custom" or preset_by_id(mode)) else "orange",
  86. "name": name,
  87. "accent": accent,
  88. "dark": dark,
  89. "soft": soft,
  90. "on": _on_color(accent),
  91. "rgb": "%d,%d,%d" % (r, g, b),
  92. }
  93. def get_raw_theme():
  94. """后台读到的原始存储对象(区分 dark/soft 是用户显式给的还是派生的)。"""
  95. try:
  96. data = json.loads(get_setting(SETTING_KEY, "") or "{}")
  97. return data if isinstance(data, dict) else {}
  98. except Exception:
  99. return {}
  100. def get_active_theme():
  101. """当前生效主题(Redis 缓存,保存时失效)。"""
  102. import cache
  103. try:
  104. cached = cache.get_json(CACHE_KEY)
  105. if cached:
  106. return cached
  107. except Exception:
  108. pass
  109. theme = normalize(get_setting(SETTING_KEY, ""))
  110. try:
  111. cache.set_json(CACHE_KEY, theme, 3600)
  112. except Exception:
  113. pass
  114. return theme
  115. def save_theme(payload):
  116. """校验并保存后台提交的主题,返回规整后的完整主题。"""
  117. if not isinstance(payload, dict):
  118. raise ValueError("payload 需为对象")
  119. mode = str(payload.get("mode") or "").strip()
  120. if mode != "custom" and not preset_by_id(mode):
  121. raise ValueError("未知主题")
  122. data = {"mode": mode}
  123. if mode == "custom":
  124. for k in ("accent", "dark", "soft"):
  125. v = str(payload.get(k) or "").strip()
  126. if v and not _HEX_RE.match(v):
  127. raise ValueError("色值需为 #RRGGBB 格式")
  128. if v:
  129. data[k] = v if v.startswith("#") else "#" + v
  130. set_setting(SETTING_KEY, json.dumps(data, ensure_ascii=False))
  131. try:
  132. import cache
  133. cache.delete(CACHE_KEY)
  134. except Exception:
  135. pass
  136. return get_active_theme()