Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active July 4, 2021 04:31
Show Gist options
  • Save wobsoriano/9ba8f5ec4d74f6f8c095623c24191df3 to your computer and use it in GitHub Desktop.
Save wobsoriano/9ba8f5ec4d74f6f8c095623c24191df3 to your computer and use it in GitHub Desktop.
Svelte Theme Store
import { writable } from 'svelte/store'
const html = document.querySelector('html')
const storedTheme = localStorage.getItem('theme')
function isSystemThemeDark() {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
}
function createThemeStore() {
const isDark = writable(storedTheme ? storedTheme === 'dark' : isSystemThemeDark())
const toggle = () => {
isDark.update(prev => !prev)
}
isDark.subscribe((value) => {
localStorage.setItem('theme', value ? 'dark' : 'light')
// For tailwind/windi
if (value) {
html.classList.add('dark')
} else {
html.classList.remove('dark')
}
})
return {
isDark,
toggle
}
}
export const theme = createThemeStore()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment