/
WithUnifiedSelection.tsx
68 lines (59 loc) · 2.39 KB
/
WithUnifiedSelection.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Viewport
*/
import { memo, useEffect, useState } from "react";
import { ViewportProps } from "@itwin/imodel-components-react";
import { getDisplayName } from "../common/Utils";
import { ViewportSelectionHandler } from "./ViewportSelectionHandler";
/**
* Props that are injected to the ViewWithUnifiedSelection HOC component.
* @public
*/
export interface ViewWithUnifiedSelectionProps {
/** @internal */
selectionHandler?: ViewportSelectionHandler;
}
/**
* A HOC component that adds unified selection functionality to the supplied
* viewport component.
*
* @public
*/
export function viewWithUnifiedSelection<P extends ViewportProps>(
ViewportComponent: React.ComponentType<P>,
): React.ComponentType<P & ViewWithUnifiedSelectionProps> {
type CombinedProps = P & ViewWithUnifiedSelectionProps;
const WithUnifiedSelection = memo<CombinedProps>((props) => {
const { selectionHandler, ...restProps } = props;
const imodel = restProps.imodel;
const [viewportSelectionHandler, setViewportSelectionHandler] = useState<ViewportSelectionHandler>();
// apply currentSelection when 'viewportSelectionHandler' is initialized (set to handler from props or new is created)
useEffect(() => {
if (selectionHandler) {
selectionHandler.applyCurrentSelection();
setViewportSelectionHandler(selectionHandler);
return;
}
const handler = new ViewportSelectionHandler({ imodel });
handler.applyCurrentSelection();
setViewportSelectionHandler(handler);
return () => {
handler.dispose();
};
}, [selectionHandler, imodel]);
// set new imodel on 'viewportSelectionHandler' when it changes
useEffect(() => {
if (!viewportSelectionHandler) {
return;
}
viewportSelectionHandler.imodel = imodel;
}, [viewportSelectionHandler, imodel]);
return <ViewportComponent {...(restProps as P)} />;
});
WithUnifiedSelection.displayName = `WithUnifiedSelection(${getDisplayName(ViewportComponent)})`;
return WithUnifiedSelection;
}