Skip to content

Commit

Permalink
Improve color modes JS
Browse files Browse the repository at this point in the history
  • Loading branch information
julien-deramond committed May 30, 2023
1 parent 388a10f commit f203ac3
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions docs/assets/js/color-modes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
*/

(() => {
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 @@ -54,7 +56,8 @@
}

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (storedTheme !== 'light' || storedTheme !== 'dark') {
const storedTheme = getStoredTheme()
if (storedTheme !== 'light' && storedTheme !== 'dark') {
setTheme(getPreferredTheme())
}
})
Expand All @@ -67,6 +70,7 @@
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 f203ac3

Please sign in to comment.