GeneIT/geneit_app/src/context_providers/DarkThemeProvider.tsx

58 lines
1.3 KiB
TypeScript

import { ThemeProvider, createTheme } from "@mui/material/styles";
import React from "react";
import { PropsWithChildren } from "react";
import { frFR as dataGridFr } from "@mui/x-data-grid";
const localStorageKey = "dark-theme";
const darkTheme = createTheme(
{
palette: {
mode: "dark",
},
},
dataGridFr
);
const lightTheme = createTheme(
{
palette: {
mode: "light",
},
},
dataGridFr
);
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) === "true"
);
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)!;
}