2025-07-23 22:26:54 -04:00
|
|
|
import { createContext, useContext, useEffect, useState } from 'react';
|
|
|
|
|
|
|
|
|
|
const ThemeContext = createContext();
|
|
|
|
|
|
2026-06-02 01:50:35 -04:00
|
|
|
function readThemeFromStorage() {
|
|
|
|
|
if (typeof window === 'undefined') return 'light';
|
|
|
|
|
return localStorage.getItem('theme') || 'light';
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-23 22:26:54 -04:00
|
|
|
export function ThemeProvider({ children }) {
|
2026-06-02 01:50:35 -04:00
|
|
|
const [theme, setTheme] = useState(readThemeFromStorage);
|
2025-07-23 22:26:54 -04:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-06-02 01:50:35 -04:00
|
|
|
document.documentElement.setAttribute('data-theme', theme);
|
|
|
|
|
}, [theme]);
|
2025-07-23 22:26:54 -04:00
|
|
|
|
|
|
|
|
const toggleTheme = () => {
|
|
|
|
|
const newTheme = theme === 'light' ? 'dark' : 'light';
|
|
|
|
|
setTheme(newTheme);
|
|
|
|
|
localStorage.setItem('theme', newTheme);
|
|
|
|
|
document.documentElement.setAttribute('data-theme', newTheme);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|