mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-29 22:46:22 +00:00
0a76707062
* Emit custom event when theme changes * Type themechange custom event * Update darkmode docs
37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
const userPref = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"
|
|
const currentTheme = localStorage.getItem("theme") ?? userPref
|
|
document.documentElement.setAttribute("saved-theme", currentTheme)
|
|
|
|
const emitThemeChangeEvent = (theme: "light" | "dark") => {
|
|
const event: CustomEventMap["themechange"] = new CustomEvent("themechange", {
|
|
detail: { theme },
|
|
})
|
|
document.dispatchEvent(event)
|
|
}
|
|
|
|
document.addEventListener("nav", () => {
|
|
const switchTheme = (e: any) => {
|
|
const newTheme = e.target.checked ? "dark" : "light"
|
|
document.documentElement.setAttribute("saved-theme", newTheme)
|
|
localStorage.setItem("theme", newTheme)
|
|
emitThemeChangeEvent(newTheme)
|
|
}
|
|
|
|
// Darkmode toggle
|
|
const toggleSwitch = document.querySelector("#darkmode-toggle") as HTMLInputElement
|
|
toggleSwitch.removeEventListener("change", switchTheme)
|
|
toggleSwitch.addEventListener("change", switchTheme)
|
|
if (currentTheme === "dark") {
|
|
toggleSwitch.checked = true
|
|
}
|
|
|
|
// Listen for changes in prefers-color-scheme
|
|
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
|
colorSchemeMediaQuery.addEventListener("change", (e) => {
|
|
const newTheme = e.matches ? "dark" : "light"
|
|
document.documentElement.setAttribute("saved-theme", newTheme)
|
|
localStorage.setItem("theme", newTheme)
|
|
toggleSwitch.checked = e.matches
|
|
emitThemeChangeEvent(newTheme)
|
|
})
|
|
})
|