50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
|
|
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||
|
|
|
||
|
|
type Theme = 'dark' | 'light' | 'ocean';
|
||
|
|
|
||
|
|
interface ThemeContextType {
|
||
|
|
theme: Theme;
|
||
|
|
setTheme: (theme: Theme) => void;
|
||
|
|
}
|
||
|
|
|
||
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||
|
|
|
||
|
|
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||
|
|
const [theme, setTheme] = useState<Theme>(() => {
|
||
|
|
// Check local storage or system preference
|
||
|
|
const saved = localStorage.getItem('theme');
|
||
|
|
if (saved) return saved as Theme;
|
||
|
|
return 'dark'; // Default
|
||
|
|
});
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const root = window.document.documentElement;
|
||
|
|
|
||
|
|
// Remove old classes
|
||
|
|
root.classList.remove('theme-light', 'theme-ocean', 'dark');
|
||
|
|
|
||
|
|
// Add new class
|
||
|
|
if (theme === 'dark') {
|
||
|
|
root.classList.add('dark');
|
||
|
|
} else {
|
||
|
|
root.classList.add(`theme-${theme}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
localStorage.setItem('theme', theme);
|
||
|
|
}, [theme]);
|
||
|
|
|
||
|
|
return (
|
||
|
|
<ThemeContext.Provider value={{ theme, setTheme }}>
|
||
|
|
{children}
|
||
|
|
</ThemeContext.Provider>
|
||
|
|
);
|
||
|
|
};
|
||
|
|
|
||
|
|
export const useTheme = () => {
|
||
|
|
const context = useContext(ThemeContext);
|
||
|
|
if (context === undefined) {
|
||
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
||
|
|
}
|
||
|
|
return context;
|
||
|
|
};
|