SolarEnergy/central_frontend/src/hooks/context_providers/DarkThemeProvider.tsx

51 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-06-29 11:26:12 +00:00
import { ThemeProvider, createTheme } from "@mui/material/styles";
import React from "react";
import { PropsWithChildren } from "react";
const localStorageKey = "dark-theme";
const darkTheme = createTheme({
palette: {
mode: "dark",
},
});
const lightTheme = createTheme({
palette: {
mode: "light",
},
});
interface DarkThemeContext {
enabled: boolean;
setEnabled: (enabled: boolean) => void;
}
const DarkThemeContextK = React.createContext<DarkThemeContext | null>(null);
export function DarkThemeProvider(p: PropsWithChildren): React.ReactElement {
const [enabled, setEnabled] = React.useState(
localStorage.getItem(localStorageKey) !== "false"
);
return (
<DarkThemeContextK.Provider
value={{
enabled: enabled,
setEnabled(enabled) {
localStorage.setItem(localStorageKey, enabled ? "true" : "false");
setEnabled(enabled);
},
}}
>
<ThemeProvider theme={enabled ? darkTheme : lightTheme}>
{p.children}
</ThemeProvider>
</DarkThemeContextK.Provider>
);
}
export function useDarkTheme(): DarkThemeContext {
return React.useContext(DarkThemeContextK)!;
}