From 876eb5459a182f12baea8373c7768f23b2ab2b00 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Tue, 16 Dec 2025 08:59:35 +0100 Subject: [PATCH] Use View Transitions for smooth theme switching --- .../controllers/theme_controller.js | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/app/javascript/controllers/theme_controller.js b/app/javascript/controllers/theme_controller.js index 154bf4fc0..eba32a8c4 100644 --- a/app/javascript/controllers/theme_controller.js +++ b/app/javascript/controllers/theme_controller.js @@ -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() {