Created
          July 5, 2021 09:11 
        
      - 
      
- 
        Save wobsoriano/db11c14f6742405c3dbb5f900c73b28f to your computer and use it in GitHub Desktop. 
    Solid Theme Provider for Tailwind/Windi
  
        
  
    
      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 { createContext, createEffect, createSignal, useContext } from 'solid-js' | |
| const themeName = 'theme' | |
| const html = document.querySelector('html') | |
| function getInitialTheme() { | |
| const isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches | |
| const storageTheme = localStorage.getItem(themeName) | |
| if (storageTheme) return storageTheme | |
| return isDark ? 'dark' : 'light' | |
| } | |
| const ThemeContext = createContext() | |
| export function ThemeProvider(props) { | |
| const [theme, setTheme] = createSignal(getInitialTheme()) | |
| createEffect(() => { | |
| localStorage.setItem(themeName, theme()) | |
| if (theme() === 'dark') { | |
| html.classList.add('dark') | |
| } else { | |
| html.classList.remove('dark') | |
| } | |
| }) | |
| const store = [ | |
| theme, | |
| { | |
| toggle() { | |
| setTheme((prev) => prev === 'dark' ? 'light' : 'dark') | |
| } | |
| } | |
| ] | |
| return <ThemeContext.Provider value={store}>{props.children}</ThemeContext.Provider>; | |
| } | |
| export function createTheme() { | |
| return useContext(ThemeContext) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment