Skip to content

Commit

Permalink
Fix: Color Mode Switcher Shows wrong icon in auto mode. Root cause co…
Browse files Browse the repository at this point in the history
…ntributes to occasional flickering. #546

- Unifies 'auto' and `null` handling for `theme` to simplify code and avoid occasional flickering.
  • Loading branch information
vicentic@immounited.com committed Jan 2, 2025
1 parent 6786420 commit a866669
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions color-modes/js/color-modes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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}"]`)
Expand All @@ -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 => {
Expand Down

0 comments on commit a866669

Please sign in to comment.