Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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