Files
Termix/src/components/theme-provider.tsx
T

74 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-09-12 14:42:00 -05:00
import { createContext, useContext, useEffect, useState } from "react";
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
type Theme = "dark" | "light" | "system";
2025-08-07 02:20:27 -05:00
type ThemeProviderProps = {
2025-09-12 14:42:00 -05:00
children: React.ReactNode;
defaultTheme?: Theme;
storageKey?: string;
};
2025-08-07 02:20:27 -05:00
type ThemeProviderState = {
2025-09-12 14:42:00 -05:00
theme: Theme;
setTheme: (theme: Theme) => void;
};
2025-08-07 02:20:27 -05:00
const initialState: ThemeProviderState = {
2025-09-12 14:42:00 -05:00
theme: "system",
setTheme: () => null,
};
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
2025-08-07 02:20:27 -05:00
export function ThemeProvider({
2025-09-12 14:42:00 -05:00
children,
defaultTheme = "system",
storageKey = "vite-ui-theme",
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
);
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
useEffect(() => {
const root = window.document.documentElement;
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
root.classList.remove("light", "dark");
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light";
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
root.classList.add(systemTheme);
return;
2025-08-07 02:20:27 -05:00
}
2025-09-12 14:42:00 -05:00
root.classList.add(theme);
}, [theme]);
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
},
};
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
);
2025-08-07 02:20:27 -05:00
}
export const useTheme = () => {
2025-09-12 14:42:00 -05:00
const context = useContext(ThemeProviderContext);
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
if (context === undefined)
throw new Error("useTheme must be used within a ThemeProvider");
2025-08-07 02:20:27 -05:00
2025-09-12 14:42:00 -05:00
return context;
};