Skip to content

Commit

Permalink
theme switcher
Browse files Browse the repository at this point in the history
  • Loading branch information
serikshaikamalov committed Jul 3, 2024
1 parent 2f7525f commit 4fee4cb
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions states/themeSwitcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
export const THEME_NAME = {
dark: 'dark',
light: 'light',
}

export const isDarkMode = () =>
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

const getSystemTheme = () => (isDarkMode() ? THEME_NAME.dark : THEME_NAME.light)

class ThemeSwitcher extends EventTarget {
constructor() {
super()
this.set(localStorage.getItem('theme'))
}
set(_theme) {
this.theme = _theme
if (!this.theme) {
this.theme = "auto"
}
localStorage.setItem('theme', this.theme)
if (this.theme === "auto") {
const systemTheme = getSystemTheme()
document.documentElement.setAttribute('data-theme', systemTheme)
} else {
document.documentElement.setAttribute('data-theme', this.theme)
}

// Displatch the current state
this.dispatchEvent(
new CustomEvent('updated', {
detail: { theme: this.theme },
})
)
}
toggle() {
if (this.theme === THEME_NAME.dark) {
this.set(THEME_NAME.light)
} else {
this.set(THEME_NAME.dark)
}
}
}
const themeSwithcherState = new ThemeSwitcher()

if (window.matchMedia) {
var colorSchemeQuery = window.matchMedia('(prefers-color-scheme: dark)')
colorSchemeQuery.addEventListener('change', () => {
themeSwithcherState.set(getSystemTheme())
})
}

export { themeSwithcherState }

0 comments on commit 4fee4cb

Please sign in to comment.