This repository has been archived by the owner on May 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathApp.tsx
231 lines (203 loc) · 8.88 KB
/
App.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { Config, Id64, Id64String, OpenMode } from "@bentley/bentleyjs-core";
import { ContextRegistryClient, Project } from "@bentley/context-registry-client";
import "@bentley/icons-generic-webfont/dist/bentley-icons-generic-webfont.css";
import { IModelQuery } from "@bentley/imodelhub-client";
import { AuthorizedFrontendRequestContext, DrawingViewState, FrontendRequestContext, IModelApp, IModelConnection, RemoteBriefcaseConnection, SpatialViewState } from "@bentley/imodeljs-frontend";
import { SignIn, ViewportComponent } from "@bentley/ui-components";
import { Button, ButtonSize, ButtonType, Spinner, SpinnerSize } from "@bentley/ui-core";
import * as React from "react";
import { BasicViewportApp } from "../api/BasicViewportApp";
import "./App.css";
import Toolbar from "./Toolbar";
// cSpell:ignore imodels
/** React state of the App component */
export interface AppState {
user: {
isAuthorized: boolean;
isLoading: boolean;
};
imodel?: IModelConnection;
viewDefinitionId?: Id64String;
}
/** A component the renders the whole application UI */
export default class App extends React.Component<{}, AppState> {
/** Creates an App instance */
constructor(props?: any, context?: any) {
super(props, context);
this.state = {
user: {
isAuthorized: BasicViewportApp.oidcClient.isAuthorized,
isLoading: false,
},
};
}
public componentDidMount() {
// Initialize authorization state, and add listener to changes
BasicViewportApp.oidcClient.onUserStateChanged.addListener(this._onUserStateChanged);
}
public componentWillUnmount() {
// unsubscribe from user state changes
BasicViewportApp.oidcClient.onUserStateChanged.removeListener(this._onUserStateChanged);
}
private _onStartSignin = async () => {
this.setState((prev) => ({ user: { ...prev.user, isLoading: true } }));
BasicViewportApp.oidcClient.signIn(new FrontendRequestContext()); // eslint-disable-line @typescript-eslint/no-floating-promises
};
private _onUserStateChanged = () => {
this.setState((prev) => ({ user: { ...prev.user, isAuthorized: BasicViewportApp.oidcClient.isAuthorized, isLoading: false } }));
};
/** Pick the first available spatial view definition in the imodel */
private async getFirstViewDefinitionId(imodel: IModelConnection): Promise<Id64String> {
// Return default view definition (if any)
const defaultViewId = await imodel.views.queryDefaultViewId();
if (Id64.isValid(defaultViewId))
return defaultViewId;
// Return first spatial view definition (if any)
const spatialViews: IModelConnection.ViewSpec[] = await imodel.views.getViewList({ from: SpatialViewState.classFullName });
if (spatialViews.length > 0)
return spatialViews[0].id;
// Return first drawing view definition (if any)
const drawingViews: IModelConnection.ViewSpec[] = await imodel.views.getViewList({ from: DrawingViewState.classFullName });
if (drawingViews.length > 0)
return drawingViews[0].id;
throw new Error("No valid view definitions in imodel");
}
/** Handle iModel open event */
private _onIModelSelected = async (imodel: IModelConnection | undefined) => {
if (!imodel) {
// reset the state when imodel is closed
this.setState({ imodel: undefined, viewDefinitionId: undefined });
return;
}
try {
// attempt to get a view definition
const viewDefinitionId = await this.getFirstViewDefinitionId(imodel);
this.setState({ imodel, viewDefinitionId });
} catch (e) {
// if failed, close the imodel and reset the state
await imodel.close();
this.setState({ imodel: undefined, viewDefinitionId: undefined });
alert(e.message);
}
};
private get _signInRedirectUri() {
const split = (Config.App.get("imjs_browser_test_redirect_uri") as string).split("://");
return split[split.length - 1];
}
/** The component's render method */
public render() {
let ui: React.ReactNode;
if (this.state.user.isLoading || window.location.href.includes(this._signInRedirectUri)) {
// if user is currently being loaded, just tell that
ui = `signing-in...`;
} else if (!this.state.user.isAuthorized) {
// if user doesn't have and access token, show sign in page
ui = (<SignIn onSignIn={this._onStartSignin} />);
} else if (!this.state.imodel || !this.state.viewDefinitionId) {
// if we don't have an imodel / view definition id - render a button that initiates imodel open
ui = (<OpenIModelButton onIModelSelected={this._onIModelSelected} />);
} else {
// if we do have an imodel and view definition id - render imodel components
ui = (<IModelComponents imodel={this.state.imodel} viewDefinitionId={this.state.viewDefinitionId} />);
}
// render the app
return (
<div className="app">
{ui}
</div>
);
}
}
/** React props for [[OpenIModelButton]] component */
interface OpenIModelButtonProps {
onIModelSelected: (imodel: IModelConnection | undefined) => void;
}
/** React state for [[OpenIModelButton]] component */
interface OpenIModelButtonState {
isLoading: boolean;
}
/** Renders a button that opens an iModel identified in configuration */
class OpenIModelButton extends React.PureComponent<OpenIModelButtonProps, OpenIModelButtonState> {
public state = { isLoading: false };
/** Finds project and imodel ids using their names */
private async getIModelInfo(): Promise<{ projectId: string, imodelId: string }> {
const imodelName = Config.App.get("imjs_test_imodel");
const projectName = Config.App.get("imjs_test_project", imodelName);
const requestContext: AuthorizedFrontendRequestContext = await AuthorizedFrontendRequestContext.create();
const connectClient = new ContextRegistryClient();
let project: Project;
try {
const projects: Project[] = await connectClient.getInvitedProjects(requestContext, { $filter: `Name+eq+'${projectName}'` });
project = projects[0];
} catch (e) {
throw new Error(`Project with name "${projectName}" does not exist`);
}
const imodelQuery = new IModelQuery();
imodelQuery.byName(imodelName);
const imodels = await IModelApp.iModelClient.iModels.get(requestContext, project.wsgId, imodelQuery);
if (imodels.length === 0)
throw new Error(`iModel with name "${imodelName}" does not exist in project "${projectName}"`);
return { projectId: project.wsgId, imodelId: imodels[0].wsgId };
}
/** Handle iModel open event */
private async onIModelSelected(imodel: IModelConnection | undefined) {
this.props.onIModelSelected(imodel);
this.setState({ isLoading: false });
}
private _onClickOpen = async () => {
this.setState({ isLoading: true });
let imodel: IModelConnection | undefined;
try {
// attempt to open the imodel
const info = await this.getIModelInfo();
imodel = await RemoteBriefcaseConnection.open(info.projectId, info.imodelId, OpenMode.Readonly);
} catch (e) {
alert(e.message);
}
await this.onIModelSelected(imodel);
};
private _onClickSignOut = async () => {
if (BasicViewportApp.oidcClient)
BasicViewportApp.oidcClient.signOut(new FrontendRequestContext()); // eslint-disable-line @typescript-eslint/no-floating-promises
};
public render() {
return (
<div>
<div>
<Button size={ButtonSize.Large} buttonType={ButtonType.Primary} className="button-open-imodel" onClick={this._onClickOpen}>
<span>Open iModel</span>
{this.state.isLoading ? <span style={{ marginLeft: "8px" }}><Spinner size={SpinnerSize.Small} /></span> : undefined}
</Button>
</div>
<div>
<Button size={ButtonSize.Large} buttonType={ButtonType.Primary} className="button-signout" onClick={this._onClickSignOut}>
<span>Sign Out</span>
</Button>
</div>
</div>
);
}
}
/** React props for [[IModelComponents]] component */
interface IModelComponentsProps {
imodel: IModelConnection;
viewDefinitionId: Id64String;
}
/** Renders a viewport */
class IModelComponents extends React.PureComponent<IModelComponentsProps> {
public render() {
return (
<>
<ViewportComponent
style={{ height: "100vh" }}
imodel={this.props.imodel}
viewDefinitionId={this.props.viewDefinitionId} />
<Toolbar />
</>
);
}
}