Skip to content

Commit

Permalink
Update color-modes.js (#38626)
Browse files Browse the repository at this point in the history
* Update color-modes.js

Fix IF statement in the prefer-color-scheme change listener always evaluating to `true` and changing the theme to "dark" even when "light" is set as the preferred theme.

| `||` | `x !== "light"` | `x !== "dark"` | Result |
|--|:--:|:--:|:--:|
| `x = "light"` | ○ | ● | ● |
| `x = "dark"` | ● | ○ | ● |
| `x = "auto"` | ● | ● | ● |
| `x = "bogus"` | ● | ● | ● |
<hr>

| `&&` | `x !== "light"` | `x !== "dark"` | Result |
|--|:--:|:--:|:--:|
| `x = "light"` | ○ | ● | ○ |
| `x = "dark"` | ● | ○ | ○ |
| `x = "auto"` | ● | ● | ● |
| `x = "bogus"` | ● | ● | ● |

* Implement re-read of stored theme
  • Loading branch information
Ionaru committed May 26, 2023
1 parent de6b9a7 commit f0be063
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions site/static/docs/5.3/assets/js/color-modes.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@
(() => {
'use strict'

const storedTheme = localStorage.getItem('theme')
const getStoredTheme = () => localStorage.getItem('theme')
const setStoredTheme = theme => localStorage.setItem('theme', theme)

const getPreferredTheme = () => {
const storedTheme = getStoredTheme()
if (storedTheme) {
return storedTheme
}

return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

const setTheme = function (theme) {
const setTheme = theme => {
if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.setAttribute('data-bs-theme', 'dark')
} else {
Expand Down Expand Up @@ -56,6 +58,7 @@
}

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
const storedTheme = getStoredTheme()
if (storedTheme !== 'light' || storedTheme !== 'dark') {
setTheme(getPreferredTheme())
}
Expand All @@ -68,7 +71,7 @@
.forEach(toggle => {
toggle.addEventListener('click', () => {
const theme = toggle.getAttribute('data-bs-theme-value')
localStorage.setItem('theme', theme)
setStoredTheme(theme)
setTheme(theme)
showActiveTheme(theme, true)
})
Expand Down

0 comments on commit f0be063

Please sign in to comment.