0
0
mirror of https://github.com/twbs/bootstrap.git synced 2025-02-19 16:54:24 +01:00

Update color-modes.js (#38626)

* 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
This commit is contained in:
Jeroen Akkerman 2023-05-26 06:18:49 +02:00 committed by GitHub
parent de6b9a7933
commit f0be063c97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,9 +7,11 @@
(() => {
'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
}
@ -17,7 +19,7 @@
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 {
@ -56,6 +58,7 @@
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
const storedTheme = getStoredTheme()
if (storedTheme !== 'light' || storedTheme !== 'dark') {
setTheme(getPreferredTheme())
}
@ -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)
})