From e42e3534186d78a9b85f0f4e8cdc9c5ce20a72e2 Mon Sep 17 00:00:00 2001 From: ouariachi Date: Sun, 25 Feb 2024 21:37:07 +0100 Subject: [PATCH] Add dark mode preference listener and handling function. --- src/components/ThemeToggle.astro | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/components/ThemeToggle.astro b/src/components/ThemeToggle.astro index 5163e056b..a919d36c7 100644 --- a/src/components/ThemeToggle.astro +++ b/src/components/ThemeToggle.astro @@ -28,14 +28,29 @@ import MoonIcon from "@/icons/moon.astro" const isDark = getThemePreference() === "dark" document.documentElement.classList[isDark ? "add" : "remove"]("dark") - const handleToggleClick = () => { - const element = document.documentElement - element.classList.toggle("dark") + const toggleTheme = () => { + const element = document.documentElement + element.classList.toggle("dark") - const isDark = element.classList.contains("dark") - localStorage.setItem("theme", isDark ? "dark" : "light") - } + const isDark = element.classList.contains("dark") + localStorage.setItem("theme", isDark ? "dark" : "light") + } + + const handleThemePreferenceChange = (e) => { + const isDark = document.documentElement.classList.contains("dark") + const toggle = (e.matches && !isDark) || (!e.matches && isDark) + if (toggle) { + toggleTheme() + } + } + + const handleToggleClick = () => { + toggleTheme() + } + const darkModePreference = window.matchMedia("(prefers-color-scheme: dark)") + darkModePreference.addEventListener("change", handleThemePreferenceChange) + darkModePreference.addListener(handleThemePreferenceChange) // backward compatibility document .getElementById("themeToggle") .addEventListener("click", handleToggleClick)