From 5e3b2d2dce487441ea3b8d193cd899178dec759f Mon Sep 17 00:00:00 2001 From: Dave Gallant Date: Sun, 7 Jan 2024 10:20:05 -0500 Subject: [PATCH] Only save theme when toggle is done --- themes/hugo-theme-gruvbox/assets/js/dark-mode.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/themes/hugo-theme-gruvbox/assets/js/dark-mode.js b/themes/hugo-theme-gruvbox/assets/js/dark-mode.js index 00b8bab9..546cf1dd 100644 --- a/themes/hugo-theme-gruvbox/assets/js/dark-mode.js +++ b/themes/hugo-theme-gruvbox/assets/js/dark-mode.js @@ -3,6 +3,10 @@ function getTheme() { // User preference return localStorage.getItem("theme"); } + // Undefined +} + +function getOSTheme() { if (window.matchMedia) { // OS preference return window.matchMedia("(prefers-color-scheme: light)").matches @@ -21,20 +25,28 @@ function setTheme(theme) { const prismLight = document.getElementById("prism-light"); prismDark.toggleAttribute("disabled", theme === "light"); prismLight.toggleAttribute("disabled", theme === "dark"); +} - // Store user preference +function saveTheme(theme) { localStorage.setItem("theme", theme); } // Initial load const theme = getTheme(); -if (theme) setTheme(theme); +const osTheme = getOSTheme(); +if (theme) { + setTheme(theme); + // Store user preference +} else if (osTheme) { + setTheme(osTheme); +} function toggleTheme(e) { const theme = e.currentTarget.classList.contains("light--hidden") ? "light" : "dark"; setTheme(theme); + saveTheme(theme); } // This script is inlined in the of the document, so we have to wait