mirror of
https://github.com/tips-of-mine/gestion-certificats2.git
synced 2025-06-28 06:58:43 +02:00
69 lines
1.7 KiB
TypeScript
69 lines
1.7 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
|
|
|
type Theme = 'light' | 'dark';
|
|
|
|
interface ThemeContextType {
|
|
theme: Theme;
|
|
toggleTheme: () => void;
|
|
setTheme: (theme: Theme) => void;
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
export const useThemeContext = () => {
|
|
const context = useContext(ThemeContext);
|
|
if (context === undefined) {
|
|
throw new Error('useThemeContext must be used within a ThemeProvider');
|
|
}
|
|
return context;
|
|
};
|
|
|
|
interface ThemeProviderProps {
|
|
children: ReactNode;
|
|
}
|
|
|
|
export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
|
const [theme, setThemeState] = useState<Theme>('light');
|
|
|
|
useEffect(() => {
|
|
// Load theme from localStorage or system preference
|
|
const savedTheme = localStorage.getItem('theme') as Theme;
|
|
if (savedTheme) {
|
|
setThemeState(savedTheme);
|
|
} else {
|
|
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
setThemeState(prefersDark ? 'dark' : 'light');
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
// Apply theme to document
|
|
const root = document.documentElement;
|
|
if (theme === 'dark') {
|
|
root.classList.add('dark');
|
|
} else {
|
|
root.classList.remove('dark');
|
|
}
|
|
localStorage.setItem('theme', theme);
|
|
}, [theme]);
|
|
|
|
const toggleTheme = () => {
|
|
setThemeState(prev => prev === 'light' ? 'dark' : 'light');
|
|
};
|
|
|
|
const setTheme = (newTheme: Theme) => {
|
|
setThemeState(newTheme);
|
|
};
|
|
|
|
const value: ThemeContextType = {
|
|
theme,
|
|
toggleTheme,
|
|
setTheme,
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={value}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
}; |