-
Notifications
You must be signed in to change notification settings - Fork 745
/
inspector.tsx
452 lines (401 loc) · 14.7 KB
/
inspector.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Framework Emulator Github:
// https://github.com/Microsoft/BotFramwork-Emulator
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Cheating here and pulling in a module from node. Can be easily replaced if we ever move the emulator to the web.
import { join, normalize } from 'path';
import {
ExtensionInspector,
InspectorAccessory,
logEntry,
LogLevel,
luisEditorDeepLinkItem,
textItem,
} from '@bfemulator/sdk-shared';
import { PrimaryButton, Spinner } from '@bfemulator/ui-react';
import { IBotConfiguration } from 'botframework-config/lib/schema';
import * as React from 'react';
import { ExtensionManager, GetInspectorResult, InspectorAPI } from '../../../../../extensions';
import { LogService } from '../../../../../platform/log/logService';
import Panel, { PanelContent, PanelControls } from '../../../panel/panel';
import * as styles from './inspector.scss';
interface InspectObject {
[key: string]: any;
}
interface GetInspectorResultInternal {
response: GetInspectorResult;
inspectObj: InspectObject;
}
interface AccessoryButton {
config: InspectorAccessory;
state: string;
enabled: boolean;
}
interface IpcMessageEvent extends Event {
channel: string;
args: any[];
}
interface InspectorProps {
appPath?: string;
document: any;
themeInfo: { themeName: string; themeComponents: string[] };
activeBot?: IBotConfiguration;
botHash?: string;
trackEvent?: (name: string, properties?: { [key: string]: any }) => void;
}
interface InspectorState {
titleOverride?: string;
activeBot?: IBotConfiguration;
botHash?: string;
inspectorSrc?: string;
inspectObj: InspectObject;
themeInfo: { themeName: string; themeComponents: string[] };
inspector: ExtensionInspector;
buttons: AccessoryButton[];
title: string;
containerRef: HTMLDivElement;
}
declare type ElectronHTMLWebViewElement = HTMLWebViewElement & {
send: (...args: any[]) => void;
};
export class Inspector extends React.Component<InspectorProps, InspectorState> {
private static renderAccessoryIcon(icon: string) {
if (icon === 'Spinner') {
return <Spinner segmentRadius={2} width={25} height={25} />;
} else if (icon) {
return <i className={`${styles.accessoryButtonIcon} ms-Icon ms-Icon--${icon}`} aria-hidden="true" />;
} else {
return false;
}
}
public get state(): InspectorState {
return this._state;
}
public set state(value: InspectorState) {
const oldState = this.state;
this._state = value;
this.stateChanged(value, oldState);
}
private _state = {} as InspectorState;
private webViewByLocation: {
[location: string]: ElectronHTMLWebViewElement;
} = {};
private domReadyByLocation = {};
public static getDerivedStateFromProps(newProps: InspectorProps, prevState: InspectorState): InspectorState {
const { document = {} } = newProps;
const inspectorResult = Inspector.getInspector(document.inspectorObjects);
const { inspector = { name: '' } } = inspectorResult.response;
if (
newProps.botHash !== prevState.botHash ||
inspector.src !== prevState.inspectorSrc ||
newProps.themeInfo.themeName !== prevState.themeInfo.themeName ||
JSON.stringify(inspectorResult.inspectObj) !== JSON.stringify(prevState.inspectObj)
) {
return {
...prevState,
activeBot: newProps.activeBot,
botHash: newProps.botHash,
inspector,
inspectorSrc: inspector.src,
inspectObj: inspectorResult.inspectObj,
themeInfo: newProps.themeInfo,
title: inspector.name,
buttons: Inspector.getButtons(inspector.accessories),
};
}
return null;
}
private static getInspector(inspectorObjects: InspectObject[] = []): GetInspectorResultInternal {
const obj = inspectorObjects[0];
return {
inspectObj: obj,
// Find an inspector for this object.
response: obj ? ExtensionManager.inspectorForObject(obj, true) || {} : ({} as any),
};
}
private static getButtons(accessories: InspectorAccessory[] = []): AccessoryButton[] {
return accessories
.map(config => {
// Accessory must have a "default" state to be added
if (config && config.states.default) {
return {
config,
state: 'default',
enabled: true,
};
} else {
return null;
}
})
.filter(accessoryState => !!accessoryState);
}
public componentDidMount() {
window.addEventListener('toggle-inspector-devtools', this.toggleDevTools);
this.updateInspector(this.state).catch();
}
public componentWillUnmount() {
window.removeEventListener('toggle-inspector-devtools', this.toggleDevTools);
}
public render() {
if (this.state.inspector && this.state.inspectObj) {
return (
<div className={styles.detailPanel}>
<Panel title={['inspector', this.state.title].filter(s => s && s.length).join(' - ')}>
{this.renderAccessoryButtons()}
<PanelContent>
<div className={styles.inspectorContainer} tabIndex={0}>
<div ref={this.webViewContainer} className={styles.webViewContainer} />
</div>
</PanelContent>
</Panel>
</div>
);
} else {
return (
// No inspector was found.
<div className={styles.detailPanel}>
<Panel title={`inspector`}>
<PanelContent>
<div className={styles.nothingInspected}>
Click on a log item in the panel below to inspect activity.
<br />
<br />
{
'You can also inspect the JSON responses from your LUIS and QnA Maker services by selecting a "trace" activity. '
}
<a href="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-debug-emulator?view=azure-bot-service-4.0">
Learn More.
</a>
</div>
</PanelContent>
</Panel>
</div>
);
}
}
private renderAccessoryButton(button: AccessoryButton, onClickHandler: (id: string) => void) {
const { config, state, enabled } = button;
const currentState = config.states[state] || {};
const { icon, ...buttonAttrs } = currentState;
return (
<PrimaryButton
{...buttonAttrs}
className={styles.accessoryButton}
key={config.id}
disabled={!enabled}
onClick={() => onClickHandler(config.id)}
>
{Inspector.renderAccessoryIcon(icon)}
{currentState.label}
</PrimaryButton>
);
}
// eslint-disable-next-line typescript/no-unused-vars
private renderAccessoryButtons() {
return (
<PanelControls>
{this.state.buttons.map(accessoryButton => this.renderAccessoryButton(accessoryButton, this.accessoryClick))}
</PanelControls>
);
}
private stateChanged(newState: InspectorState, oldState: InspectorState): void {
if (oldState.botHash !== newState.botHash) {
this.botUpdated(newState.activeBot);
}
if (oldState.inspectorSrc !== newState.inspectorSrc || oldState.containerRef !== newState.containerRef) {
this.updateInspector(this.state).catch();
}
if (JSON.stringify(oldState.inspectObj) !== JSON.stringify(newState.inspectObj)) {
this.inspect(newState.inspectObj);
}
if ((oldState.themeInfo || { themeName: '' }).themeName !== newState.themeInfo.themeName) {
this.sendToInspector('theme', newState.themeInfo);
}
}
private async updateInspector(state: InspectorState): Promise<void> {
const { src } = state.inspector || { src: '' };
if (!src) {
return;
}
const encodedSrc = encodeURI(src);
const { webViewByLocation: webViews } = this;
if (!webViews[encodedSrc]) {
webViews[encodedSrc] = this.createWebView(state);
} else {
this.sendInitializationStackToInspector();
}
const nextInspector = webViews[encodedSrc] || (webViews[encodedSrc] = this.createWebView(state));
nextInspector.style.display = '';
const { containerRef } = this.state;
if (!containerRef) {
return;
}
if (!containerRef.contains(nextInspector)) {
containerRef.appendChild(nextInspector);
nextInspector.addEventListener('dom-ready', this.onWebViewDOMReady);
}
Array.prototype.forEach.call(containerRef.children, child => {
if (child !== nextInspector) {
child.style.display = 'none';
}
});
}
private createWebView(state: InspectorState): ElectronHTMLWebViewElement {
const appPath = normalize(this.props.appPath);
const preload = normalize(join('file://', appPath, '/node_modules/@bfemulator/client/public/inspector-preload.js'));
const webView: ElectronHTMLWebViewElement = document.createElement('webview');
webView.className = styles.webViewContainer;
webView.addEventListener('dragenter', this.onInspectorDrag, true);
webView.addEventListener('dragover', this.onInspectorDrag, true);
webView.addEventListener('ipc-message', this.ipcMessageEventHandler);
webView.setAttribute('partition', `persist:${state.botHash}`);
webView.setAttribute('preload', preload);
webView.setAttribute('src', encodeURI(state.inspector.src));
return webView;
}
private webViewContainer = (ref: HTMLDivElement): void => {
this.setState({ containerRef: ref });
};
private enableAccessory = (id: string, enable: boolean) => {
const button = this.state.buttons.find(buttonArg => buttonArg.config.id === id);
if (button) {
if (button.enabled !== enable) {
button.enabled = enable;
this.setState(this.state);
}
}
};
private setAccessoryState = (id: string, state: string) => {
const button = this.state.buttons.find(buttonArg => buttonArg.config.id === id);
if (button && button.state !== state) {
const { config } = button;
if (config.states[state]) {
button.state = state;
this.setState(this.state);
}
}
};
private setInspectorTitle = (title: string) => {
if (this.state.title !== title) {
this.setState({ title });
}
};
private accessoryClick = (id: string): void => {
this.sendToInspector('accessory-click', id);
};
private toggleDevTools = (): void => {
this.sendToInspector('toggle-dev-tools');
};
private canInspect(inspectObj: InspectObject): boolean {
return this.state.inspector.name === 'JSON' || InspectorAPI.canInspect(this.state.inspector, inspectObj);
}
private onWebViewDOMReady = (event: Event) => {
const webView = event.currentTarget as ElectronHTMLWebViewElement;
this.domReadyByLocation[webView.getAttribute('src')] = true;
webView.removeEventListener('dom-ready', this.onWebViewDOMReady);
this.sendInitializationStackToInspector();
};
private ipcMessageEventHandler = (event: IpcMessageEvent): void => {
// TODO - localization
const { channel } = event;
switch (channel) {
case 'enable-accessory':
this.enableAccessory(event.args[0], event.args[1]);
break;
case 'set-accessory-state':
this.setAccessoryState(event.args[0], event.args[1]);
break;
case 'set-inspector-title':
this.setState({ titleOverride: event.args[0] });
this.setInspectorTitle(event.args[0]);
break;
case 'logger.log':
case 'logger.error': {
const logLevel = channel === 'logger.log' ? LogLevel.Info : LogLevel.Error;
const { documentId } = this.props.document;
const inspectorName = this._state.titleOverride || this.state.inspector.name || 'inspector';
const text = `[${inspectorName}] ${event.args[0]}`;
LogService.logToDocument(documentId, logEntry(textItem(logLevel, text)));
break;
}
case 'logger.luis-editor-deep-link': {
const { documentId } = this.props.document;
const inspectorName = this._state.titleOverride || this.state.inspector.name || 'inspector';
const text = `[${inspectorName}] ${event.args[0]}`;
LogService.logToDocument(documentId, logEntry(luisEditorDeepLinkItem(text)));
break;
}
// record telemetry from extension
case 'track-event': {
const eventName = event.args[0];
const eventProperties = event.args[1] || {};
this.props.trackEvent(eventName, eventProperties);
break;
}
default:
// eslint-disable-next-line no-console
console.warn('Unexpected message from inspector', event.channel, ...event.args);
}
};
private sendInitializationStackToInspector(): void {
this.botUpdated(this.state.activeBot);
this.inspect(this.state.inspectObj);
this.sendToInspector('theme', this.state.themeInfo);
}
private inspect(obj: InspectObject) {
if (this.canInspect(obj)) {
// showInInspector is for internal bookkeeping and shouldn't make it to the view
// remove before rendering
delete obj.showInInspector;
this.sendToInspector('inspect', obj);
}
}
private botUpdated(bot: IBotConfiguration) {
this.sendToInspector('bot-updated', bot);
}
private sendToInspector(channel: string, ...args: any[]) {
const { inspectorSrc } = this.state;
const inspector = this.webViewByLocation[encodeURI(inspectorSrc)];
if (!inspector || !this.domReadyByLocation[encodeURI(inspectorSrc)]) {
return;
}
try {
inspector.send(channel, ...args);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
private onInspectorDrag = (event: DragEvent): void => {
// prevent drag & drops inside of the inspector panel
event.stopPropagation();
};
}