69 lines
1.5 KiB
TypeScript
69 lines
1.5 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
createContext,
|
|
useContext,
|
|
useEffect,
|
|
useState,
|
|
useCallback,
|
|
type ReactNode,
|
|
} from "react";
|
|
|
|
const STORAGE_KEY = "theme";
|
|
|
|
export type Theme = "light" | "dark";
|
|
|
|
type ThemeContextValue = {
|
|
theme: Theme;
|
|
setTheme: (theme: Theme) => void;
|
|
toggleTheme: () => void;
|
|
};
|
|
|
|
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
|
|
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
|
const [theme, setThemeState] = useState<Theme>("light");
|
|
const [mounted, setMounted] = useState(false);
|
|
|
|
useEffect(() => {
|
|
setMounted(true);
|
|
const hasDark = document.documentElement.classList.contains("dark");
|
|
setThemeState(hasDark ? "dark" : "light");
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!mounted) return;
|
|
const root = document.documentElement;
|
|
if (theme === "dark") {
|
|
root.classList.add("dark");
|
|
} else {
|
|
root.classList.remove("dark");
|
|
}
|
|
localStorage.setItem(STORAGE_KEY, theme);
|
|
}, [theme, mounted]);
|
|
|
|
const setTheme = useCallback((newTheme: Theme) => {
|
|
setThemeState(newTheme);
|
|
}, []);
|
|
|
|
const toggleTheme = useCallback(() => {
|
|
setThemeState((prev) => (prev === "light" ? "dark" : "light"));
|
|
}, []);
|
|
|
|
const value: ThemeContextValue = {
|
|
theme,
|
|
setTheme,
|
|
toggleTheme,
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useTheme() {
|
|
const ctx = useContext(ThemeContext);
|
|
if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
|
|
return ctx;
|
|
}
|