-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathLayoutSettingsContext.tsx
70 lines (59 loc) · 1.75 KB
/
LayoutSettingsContext.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { isEqual, merge } from 'lodash-es';
import React, { useContext, useEffect, useState } from 'react';
import { PartialDeep } from 'type-fest';
import { HeaderProps } from 'app/components/Header';
type LayoutSettings = {
header: HeaderProps;
};
const DEFAULT_LAYOUT_SETTINGS: LayoutSettings = {
header: {},
};
type LayoutSettingsContextType = {
layoutSettings: LayoutSettings;
setLayoutSettings: (newLayoutSettings: LayoutSettings) => void;
};
export const LayoutSettingsContext =
React.createContext<LayoutSettingsContextType>({
layoutSettings: DEFAULT_LAYOUT_SETTINGS,
/* eslint-disable-next-line @typescript-eslint/no-empty-function */
setLayoutSettings: () => {},
});
export const LayoutSettingsContextProvider: React.FC = function ({ children }) {
const [layoutSettings, setLayoutSettings] = useState(DEFAULT_LAYOUT_SETTINGS);
return (
<LayoutSettingsContext.Provider
value={{
layoutSettings,
setLayoutSettings,
}}
>
{children}
</LayoutSettingsContext.Provider>
);
};
export const setLayoutSettings = function (
settings: PartialDeep<LayoutSettings>
): void {
const { layoutSettings, setLayoutSettings } = useContext(
LayoutSettingsContext
);
// Ensure the settings are actually being changed before updating
const mergedLayoutSettings = merge(
{},
DEFAULT_LAYOUT_SETTINGS,
layoutSettings,
settings
);
if (!isEqual(layoutSettings, mergedLayoutSettings)) {
useEffect(() => {
return setLayoutSettings(mergedLayoutSettings);
}, [mergedLayoutSettings]);
}
};
export const HeaderSettings: React.FC<HeaderProps> = function ({
background,
scrollBackground,
}) {
setLayoutSettings({ header: { background, scrollBackground } });
return <></>;
};