-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy paththeme-switch.js
78 lines (71 loc) · 2.22 KB
/
theme-switch.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
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
76
77
78
"use strict";
// val: "light" | "dark"
function renderTheme(val) {
document.documentElement.setAttribute("data-theme", val);
document.getElementById("syntax-theme").href = `/styles/syntax-theme-${val}.css`
}
function changeThemeTo(val) {
if (val === "system") {
setThemeToSystemPref();
// delete explicit theme pref from browser storage
if (storageAvailable("localStorage")) {
localStorage.removeItem("blog-rust-lang-org-theme");
}
} else {
renderTheme(val);
// save theme prefs in the browser
if (storageAvailable("localStorage")) {
localStorage.setItem("blog-rust-lang-org-theme", val);
}
}
// the theme dropdown will close itself when returning to the dropdown() caller
}
function dropdown () {
document.getElementById("theme-choice").classList.toggle("showThemeDropdown");
}
// courtesy MDN
function storageAvailable(type) {
let storage;
try {
storage = window[type];
const x = "__storage_test__";
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return (
e instanceof DOMException &&
e.name === "QuotaExceededError" &&
// acknowledge QuotaExceededError only if there's something already stored
storage &&
storage.length !== 0
);
}
}
function handleBlur(event) {
const parent = document.getElementById("theme-choice");
if (!parent.contains(document.activeElement) &&
!parent.contains(event.relatedTarget) &&
parent.classList.contains("showThemeDropdown")
) {
console.debug('Closing the dropdown');
parent.classList.remove("showThemeDropdown");
}
}
function setThemeToSystemPref() {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
renderTheme("dark");
} else {
renderTheme("light");
}
}
// Check for saved user preference on load, else check and save user agent prefs
let savedTheme = null;
if (storageAvailable("localStorage")) {
savedTheme = localStorage.getItem("blog-rust-lang-org-theme");
}
if (savedTheme) {
renderTheme(savedTheme);
} else {
setThemeToSystemPref();
}