open-swe/apps/web/src/components/theme-provider.tsx

87 lines
1.8 KiB
TypeScript
Raw Normal View History

"use client";
import { createContext, useContext, useEffect, useState } from "react";
type Theme = "dark" | "light" | "system";
type ThemeProviderProps = {
children: React.ReactNode;
defaultTheme?: Theme;
storageKey?: string;
};
type ThemeProviderState = {
theme: Theme;
setTheme: (theme: Theme) => void;
};
const initialState: ThemeProviderState = {
theme: "system",
setTheme: () => null,
};
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
export function ThemeProvider({
children,
defaultTheme = "system",
storageKey = "theme",
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(defaultTheme);
useEffect(() => {
const savedTheme = localStorage.getItem(storageKey) as Theme | null;
if (savedTheme) {
setTheme(savedTheme);
}
}, [storageKey]);
useEffect(() => {
const root = window.document.documentElement;
// Determine the target theme
let targetTheme: string;
if (theme === "system") {
targetTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
} else {
targetTheme = theme;
}
// Only apply theme if it's not already present
if (!root.classList.contains(targetTheme)) {
root.classList.remove("light", "dark");
root.classList.add(targetTheme);
}
}, [theme]);
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
},
};
return (
<ThemeProviderContext.Provider
{...props}
value={value}
>
{children}
</ThemeProviderContext.Provider>
);
}
export const useTheme = () => {
const context = useContext(ThemeProviderContext);
if (context === undefined) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
};