-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSavedViewsContext.tsx
61 lines (50 loc) · 2.15 KB
/
SavedViewsContext.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { createContext, useContext, useMemo, type PropsWithChildren, type ReactElement } from "react";
import { defaultLocalization, type LocalizationStrings } from "./localization.js";
const savedViewsContext = createContext<SavedViewsContext>({ localization: defaultLocalization });
savedViewsContext.displayName = "SavedViewsContext";
export interface SavedViewsContext {
localization: typeof defaultLocalization;
}
interface SavedViewsContextProviderProps {
/** Custom strings to be used within `@itwin/saved-views-react` React components. */
localization?: LocalizationStrings | undefined;
}
/** React context for `@itwin/saved-views-react` components. Optional. */
export function SavedViewsContextProvider(props: PropsWithChildren<SavedViewsContextProviderProps>): ReactElement {
const localization = useMemo(
() => {
if (!props.localization) {
return defaultLocalization;
}
const localization = { ...defaultLocalization };
replaceStringsRecursively(props.localization, localization);
return localization;
},
[props.localization],
);
const contextValue = useMemo(() => ({ localization }), [localization]);
return (
<savedViewsContext.Provider value={contextValue}>
{props.children}
</savedViewsContext.Provider>
);
}
export function useSavedViewsContext(): SavedViewsContext {
return useContext(savedViewsContext);
}
function replaceStringsRecursively(source: Record<string, unknown>, destination: Record<string, unknown>): void {
for (const key in source) {
if (!Object.hasOwnProperty.call(destination, key)) {
return;
}
if (typeof source[key] === "string") {
destination[key] = source[key];
} else {
replaceStringsRecursively(source[key] as Record<string, unknown>, destination[key] as Record<string, unknown>);
}
}
}