From 24320c669f9a571cb6adc8a86d51f011164cefae Mon Sep 17 00:00:00 2001 From: novcmbro Date: Thu, 6 Jun 2024 17:15:43 -0300 Subject: [PATCH] fixed theme to change only if different from current and to watch preferred color scheme changes --- src/js/theme.js | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/js/theme.js b/src/js/theme.js index 5eccbe1..ddc8398 100644 --- a/src/js/theme.js +++ b/src/js/theme.js @@ -1,29 +1,39 @@ +const prefersLightTheme = window.matchMedia("(prefers-color-scheme: light)") const localStorageKey = "novcmbro_decoder_theme" const rootElement = document.documentElement const theme = { + preferred: undefined, db: () => localStorage.getItem(localStorageKey), update: undefined, init: undefined, change: undefined } -theme.update = () => rootElement.classList = theme.db() +theme.preferred = () => prefersLightTheme.matches ? "light" : "dark" -theme.init = () => { - const prefersLightTheme = window.matchMedia("(prefers-color-scheme: light)").matches +theme.update = () => rootElement.className = theme.db() +theme.init = () => { if (!theme.db()) { - localStorage.setItem(localStorageKey, prefersLightTheme ? "light" : "dark") + localStorage.setItem(localStorageKey, theme.preferred()) } + prefersLightTheme.addEventListener("change", () => { + localStorage.setItem(localStorageKey, theme.preferred()) + theme.update() + }) + theme.update() } theme.change = ({ currentTarget }) => { const themeName = currentTarget.classList[1] - localStorage.setItem(localStorageKey, themeName) - theme.update() + + if (rootElement.className !== themeName) { + localStorage.setItem(localStorageKey, themeName) + theme.update() + } } const { init, change } = theme