-
Notifications
You must be signed in to change notification settings - Fork 2
/
useUiStateStorage.tsx
75 lines (67 loc) · 2.29 KB
/
useUiStateStorage.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
71
72
73
74
75
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module UiStateStorage
*/
import * as React from "react";
import type { UiStateStorage } from "@itwin/core-react";
import { LocalStateStorage } from "@itwin/core-react";
import { UiFramework } from "../UiFramework";
import {
SyncUiEventDispatcher,
SyncUiEventId,
} from "../syncui/SyncUiEventDispatcher";
import type { UiSyncEventArgs } from "../syncui/UiSyncEvent";
/** @public */
export function useUiStateStorageHandler(): UiStateStorage {
return React.useContext(UiStateStorageContext);
}
/** @internal */
export const UiStateStorageContext = React.createContext<UiStateStorage>(
new LocalStateStorage()
);
UiStateStorageContext.displayName = "uifw:UiStateStorageContext";
/** Properties for the [[UiStateStorageHandler]] component.
* @public
*/
export interface UiSettingsProviderProps {
children?: React.ReactNode;
}
/** Allows to provide a custom [[UiStateStorage]] implementation to persist UI settings
* through [[UiFramework.setUiStateStorage]].
*
* This component should wrap the [[ConfigurableUiContent]].
*
* ```tsx
* <UiStateStorageHandler>
* <ConfigurableUiContent />
* </UiStateStorageHandler>
* ```
* @public
*/
export function UiStateStorageHandler(props: UiSettingsProviderProps) {
const [stateStorage, setStateStorage] = React.useState(
UiFramework.getUiStateStorage()
);
React.useEffect(() => {
// istanbul ignore next
// eslint-disable-next-line deprecation/deprecation
const handleSyncUiEvent = (args: UiSyncEventArgs): void => {
if (
SyncUiEventDispatcher.hasEventOfInterest(args.eventIds, [
SyncUiEventId.UiStateStorageChanged,
])
)
setStateStorage(UiFramework.getUiStateStorage());
};
return SyncUiEventDispatcher.onSyncUiEvent.addListener(handleSyncUiEvent);
});
return (
<UiStateStorageContext.Provider
children={props.children} // eslint-disable-line react/no-children-prop
value={stateStorage}
/>
);
}