-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathdarkmode.js
34 lines (31 loc) · 919 Bytes
/
darkmode.js
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
{
const LS_KEY = "use-dark-mode",
setLsValue = (enabled) =>
window.localStorage.setItem(LS_KEY, enabled ? "1" : "0");
let useDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
const storedPreference = window.localStorage.getItem(LS_KEY);
if (storedPreference === null) {
setLsValue(useDarkMode);
} else {
useDarkMode = storedPreference === "1";
}
const darkStylesheets = Array.from(
document.head.querySelectorAll("link[data-dark-stylesheet]")
);
const setDarkMode = (enabled) => {
useDarkMode = enabled;
setLsValue(enabled);
for (const stylesheet of darkStylesheets) {
enabled
? stylesheet.setAttribute("rel", "stylesheet")
: stylesheet.removeAttribute("rel");
}
};
Object.defineProperty(window, "_darkMode", {
get() {
return useDarkMode;
},
set: setDarkMode,
});
setDarkMode(useDarkMode);
}