mirror of
https://bitbucket.org/Mattrixwv/mattrixwvreactcomponents.git
synced 2025-12-06 21:53:57 -05:00
Most simple components created
This commit is contained in:
61
lib/providers/theme/ThemeProvider.tsx
Normal file
61
lib/providers/theme/ThemeProvider.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import type { Theme, ThemeProviderProps, ThemeProviderState } from "$/types/Theme";
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
|
||||
const themeInitialState: ThemeProviderState = {
|
||||
theme: "system",
|
||||
setTheme: () => null
|
||||
}
|
||||
|
||||
export const ThemeProviderContext = createContext<ThemeProviderState>(themeInitialState);
|
||||
|
||||
|
||||
export default function ThemeProvider(props: ThemeProviderProps){
|
||||
const {
|
||||
children,
|
||||
defaultTheme = "system",
|
||||
storageKey = "mattrixwv-ui-theme"
|
||||
} = props;
|
||||
|
||||
const [ theme, setTheme ] = useState<Theme>((localStorage.getItem(storageKey) as Theme) || defaultTheme);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
root.classList.remove("light", "dark");
|
||||
|
||||
if(theme === "system"){
|
||||
const systemTheme = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
|
||||
|
||||
root.classList.add(systemTheme);
|
||||
}
|
||||
else{
|
||||
root.classList.add(theme);
|
||||
}
|
||||
}, [ theme ]);
|
||||
|
||||
const value: ThemeProviderState = useMemo(() => ({
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
setTheme(theme);
|
||||
}
|
||||
}), [ theme ]);
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
export function useTheme(){
|
||||
const context = useContext(ThemeProviderContext);
|
||||
|
||||
if(!context){
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user