โ– humdrum codex / custard v0.2.0
license AGPL-3.0
1.5 KB raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// theme.js โ€” live side of the theme switcher. The picker chooses a palette
// FAMILY (flexoki/uchu/humdrum/eink); light vs dark follows the OS. An inline
// <head> script already resolved the first paint; this handles switching and
// reacting when the OS color scheme flips.
(function () {
  "use strict";
  var FAMILIES = ["flexoki", "uchu", "humdrum", "eink"];

  function family() {
    var m = document.cookie.match(/(?:^|; )theme=([^;]+)/);
    var f = m ? decodeURIComponent(m[1]) : "flexoki";
    return FAMILIES.indexOf(f) < 0 ? "flexoki" : f;
  }

  function systemDark() {
    return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  }

  function resolve(f) {
    return f === "eink" ? "eink" : (systemDark() ? f + "-dark" : f);
  }

  function apply(f) {
    document.documentElement.setAttribute("data-theme", resolve(f));
    document.cookie = "theme=" + f + "; Path=/; Max-Age=31536000; SameSite=Lax";
    try { localStorage.setItem("theme", f); } catch (e) {}
  }

  document.addEventListener("DOMContentLoaded", function () {
    var sel = document.getElementById("theme-select");
    if (sel) sel.addEventListener("change", function () { apply(sel.value); });
  });

  if (window.matchMedia) {
    var mq = window.matchMedia("(prefers-color-scheme: dark)");
    var onChange = function () {
      document.documentElement.setAttribute("data-theme", resolve(family()));
    };
    if (mq.addEventListener) mq.addEventListener("change", onChange);
    else if (mq.addListener) mq.addListener(onChange);
  }
})();