Use View Transitions for smooth theme switching

This commit is contained in:
Alexander Zaytsev
2025-12-16 08:59:35 +01:00
parent df9a6de57d
commit 876eb5459a
+19 -5
View File
@@ -26,13 +26,27 @@ export default class extends Controller {
set #theme(theme) {
localStorage.setItem("theme", theme)
if (theme === "auto") {
document.documentElement.removeAttribute("data-theme")
} else {
document.documentElement.setAttribute("data-theme", theme)
const currentTheme = document.documentElement.getAttribute("data-theme") || "auto"
const isInitialLoad = currentTheme === theme
const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches
const animate = !isInitialLoad && !prefersReducedMotion
const applyTheme = () => {
if (theme === "auto") {
document.documentElement.removeAttribute("data-theme")
} else {
document.documentElement.setAttribute("data-theme", theme)
}
this.#updateButtons()
}
this.#updateButtons()
if (animate && document.startViewTransition) {
document.startViewTransition(applyTheme)
} else {
applyTheme()
}
}
#applyStoredTheme() {