2023-07-23 07:27:41 +07: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-04 02:07:19 +07:00
|
|
|
|
2024-01-24 05:52:41 +07:00
|
|
|
const emitThemeChangeEvent = (theme: "light" | "dark") => {
|
|
|
|
const event: CustomEventMap["themechange"] = new CustomEvent("themechange", {
|
|
|
|
detail: { theme },
|
|
|
|
})
|
|
|
|
document.dispatchEvent(event)
|
|
|
|
}
|
|
|
|
|
2023-07-03 03:08:29 +07:00
|
|
|
document.addEventListener("nav", () => {
|
2024-02-02 14:55:11 +07:00
|
|
|
const switchTheme = (e: Event) => {
|
2024-08-25 03:33:30 +07:00
|
|
|
const newTheme =
|
|
|
|
document.documentElement.getAttribute("saved-theme") === "dark" ? "light" : "dark"
|
2024-01-24 05:52:41 +07:00
|
|
|
document.documentElement.setAttribute("saved-theme", newTheme)
|
|
|
|
localStorage.setItem("theme", newTheme)
|
|
|
|
emitThemeChangeEvent(newTheme)
|
2023-06-07 10:58:26 +07:00
|
|
|
}
|
2023-06-07 09:48:37 +07:00
|
|
|
|
2024-02-02 14:55:11 +07:00
|
|
|
const themeChange = (e: MediaQueryListEvent) => {
|
|
|
|
const newTheme = e.matches ? "dark" : "light"
|
|
|
|
document.documentElement.setAttribute("saved-theme", newTheme)
|
|
|
|
localStorage.setItem("theme", newTheme)
|
|
|
|
emitThemeChangeEvent(newTheme)
|
|
|
|
}
|
|
|
|
|
2023-06-07 10:58:26 +07:00
|
|
|
// Darkmode toggle
|
2024-08-25 03:33:30 +07:00
|
|
|
const themeButton = document.querySelector("#darkmode") as HTMLButtonElement
|
|
|
|
themeButton.addEventListener("click", switchTheme)
|
|
|
|
window.addCleanup(() => themeButton.removeEventListener("click", switchTheme))
|
2023-09-19 23:25:51 +07:00
|
|
|
|
|
|
|
// Listen for changes in prefers-color-scheme
|
|
|
|
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
2024-02-02 14:55:11 +07:00
|
|
|
colorSchemeMediaQuery.addEventListener("change", themeChange)
|
|
|
|
window.addCleanup(() => colorSchemeMediaQuery.removeEventListener("change", themeChange))
|
2023-06-07 09:48:37 +07:00
|
|
|
})
|