71 lines
1.7 KiB
TypeScript
71 lines
1.7 KiB
TypeScript
// /src/app/components/ThemeProvider.tsx
|
|
|
|
'use client';
|
|
|
|
import { useState, useEffect, createContext, useContext } from 'react';
|
|
|
|
interface ThemeContextType {
|
|
theme: string;
|
|
setTheme: (theme: string) => void;
|
|
toggleTheme: () => void;
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
export const useTheme = () => {
|
|
const context = useContext(ThemeContext);
|
|
if (!context) {
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
|
}
|
|
return context;
|
|
};
|
|
|
|
export default function ThemeProvider({ children }: { children?: React.ReactNode }) {
|
|
const [theme, setTheme] = useState<string>('light');
|
|
const [mounted, setMounted] = useState(false);
|
|
|
|
useEffect(() => {
|
|
setMounted(true);
|
|
|
|
// Theme aus localStorage laden
|
|
const savedTheme = localStorage.getItem('hs_theme');
|
|
if (savedTheme) {
|
|
setTheme(savedTheme);
|
|
applyTheme(savedTheme);
|
|
} else {
|
|
// Standardtheme auf 'light' setzen
|
|
setTheme('light');
|
|
localStorage.setItem('hs_theme', 'light');
|
|
applyTheme('light');
|
|
}
|
|
}, []);
|
|
|
|
const applyTheme = (newTheme: string) => {
|
|
if (newTheme === 'dark') {
|
|
document.documentElement.classList.add('dark');
|
|
} else {
|
|
document.documentElement.classList.remove('dark');
|
|
}
|
|
};
|
|
|
|
const handleSetTheme = (newTheme: string) => {
|
|
setTheme(newTheme);
|
|
localStorage.setItem('hs_theme', newTheme);
|
|
applyTheme(newTheme);
|
|
};
|
|
|
|
const toggleTheme = () => {
|
|
const newTheme = theme === 'light' ? 'dark' : 'light';
|
|
handleSetTheme(newTheme);
|
|
};
|
|
|
|
if (!mounted) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, setTheme: handleSetTheme, toggleTheme }}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
} |