Skip to content

Commit a866669

Browse files
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.
1 parent 6786420 commit a866669

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

color-modes/js/color-modes.js

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,23 @@
88
'use strict'
99

1010
const getStoredTheme = () => localStorage.getItem('theme')
11-
const setStoredTheme = theme => localStorage.setItem('theme', theme)
12-
13-
const getPreferredTheme = () => {
14-
const storedTheme = getStoredTheme()
15-
if (storedTheme) {
16-
return storedTheme
11+
const setStoredTheme = theme => {
12+
if (theme == null || theme === 'auto') {
13+
localStorage.removeItem('theme');
14+
} else {
15+
localStorage.setItem('theme', theme)
1716
}
18-
19-
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
2017
}
2118

2219
const setTheme = theme => {
23-
if (theme === 'auto') {
20+
if (theme == null || theme === 'auto') {
2421
document.documentElement.setAttribute('data-bs-theme', (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'))
2522
} else {
2623
document.documentElement.setAttribute('data-bs-theme', theme)
2724
}
2825
}
2926

30-
setTheme(getPreferredTheme())
27+
setTheme(getStoredTheme())
3128

3229
const showActiveTheme = (theme, focus = false) => {
3330
const themeSwitcher = document.querySelector('#bd-theme')
@@ -36,6 +33,10 @@
3633
return
3734
}
3835

36+
if (theme == null) {
37+
theme = 'auto'
38+
}
39+
3940
const themeSwitcherText = document.querySelector('#bd-theme-text')
4041
const activeThemeIcon = document.querySelector('.theme-icon-active use')
4142
const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`)
@@ -58,14 +59,14 @@
5859
}
5960

6061
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
61-
const storedTheme = getStoredTheme()
62-
if (storedTheme !== 'light' && storedTheme !== 'dark') {
63-
setTheme(getPreferredTheme())
62+
const storedTheme = getStoredTheme();
63+
if (storedTheme == null || storedTheme === 'auto') {
64+
setTheme(); // react on system theme change only in `auto` mode.
6465
}
6566
})
6667

6768
window.addEventListener('DOMContentLoaded', () => {
68-
showActiveTheme(getPreferredTheme())
69+
showActiveTheme(getStoredTheme())
6970

7071
document.querySelectorAll('[data-bs-theme-value]')
7172
.forEach(toggle => {

0 commit comments

Comments
 (0)