-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme-toggle.js
36 lines (30 loc) · 1.05 KB
/
theme-toggle.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
const storageKey = 'setting-theme';
const authoThemeKey = 'auto-theme';
const getSystemPreference = () => {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
const getColorPreference = () => {
if (localStorage.getItem(storageKey))
return localStorage.getItem(storageKey);
else
return getSystemPreference();
}
document.reflectTheme = reflectPreference = function () {
let theme = document.firstElementChild.getAttribute('data-theme');
if (theme) return;
if (localStorage.getItem(authoThemeKey) === 'true') {
document.firstElementChild.setAttribute('data-theme', getSystemPreference());
} else {
document.firstElementChild.setAttribute('data-theme', getColorPreference())
}
}
document.reflectTheme()
window.onload = () => {
document.reflectTheme()
}
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', ({matches:isDark}) => {
// TODO: same call in webapp when selecting auto-theme
reflectPreference()
})