51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
|
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)!;
|
||
|
}
|