-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggle-theme.js
61 lines (44 loc) · 1.38 KB
/
toggle-theme.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
const primaryColorScheme = ""
const currentTheme = localStorage.getItem("theme")
function getPreferTheme() {
if (currentTheme) return currentTheme
if (primaryColorScheme) return primaryColorScheme
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light"
}
let themeValue = getPreferTheme()
function setPreference() {
localStorage.setItem("theme", themeValue)
reflectPreference()
}
function reflectPreference() {
document.firstElementChild.setAttribute("data-theme", themeValue)
document.querySelector("#theme-btn")?.setAttribute("aria-label", themeValue)
const body = document.body
if (body) {
const computedStyles = window.getComputedStyle(body)
const bgColor = computedStyles.backgroundColor
document
.querySelector("meta[name='theme-color']")
?.setAttribute("content", bgColor)
}
}
reflectPreference()
window.onload = () => {
function setThemeFeature() {
reflectPreference()
document.querySelector("#theme-btn")?.addEventListener("click", () => {
themeValue = themeValue === "light" ? "dark" : "light"
setPreference()
})
}
setThemeFeature()
document.addEventListener("astro:after-swap", setThemeFeature)
}
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", ({ matches: isDark }) => {
themeValue = isDark ? "dark" : "light"
setPreference()
})