From e9d73d4ded8a9e8d625fc198c632537149a64201 Mon Sep 17 00:00:00 2001 From: Remo Senekowitsch Date: Thu, 26 Dec 2024 12:25:08 +0100 Subject: [PATCH] Add system theme setting The system setting is followed if there is no item `blog-rust-lang-org-theme` in local storage. In order to switch back to the system theme, that item is deleted. Previously, if a system preference for dark theme was detected, that was additionally stored explicitly as `blog-rust-lang-org-theme`. That was removed, because it prevents the system setting from being followed if the user switches their system back to light theme. --- static/scripts/theme-switch.js | 29 ++++++++++++++++++++++------- templates/nav.hbs | 1 + 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/static/scripts/theme-switch.js b/static/scripts/theme-switch.js index 804e72b58..b8ffcd7a7 100644 --- a/static/scripts/theme-switch.js +++ b/static/scripts/theme-switch.js @@ -1,10 +1,18 @@ "use strict"; function changeThemeTo(val) { - document.documentElement.setAttribute("data-theme", val); - // save theme prefs in the browser - if (storageAvailable("localStorage")) { - localStorage.setItem("blog-rust-lang-org-theme", val); + if (val === "system") { + setThemeToSystemPref(); + // delete explicit theme pref from browser storage + if (storageAvailable("localStorage")) { + localStorage.removeItem("blog-rust-lang-org-theme"); + } + } else { + document.documentElement.setAttribute("data-theme", val); + // save theme prefs in the browser + if (storageAvailable("localStorage")) { + localStorage.setItem("blog-rust-lang-org-theme", val); + } } // the theme dropdown will close itself when returning to the dropdown() caller } @@ -44,6 +52,14 @@ function handleBlur(event) { } } +function setThemeToSystemPref() { + if (window.matchMedia("(prefers-color-scheme: dark)").matches) { + document.documentElement.setAttribute("data-theme", "dark"); + } else { + document.documentElement.setAttribute("data-theme", "light"); + } +} + // close the theme dropdown if clicking somewhere else document.querySelector('.theme-icon').onblur = handleBlur; @@ -54,9 +70,8 @@ if (storageAvailable("localStorage")) { } if (savedTheme) { document.documentElement.setAttribute("data-theme", savedTheme); -} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) { - document.documentElement.setAttribute("data-theme", "dark"); - localStorage.setItem("blog-rust-lang-org-theme", "dark"); +} else { + setThemeToSystemPref(); } // show the theme selector only if JavaScript is enabled/available diff --git a/templates/nav.hbs b/templates/nav.hbs index 36d1da5ed..8d16fb77b 100644 --- a/templates/nav.hbs +++ b/templates/nav.hbs @@ -17,6 +17,7 @@