74 lines
1.6 KiB
TypeScript
74 lines
1.6 KiB
TypeScript
// * Packages
|
|
import {
|
|
createContext,
|
|
ReactNode,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
} from "react";
|
|
// * Other
|
|
import { Theme } from "@/back/types/global";
|
|
|
|
type ThemeProviderProps = {
|
|
children: ReactNode;
|
|
defaultTheme?: Theme;
|
|
storageKey?: string;
|
|
};
|
|
|
|
type ThemeProviderState = {
|
|
theme: Theme;
|
|
// eslint-disable-next-line no-unused-vars
|
|
setTheme: (theme: Theme) => void;
|
|
};
|
|
|
|
const initialState: ThemeProviderState = {
|
|
theme: "light",
|
|
setTheme: () => {},
|
|
};
|
|
|
|
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
|
|
|
export function ThemeProvider({
|
|
children,
|
|
defaultTheme = "light",
|
|
storageKey = "vite-ui-theme",
|
|
}: ThemeProviderProps) {
|
|
const [theme, setTheme] = useState<Theme>(() => {
|
|
const storedTheme = localStorage.getItem(storageKey);
|
|
return (storedTheme as Theme) || defaultTheme;
|
|
});
|
|
|
|
useEffect(() => {
|
|
const root = window.document.documentElement;
|
|
root.classList.remove("light", "dark");
|
|
root.classList.add(theme);
|
|
}, [theme]);
|
|
|
|
const value = useMemo(
|
|
() => ({
|
|
theme,
|
|
setTheme: (newTheme: Theme) => {
|
|
localStorage.setItem(storageKey, newTheme);
|
|
setTheme(newTheme);
|
|
},
|
|
}),
|
|
[theme, setTheme, storageKey],
|
|
);
|
|
|
|
return (
|
|
<ThemeProviderContext.Provider 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;
|
|
};
|