Last active
          July 4, 2021 04:31 
        
      - 
      
- 
        Save wobsoriano/9ba8f5ec4d74f6f8c095623c24191df3 to your computer and use it in GitHub Desktop. 
    Svelte Theme Store
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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