summaryrefslogtreecommitdiffstats
path: root/docs/theme/ThemeSwitch.js
blob: c8b28472001b4b9fded4dc7ae58b586a5681eacd (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
import { on } from "./jxui.js";

const SEL_TARGET = ".cd-theme-switch";
const STORAGE_KEY = "theme";

const DARK = "dark";
const LIGHT = "light";
const theme = {value: getColorPreference()};

reflectPreference();
on("click", SEL_TARGET, onClick);
// sync with system changes
window
  .matchMedia("(prefers-color-scheme: dark)")
  .addEventListener("change", ({matches:isDark}) => {
    theme.value = isDark ? DARK : LIGHT
    setPreference()
  });

function onClick (event, target) {
  if (target.matches("[disabled]")) return;
  theme.value = theme.value === LIGHT ? DARK : LIGHT;
  setPreference();
}
function setPreference () {
  localStorage.setItem(STORAGE_KEY, theme.value);
  reflectPreference();
}
function reflectPreference () {
  const value = getColorPreference ();
  if (value === DARK) {
    document.documentElement.classList.add(DARK);
    document.documentElement.classList.remove(LIGHT);
  } else {
    document.documentElement.classList.add(LIGHT);
    document.documentElement.classList.remove(DARK);
  }
}
function getColorPreference () {
  return localStorage.getItem(STORAGE_KEY);
}