57 lines
1.3 KiB
Text
57 lines
1.3 KiB
Text
---
|
|
import { Moon, Sun } from "lucide-react"
|
|
---
|
|
|
|
<button id="themeToggle">
|
|
<Sun className="dark:hidden" />
|
|
<Moon className="hidden dark:block" />
|
|
</button>
|
|
|
|
<script>
|
|
// check current theme
|
|
const theme = (() => {
|
|
if (typeof localStorage !== "undefined" && localStorage.getItem("theme")) {
|
|
return localStorage.getItem("theme")
|
|
}
|
|
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
|
return "dark"
|
|
}
|
|
return "light"
|
|
})()
|
|
|
|
// set theme
|
|
if (theme === "light") {
|
|
document.documentElement.classList.remove("dark")
|
|
} else {
|
|
document.documentElement.classList.add("dark")
|
|
}
|
|
|
|
// save theme
|
|
window.localStorage.setItem("theme", theme!)
|
|
|
|
// update theme
|
|
const updateTheme = () => {
|
|
const isDark = document.documentElement.classList.contains("dark")
|
|
localStorage.setItem("theme", isDark ? "dark" : "light")
|
|
}
|
|
|
|
// toggle theme
|
|
const handleToggleClick = () => {
|
|
const element = document.documentElement
|
|
|
|
if (!document.startViewTransition) {
|
|
element.classList.toggle("dark")
|
|
updateTheme()
|
|
return
|
|
}
|
|
|
|
document.startViewTransition(() => {
|
|
element.classList.toggle("dark")
|
|
updateTheme()
|
|
})
|
|
}
|
|
|
|
document
|
|
.getElementById("themeToggle")!
|
|
.addEventListener("click", handleToggleClick)
|
|
</script>
|