2023-07-23 00:27:41 +00:00
|
|
|
const userPref = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"
|
|
|
|
const currentTheme = localStorage.getItem("theme") ?? userPref
|
|
|
|
document.documentElement.setAttribute("saved-theme", currentTheme)
|
2023-06-03 19:07:19 +00:00
|
|
|
|
2024-02-05 10:45:36 +00:00
|
|
|
const emitThemeChangeEvent = (theme: "light" | "dark") => {
|
|
|
|
const event: CustomEventMap["themechange"] = new CustomEvent("themechange", {
|
|
|
|
detail: { theme },
|
|
|
|
})
|
|
|
|
document.dispatchEvent(event)
|
|
|
|
}
|
|
|
|
|
2023-07-02 20:08:29 +00:00
|
|
|
document.addEventListener("nav", () => {
|
2024-02-05 10:45:36 +00:00
|
|
|
const switchTheme = (e: Event) => {
|
|
|
|
const newTheme = (e.target as HTMLInputElement)?.checked ? "dark" : "light"
|
|
|
|
document.documentElement.setAttribute("saved-theme", newTheme)
|
|
|
|
localStorage.setItem("theme", newTheme)
|
|
|
|
emitThemeChangeEvent(newTheme)
|
|
|
|
}
|
|
|
|
|
|
|
|
const themeChange = (e: MediaQueryListEvent) => {
|
|
|
|
const newTheme = e.matches ? "dark" : "light"
|
|
|
|
document.documentElement.setAttribute("saved-theme", newTheme)
|
|
|
|
localStorage.setItem("theme", newTheme)
|
|
|
|
toggleSwitch.checked = e.matches
|
|
|
|
emitThemeChangeEvent(newTheme)
|
2023-06-07 03:58:26 +00:00
|
|
|
}
|
2023-06-07 02:48:37 +00:00
|
|
|
|
2023-06-07 03:58:26 +00:00
|
|
|
// Darkmode toggle
|
2023-07-23 00:27:41 +00:00
|
|
|
const toggleSwitch = document.querySelector("#darkmode-toggle") as HTMLInputElement
|
|
|
|
toggleSwitch.addEventListener("change", switchTheme)
|
2024-02-05 10:45:36 +00:00
|
|
|
window.addCleanup(() => toggleSwitch.removeEventListener("change", switchTheme))
|
2023-07-23 00:27:41 +00:00
|
|
|
if (currentTheme === "dark") {
|
2023-06-07 02:48:37 +00:00
|
|
|
toggleSwitch.checked = true
|
|
|
|
}
|
2023-09-19 16:25:51 +00:00
|
|
|
|
|
|
|
// Listen for changes in prefers-color-scheme
|
|
|
|
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
2024-02-05 10:45:36 +00:00
|
|
|
colorSchemeMediaQuery.addEventListener("change", themeChange)
|
|
|
|
window.addCleanup(() => colorSchemeMediaQuery.removeEventListener("change", themeChange))
|
2023-06-07 02:48:37 +00:00
|
|
|
})
|