-
Notifications
You must be signed in to change notification settings - Fork 2
/
useActiveViewport.tsx
73 lines (67 loc) · 2.58 KB
/
useActiveViewport.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Hooks
*/
import { useEffect, useState } from "react";
import type { ScreenViewport } from "@itwin/core-frontend";
import { IModelApp } from "@itwin/core-frontend";
import type { ActiveContentChangedEventArgs } from "../framework/FrameworkContent";
import {
SyncUiEventDispatcher,
SyncUiEventId,
} from "../syncui/SyncUiEventDispatcher";
import { UiFramework } from "../UiFramework";
import type { UiSyncEventArgs } from "../syncui/UiSyncEvent";
/** React hook that maintains the active viewport.
* @public
*/
// istanbul ignore next
export function useActiveViewport(): ScreenViewport | undefined {
const [activeViewport, setActiveViewport] = useState(
IModelApp.viewManager.selectedView
);
useEffect(() => {
// eslint-disable-next-line deprecation/deprecation
const onActiveContentChanged = (_args: ActiveContentChangedEventArgs) => {
setActiveViewport(IModelApp.viewManager.selectedView);
};
// IModelApp.viewManager.onSelectedViewportChanged will often fire before UI components have mounted
// so use UiFramework.content.onActiveContentChangedEvent which will always trigger once all stage components
// are loaded and when the IModelApp.viewManager.selectedView changes.
UiFramework.content.onActiveContentChangedEvent.addListener(
onActiveContentChanged
);
return () => {
UiFramework.content.onActiveContentChangedEvent.removeListener(
onActiveContentChanged
);
};
}, []);
useEffect(() => {
const syncIdsOfInterest = [
SyncUiEventId.ActiveContentChanged,
SyncUiEventId.ContentControlActivated,
SyncUiEventId.FrontstageReady,
];
// eslint-disable-next-line deprecation/deprecation
const handleSyncUiEvent = (args: UiSyncEventArgs): void => {
// istanbul ignore else
if (
syncIdsOfInterest.some((value: string): boolean =>
args.eventIds.has(value)
)
) {
const activeContentControl =
UiFramework.content.getActiveContentControl();
setActiveViewport(
activeContentControl && activeContentControl.viewport
);
}
};
return SyncUiEventDispatcher.onSyncUiEvent.addListener(handleSyncUiEvent);
}, []);
return activeViewport;
}