slate/components/system/ThemeProvider.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-02-17 21:37:34 +03:00
import * as React from "react";
import * as Constants from "~/common/constants";
import { ThemeProvider as EmotionTP } from "@emotion/react";
export default function ThemeProvider({ children }) {
2021-03-24 20:24:24 +03:00
const [theme, setTheme] = useLocalStorage("slate-theme", {
darkmode: true,
fontPreviewDarkMode: true,
});
2021-02-18 20:39:44 +03:00
const handleSlateTheme = (e) => setTheme((prev) => ({ ...prev, ...e.detail }));
2021-02-17 21:37:34 +03:00
React.useEffect(() => {
if (!window) return;
2021-02-18 20:39:44 +03:00
window.addEventListener("set-slate-theme", handleSlateTheme);
2021-02-17 21:37:34 +03:00
return () => {
if (!window) return;
2021-02-18 20:39:44 +03:00
window.removeEventListener("set-slate-theme", handleSlateTheme);
2021-02-17 21:37:34 +03:00
};
}, []);
const value = React.useMemo(
() => ({
sizes: Constants.sizes,
system: Constants.system,
shadow: Constants.shadow,
zindex: Constants.zindex,
font: Constants.font,
typescale: Constants.typescale,
2021-07-08 00:44:13 +03:00
semantic: Constants.semantic,
grids: Constants.grids,
2021-03-24 20:24:24 +03:00
...theme,
2021-02-17 21:37:34 +03:00
}),
[theme]
);
return (
<EmotionTP theme={value}>
<React.Fragment>{children}</React.Fragment>
</EmotionTP>
);
}
2021-02-18 20:39:44 +03:00
export const useLocalStorage = (key, defaultValue) => {
const [value, setValue] = React.useState(defaultValue);
React.useEffect(() => {
const cachedValue = localStorage.getItem(key);
if (cachedValue) setValue(JSON.parse(cachedValue));
}, []);
React.useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
};