summaryrefslogtreecommitdiff
path: root/static/js/theme.js
blob: 3d2b25cdd5ed988d7325a6f394d2495bc5f88e08 (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
(function () {
  "use strict";

  var root = document.documentElement;
  root.classList.add("theme-ready");
  var toggle = document.querySelector("[data-theme-toggle]");
  var syntaxLight = document.getElementById("syntax-light");
  var syntaxDark = document.getElementById("syntax-dark");
  var media = window.matchMedia("(prefers-color-scheme: dark)");
  var storedTheme = null;

  try {
    storedTheme = window.localStorage.getItem("theme");
  } catch (error) {
    storedTheme = null;
  }

  function activeTheme() {
    if (root.dataset.theme === "light" || root.dataset.theme === "dark") {
      return root.dataset.theme;
    }
    return media.matches ? "dark" : "light";
  }

  function syncSyntax(theme) {
    if (!syntaxLight || !syntaxDark) {
      return;
    }
    syntaxLight.media = theme === "light" ? "all" : "not all";
    syntaxDark.media = theme === "dark" ? "all" : "not all";
  }

  function updateToggle() {
    if (!toggle) {
      return;
    }
    var dark = activeTheme() === "dark";
    toggle.setAttribute("aria-pressed", String(dark));
    toggle.setAttribute("aria-label", dark ? "ライトテーマに切り替える" : "ダークテーマに切り替える");
    toggle.textContent = dark ? "Light" : "Dark";
  }

  function applyTheme(theme, persist) {
    root.dataset.theme = theme;
    syncSyntax(theme);
    updateToggle();
    if (persist) {
      try {
        window.localStorage.setItem("theme", theme);
      } catch (error) {
        // Storageが利用できなくても、現在のpageではthemeを維持する。
      }
    }
  }

  if (storedTheme === "light" || storedTheme === "dark") {
    applyTheme(storedTheme, false);
  } else {
    syncSyntax(activeTheme());
    updateToggle();
  }

  if (toggle) {
    toggle.addEventListener("click", function () {
      applyTheme(activeTheme() === "dark" ? "light" : "dark", true);
    });
  }

  media.addEventListener("change", function () {
    if (!root.dataset.theme) {
      syncSyntax(activeTheme());
      updateToggle();
    }
  });
})();