Spaces:
Running
Running
| import { createContext, useContext, useEffect, useState, ReactNode } from 'react'; | |
| interface ThemeContextType { | |
| theme: 'light' | 'dark'; | |
| toggleTheme: () => void; | |
| } | |
| const ThemeContext = createContext<ThemeContextType | undefined>(undefined); | |
| export function ThemeProvider({ children }: { children: ReactNode }) { | |
| const [theme, setTheme] = useState<'light' | 'dark'>('light'); | |
| useEffect(() => { | |
| // Check user preference from localStorage or system preference | |
| const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null; | |
| const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; | |
| if (savedTheme) { | |
| setTheme(savedTheme); | |
| } else if (systemPrefersDark) { | |
| setTheme('dark'); | |
| } | |
| }, []); | |
| useEffect(() => { | |
| // Apply theme to document | |
| document.documentElement.classList.remove('light', 'dark'); | |
| document.documentElement.classList.add(theme); | |
| localStorage.setItem('theme', theme); | |
| }, [theme]); | |
| const toggleTheme = () => { | |
| setTheme(prev => prev === 'light' ? 'dark' : 'light'); | |
| }; | |
| return ( | |
| <ThemeContext.Provider value={{ theme, toggleTheme }}> | |
| {children} | |
| </ThemeContext.Provider> | |
| ); | |
| } | |
| export function useTheme() { | |
| const context = useContext(ThemeContext); | |
| if (context === undefined) { | |
| throw new Error('useTheme must be used within a ThemeProvider'); | |
| } | |
| return context; | |
| } |