From a8666690cf11a495f0cdd37b7abca72b95fdc236 Mon Sep 17 00:00:00 2001 From: "vicentic@immounited.com" Date: Thu, 2 Jan 2025 15:45:52 +0100 Subject: [PATCH] Fix: Color Mode Switcher Shows wrong icon in auto mode. Root cause contributes to occasional flickering. #546 - Unifies 'auto' and `null` handling for `theme` to simplify code and avoid occasional flickering. --- color-modes/js/color-modes.js | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/color-modes/js/color-modes.js b/color-modes/js/color-modes.js index 31f22f9e..d3d94fcd 100644 --- a/color-modes/js/color-modes.js +++ b/color-modes/js/color-modes.js @@ -8,26 +8,23 @@ 'use strict' const getStoredTheme = () => localStorage.getItem('theme') - const setStoredTheme = theme => localStorage.setItem('theme', theme) - - const getPreferredTheme = () => { - const storedTheme = getStoredTheme() - if (storedTheme) { - return storedTheme + const setStoredTheme = theme => { + if (theme == null || theme === 'auto') { + localStorage.removeItem('theme'); + } else { + localStorage.setItem('theme', theme) } - - return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' } const setTheme = theme => { - if (theme === 'auto') { + if (theme == null || theme === 'auto') { document.documentElement.setAttribute('data-bs-theme', (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')) } else { document.documentElement.setAttribute('data-bs-theme', theme) } } - setTheme(getPreferredTheme()) + setTheme(getStoredTheme()) const showActiveTheme = (theme, focus = false) => { const themeSwitcher = document.querySelector('#bd-theme') @@ -36,6 +33,10 @@ return } + if (theme == null) { + theme = 'auto' + } + const themeSwitcherText = document.querySelector('#bd-theme-text') const activeThemeIcon = document.querySelector('.theme-icon-active use') const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`) @@ -58,14 +59,14 @@ } window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { - const storedTheme = getStoredTheme() - if (storedTheme !== 'light' && storedTheme !== 'dark') { - setTheme(getPreferredTheme()) + const storedTheme = getStoredTheme(); + if (storedTheme == null || storedTheme === 'auto') { + setTheme(); // react on system theme change only in `auto` mode. } }) window.addEventListener('DOMContentLoaded', () => { - showActiveTheme(getPreferredTheme()) + showActiveTheme(getStoredTheme()) document.querySelectorAll('[data-bs-theme-value]') .forEach(toggle => {