Skip to content

Commit

Permalink
fixed theme to change only if different from current and to watch pre…
Browse files Browse the repository at this point in the history
…ferred color scheme changes
  • Loading branch information
novcmbro committed Jun 6, 2024
1 parent a10e150 commit 24320c6
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/js/theme.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
const prefersLightTheme = window.matchMedia("(prefers-color-scheme: light)")
const localStorageKey = "novcmbro_decoder_theme"
const rootElement = document.documentElement

const theme = {
preferred: undefined,
db: () => localStorage.getItem(localStorageKey),
update: undefined,
init: undefined,
change: undefined
}

theme.update = () => rootElement.classList = theme.db()
theme.preferred = () => prefersLightTheme.matches ? "light" : "dark"

theme.init = () => {
const prefersLightTheme = window.matchMedia("(prefers-color-scheme: light)").matches
theme.update = () => rootElement.className = theme.db()

theme.init = () => {
if (!theme.db()) {
localStorage.setItem(localStorageKey, prefersLightTheme ? "light" : "dark")
localStorage.setItem(localStorageKey, theme.preferred())
}

prefersLightTheme.addEventListener("change", () => {
localStorage.setItem(localStorageKey, theme.preferred())
theme.update()
})

theme.update()
}

theme.change = ({ currentTarget }) => {
const themeName = currentTarget.classList[1]
localStorage.setItem(localStorageKey, themeName)
theme.update()

if (rootElement.className !== themeName) {
localStorage.setItem(localStorageKey, themeName)
theme.update()
}
}

const { init, change } = theme
Expand Down

0 comments on commit 24320c6

Please sign in to comment.