website/components/ThemeProvider.tsx
2025-11-06 12:02:10 +00:00

58 lines
1.7 KiB
TypeScript

"use client";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
type Theme = "light" | "dark";
type ThemeContextValue = {
theme: Theme;
setTheme: (t: Theme) => void;
toggleTheme: () => void;
};
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
export function useAppTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useAppTheme must be used within ThemeProvider");
return ctx;
}
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setThemeState] = useState<Theme>("light");
const setTheme = (t: Theme) => setThemeState(t);
// Initialize from localStorage or system preference on mount
useEffect(() => {
const stored = typeof window !== "undefined" ? localStorage.getItem("theme") : null;
if (stored === "light" || stored === "dark") {
setThemeState(stored);
return;
}
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
setThemeState(prefersDark ? "dark" : "light");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Apply class to <html> and persist
useEffect(() => {
const root = document.documentElement;
if (theme === "dark") {
root.classList.add("dark");
} else {
root.classList.remove("dark");
}
localStorage.setItem("theme", theme);
}, [theme]);
const value = useMemo<ThemeContextValue>(() => ({
theme,
setTheme,
toggleTheme: () => setThemeState((t) => (t === "dark" ? "light" : "dark")),
}), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}