-
Notifications
You must be signed in to change notification settings - Fork 30
/
ts-embed.ts
1306 lines (1172 loc) · 43.5 KB
/
ts-embed.ts
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2022
*
* Base classes
*
* @summary Base classes
* @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
*/
import isEqual from 'lodash/isEqual';
import pkgInfo from '../../package.json';
import { AuthFailureType } from '../auth';
import { getAuthenticationToken } from '../authToken';
import {
DEFAULT_EMBED_HEIGHT,
DEFAULT_EMBED_WIDTH,
URL_MAX_LENGTH,
getThoughtSpotHost,
getV2BasePath,
} from '../config';
import { MIXPANEL_EVENT, uploadMixpanelEvent } from '../mixpanel-service';
import {
Action,
AuthType,
ContextMenuTriggerOptions,
DOMSelector,
EmbedConfig,
EmbedEvent,
HostEvent,
MessageCallback,
MessageCallbackObj,
MessageOptions,
Param,
ViewConfig,
} from '../types';
import {
embedEventStatus,
getCssDimension,
getCustomisations,
getDOMNode,
getEncodedQueryParamsString,
getFilterQuery,
getOffsetTop,
getQueryParamString,
getRuntimeFilters,
getRuntimeParameters,
isUndefined,
removeStyleProperties,
setAttributes,
setStyleProperties,
} from '../utils';
import { AnswerService } from '../utils/graphql/answerService/answerService';
import { logger } from '../utils/logger';
import { processAuthFailure, processEventData } from '../utils/processData';
import { processTrigger } from '../utils/processTrigger';
import {
getAuthPromise, handleAuth, notifyAuthFailure, renderInQueue,
} from './base';
import { getEmbedConfig } from './embedConfig';
const { version } = pkgInfo;
/**
* Global prefix for all Thoughtspot postHash Params.
*/
export const THOUGHTSPOT_PARAM_PREFIX = 'ts-';
const TS_EMBED_ID = '_thoughtspot-embed';
/**
* The event id map from v2 event names to v1 event id
* v1 events are the classic embed events implemented in Blink v1
* We cannot rename v1 event types to maintain backward compatibility
*
* @internal
*/
const V1EventMap = {};
/**
* Base class for embedding v2 experience
* Note: the v2 version of ThoughtSpot Blink is built on the new stack:
* React+GraphQL
*/
export class TsEmbed {
/**
* The DOM node which was inserted by the SDK to either
* render the iframe or display an error message.
* This is useful for removing the DOM node when the
* embed instance is destroyed.
*/
protected insertedDomEl: Node;
/**
* The DOM node where the ThoughtSpot app is to be embedded.
*/
protected el: Element;
/**
* The key to store the embed instance in the DOM node
*/
protected embedNodeKey = '__tsEmbed';
protected isAppInitialized = false;
/**
* A reference to the iframe within which the ThoughtSpot app
* will be rendered.
*/
protected iFrame: HTMLIFrameElement;
protected viewConfig: ViewConfig;
protected embedConfig: EmbedConfig;
/**
* The ThoughtSpot hostname or IP address
*/
protected thoughtSpotHost: string;
/*
* This is the base to access ThoughtSpot V2.
*/
protected thoughtSpotV2Base: string;
/**
* A map of event handlers for particular message types triggered
* by the embedded app; multiple event handlers can be registered
* against a particular message type.
*/
private eventHandlerMap: Map<string, MessageCallbackObj[]>;
/**
* A flag that is set to true post render.
*/
protected isRendered: boolean;
/**
* A flag to mark if an error has occurred.
*/
private isError: boolean;
/**
* A flag that is set to true post preRender.
*/
private isPreRendered: boolean;
/**
* Should we encode URL Query Params using base64 encoding which thoughtspot
* will generate for embedding. This provides additional security to
* thoughtspot clusters against Cross site scripting attacks.
*
* @default false
*/
private shouldEncodeUrlQueryParams = false;
private defaultHiddenActions = [Action.ReportError];
private resizeObserver: ResizeObserver;
constructor(domSelector: DOMSelector, viewConfig?: ViewConfig) {
this.el = getDOMNode(domSelector);
// TODO: handle error
this.embedConfig = getEmbedConfig();
if (!this.embedConfig.authTriggerContainer && !this.embedConfig.useEventForSAMLPopup) {
this.embedConfig.authTriggerContainer = domSelector;
}
this.thoughtSpotHost = getThoughtSpotHost(this.embedConfig);
this.thoughtSpotV2Base = getV2BasePath(this.embedConfig);
this.eventHandlerMap = new Map();
this.isError = false;
this.viewConfig = { excludeRuntimeFiltersfromURL: false, ...viewConfig };
this.shouldEncodeUrlQueryParams = this.embedConfig.shouldEncodeUrlQueryParams;
this.registerAppInit();
uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_EMBED_CREATE, {
...viewConfig,
});
}
/**
* Throws error encountered during initialization.
*/
private throwInitError() {
this.handleError('You need to init the ThoughtSpot SDK module first');
}
/**
* Handles errors within the SDK
*
* @param error The error message or object
*/
protected handleError(error: string | Record<string, unknown>) {
this.isError = true;
this.executeCallbacks(EmbedEvent.Error, {
error,
});
// Log error
logger.error(error);
}
/**
* Extracts the type field from the event payload
*
* @param event The window message event
*/
private getEventType(event: MessageEvent) {
// eslint-disable-next-line no-underscore-dangle
return event.data?.type || event.data?.__type;
}
/**
* Extracts the port field from the event payload
*
* @param event The window message event
* @returns
*/
private getEventPort(event: MessageEvent) {
if (event.ports.length && event.ports[0]) {
return event.ports[0];
}
return null;
}
/**
* fix for ts7.sep.cl
* will be removed for ts7.oct.cl
*
* @param event
* @param eventType
* @hidden
*/
private formatEventData(event: MessageEvent, eventType: string) {
const eventData = {
...event.data,
type: eventType,
};
if (!eventData.data) {
eventData.data = event.data.payload;
}
return eventData;
}
private subscribedListeners = {};
/**
* Adds a global event listener to window for "message" events.
* ThoughtSpot detects if a particular event is targeted to this
* embed instance through an identifier contained in the payload,
* and executes the registered callbacks accordingly.
*/
private subscribeToEvents() {
this.unsubscribeToEvents();
const messageEventListener = (event: MessageEvent<any>) => {
const eventType = this.getEventType(event);
const eventPort = this.getEventPort(event);
const eventData = this.formatEventData(event, eventType);
if (event.source === this.iFrame.contentWindow) {
this.executeCallbacks(
eventType,
processEventData(
eventType,
eventData,
this.thoughtSpotHost,
this.isPreRendered ? this.preRenderWrapper : this.el,
),
eventPort,
);
}
};
window.addEventListener('message', messageEventListener);
const onlineEventListener = (e: Event) => {
this.trigger(HostEvent.Reload);
};
window.addEventListener('online', onlineEventListener);
const offlineEventListener = (e: Event) => {
const offlineWarning = 'Network not Detected. Embed is offline. Please reconnect and refresh';
this.executeCallbacks(EmbedEvent.Error, {
offlineWarning,
});
logger.warn(offlineWarning);
};
window.addEventListener('offline', offlineEventListener);
this.subscribedListeners = {
message: messageEventListener,
online: onlineEventListener,
offline: offlineEventListener,
};
}
private unsubscribeToEvents() {
Object.keys(this.subscribedListeners).forEach((key) => {
window.removeEventListener(key, this.subscribedListeners[key]);
});
}
/**
* Send Custom style as part of payload of APP_INIT
*
* @param _
* @param responder
*/
private appInitCb = async (_: any, responder: any) => {
let authToken = '';
if (this.embedConfig.authType === AuthType.TrustedAuthTokenCookieless) {
try {
authToken = await getAuthenticationToken(this.embedConfig);
} catch (e) {
processAuthFailure(e, this.isPreRendered ? this.preRenderWrapper : this.el);
return;
}
}
this.isAppInitialized = true;
responder({
type: EmbedEvent.APP_INIT,
data: {
customisations: getCustomisations(this.embedConfig, this.viewConfig),
authToken,
runtimeFilterParams: this.viewConfig.excludeRuntimeFiltersfromURL
? getRuntimeFilters(this.viewConfig.runtimeFilters)
: null,
hiddenHomepageModules: this.viewConfig.hiddenHomepageModules || [],
reorderedHomepageModules: this.viewConfig.reorderedHomepageModules || [],
hostConfig: this.embedConfig.hostConfig,
hiddenHomeLeftNavItems: this.viewConfig?.hiddenHomeLeftNavItems
? this.viewConfig?.hiddenHomeLeftNavItems
: [],
},
});
};
/**
* Sends updated auth token to the iFrame to avoid user logout
*
* @param _
* @param responder
*/
private updateAuthToken = async (_: any, responder: any) => {
const { autoLogin = false, authType } = this.embedConfig; // Set autoLogin default to false
if (authType === AuthType.TrustedAuthTokenCookieless) {
let authToken = '';
try {
authToken = await getAuthenticationToken(this.embedConfig);
responder({
type: EmbedEvent.AuthExpire,
data: { authToken },
});
} catch (e) {
processAuthFailure(e, this.isPreRendered ? this.preRenderWrapper : this.el);
}
} else if (autoLogin) {
handleAuth();
}
notifyAuthFailure(AuthFailureType.EXPIRY);
};
/**
* Register APP_INIT event and sendback init payload
*/
private registerAppInit = () => {
this.on(EmbedEvent.APP_INIT, this.appInitCb, { start: false }, true);
this.on(EmbedEvent.AuthExpire, this.updateAuthToken, { start: false }, true);
};
/**
* Constructs the base URL string to load the ThoughtSpot app.
*
* @param query
*/
protected getEmbedBasePath(query: string): string {
let queryString = query;
if (this.shouldEncodeUrlQueryParams) {
queryString = `?base64UrlEncodedFlags=${getEncodedQueryParamsString(
queryString.substr(1),
)}`;
}
const basePath = [this.thoughtSpotHost, this.thoughtSpotV2Base, queryString]
.filter((x) => x.length > 0)
.join('/');
return `${basePath}#`;
}
/**
* Common query params set for all the embed modes.
*
* @param queryParams
* @returns queryParams
*/
protected getBaseQueryParams(queryParams = {}) {
let hostAppUrl = window?.location?.host || '';
// The below check is needed because TS Cloud firewall, blocks
// localhost/127.0.0.1 in any url param.
if (hostAppUrl.includes('localhost') || hostAppUrl.includes('127.0.0.1')) {
hostAppUrl = 'local-host';
}
queryParams[Param.HostAppUrl] = encodeURIComponent(hostAppUrl);
queryParams[Param.ViewPortHeight] = window.innerHeight;
queryParams[Param.ViewPortWidth] = window.innerWidth;
queryParams[Param.Version] = version;
queryParams[Param.AuthType] = this.embedConfig.authType;
queryParams[Param.blockNonEmbedFullAppAccess] = this.embedConfig.blockNonEmbedFullAppAccess
?? true;
if (this.embedConfig.disableLoginRedirect === true || this.embedConfig.autoLogin === true) {
queryParams[Param.DisableLoginRedirect] = true;
}
if (this.embedConfig.authType === AuthType.EmbeddedSSO) {
queryParams[Param.ForceSAMLAutoRedirect] = true;
}
if (this.embedConfig.authType === AuthType.TrustedAuthTokenCookieless) {
queryParams[Param.cookieless] = true;
}
if (this.embedConfig.pendoTrackingKey) {
queryParams[Param.PendoTrackingKey] = this.embedConfig.pendoTrackingKey;
}
if (this.embedConfig.numberFormatLocale) {
queryParams[Param.NumberFormatLocale] = this.embedConfig.numberFormatLocale;
}
if (this.embedConfig.dateFormatLocale) {
queryParams[Param.DateFormatLocale] = this.embedConfig.dateFormatLocale;
}
if (this.embedConfig.currencyFormat) {
queryParams[Param.CurrencyFormat] = this.embedConfig.currencyFormat;
}
const {
disabledActions,
disabledActionReason,
hiddenActions,
visibleActions,
hiddenTabs,
visibleTabs,
showAlerts,
additionalFlags,
locale,
customizations,
contextMenuTrigger,
linkOverride,
insertInToSlide,
} = this.viewConfig;
if (Array.isArray(visibleActions) && Array.isArray(hiddenActions)) {
this.handleError('You cannot have both hidden actions and visible actions');
return queryParams;
}
if (Array.isArray(visibleTabs) && Array.isArray(hiddenTabs)) {
this.handleError('You cannot have both hidden Tabs and visible Tabs');
return queryParams;
}
// TODO remove embedConfig.customCssUrl
const cssUrlParam = customizations?.style?.customCSSUrl || this.embedConfig.customCssUrl;
if (cssUrlParam) {
queryParams[Param.CustomCSSUrl] = cssUrlParam;
}
if (disabledActions?.length) {
queryParams[Param.DisableActions] = disabledActions;
}
if (disabledActionReason) {
queryParams[Param.DisableActionReason] = disabledActionReason;
}
queryParams[Param.HideActions] = [...this.defaultHiddenActions, ...(hiddenActions ?? [])];
if (Array.isArray(visibleActions)) {
queryParams[Param.VisibleActions] = visibleActions;
}
if (Array.isArray(hiddenTabs)) {
queryParams[Param.HiddenTabs] = hiddenTabs;
}
if (Array.isArray(visibleTabs)) {
queryParams[Param.VisibleTabs] = visibleTabs;
}
/**
* Default behavior for context menu will be left-click
* from version 9.2.0.cl the user have an option to override context
* menu click
*/
if (contextMenuTrigger === ContextMenuTriggerOptions.LEFT_CLICK) {
queryParams[Param.ContextMenuTrigger] = true;
} else if (contextMenuTrigger === ContextMenuTriggerOptions.RIGHT_CLICK) {
queryParams[Param.ContextMenuTrigger] = false;
}
const spriteUrl = customizations?.iconSpriteUrl
|| this.embedConfig.customizations?.iconSpriteUrl;
if (spriteUrl) {
queryParams[Param.IconSpriteUrl] = spriteUrl.replace('https://', '');
}
if (showAlerts !== undefined) {
queryParams[Param.ShowAlerts] = showAlerts;
}
if (locale !== undefined) {
queryParams[Param.Locale] = locale;
}
if (additionalFlags && additionalFlags.constructor.name === 'Object') {
Object.assign(queryParams, additionalFlags);
}
if (linkOverride) {
queryParams[Param.LinkOverride] = linkOverride;
}
if (insertInToSlide) {
queryParams[Param.ShowInsertToSlide] = insertInToSlide;
}
queryParams[Param.OverrideNativeConsole] = true;
queryParams[Param.ClientLogLevel] = this.embedConfig.logLevel;
return queryParams;
}
/**
* Constructs the base URL string to load v1 of the ThoughtSpot app.
* This is used for embedding Liveboards, visualizations, and full application.
*
* @param queryString The query string to append to the URL.
* @param isAppEmbed A Boolean parameter to specify if you are embedding
* the full application.
*/
protected getV1EmbedBasePath(queryString: string): string {
const queryParams = this.shouldEncodeUrlQueryParams
? `?base64UrlEncodedFlags=${getEncodedQueryParamsString(queryString)}`
: `?${queryString}`;
const host = this.thoughtSpotHost;
const path = `${host}/${queryParams}#`;
return path;
}
protected getEmbedParams() {
const queryParams = this.getBaseQueryParams();
return getQueryParamString(queryParams);
}
protected getRootIframeSrc() {
const query = this.getEmbedParams();
return this.getEmbedBasePath(query);
}
protected createIframeEl(frameSrc: string): HTMLIFrameElement {
const iFrame = document.createElement('iframe');
iFrame.src = frameSrc;
iFrame.id = TS_EMBED_ID;
iFrame.setAttribute('data-ts-iframe', 'true');
// according to screenfull.js documentation
// allowFullscreen, webkitallowfullscreen and mozallowfullscreen must be
// true
iFrame.allowFullscreen = true;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
iFrame.webkitallowfullscreen = true;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
iFrame.mozallowfullscreen = true;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
iFrame.allow = 'clipboard-read; clipboard-write';
const {
height: frameHeight,
width: frameWidth, ...restParams
} = this.viewConfig.frameParams || {};
const width = getCssDimension(frameWidth || DEFAULT_EMBED_WIDTH);
const height = getCssDimension(frameHeight || DEFAULT_EMBED_HEIGHT);
setAttributes(iFrame, restParams);
iFrame.style.width = `${width}`;
iFrame.style.height = `${height}`;
iFrame.style.border = '0';
iFrame.name = 'ThoughtSpot Embedded Analytics';
return iFrame;
}
protected handleInsertionIntoDOM(child: string | Node): void {
if (this.isPreRendered) {
this.insertIntoDOMForPreRender(child);
} else {
this.insertIntoDOM(child);
}
if (this.insertedDomEl instanceof Node) {
this.insertedDomEl[this.embedNodeKey] = this;
}
}
/**
* Renders the embedded ThoughtSpot app in an iframe and sets up
* event listeners.
*
* @param url - The URL of the embedded ThoughtSpot app.
*/
protected async renderIFrame(url: string): Promise<any> {
if (this.isError) {
return null;
}
if (!this.thoughtSpotHost) {
this.throwInitError();
}
if (url.length > URL_MAX_LENGTH) {
// warn: The URL is too long
}
return renderInQueue((nextInQueue) => {
const initTimestamp = Date.now();
this.executeCallbacks(EmbedEvent.Init, {
data: {
timestamp: initTimestamp,
},
type: EmbedEvent.Init,
});
uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_RENDER_START);
return getAuthPromise()
?.then((isLoggedIn: boolean) => {
if (!isLoggedIn) {
this.handleInsertionIntoDOM(this.embedConfig.loginFailedMessage);
return;
}
this.iFrame = this.iFrame || this.createIframeEl(url);
this.iFrame.addEventListener('load', () => {
nextInQueue();
const loadTimestamp = Date.now();
this.executeCallbacks(EmbedEvent.Load, {
data: {
timestamp: loadTimestamp,
},
type: EmbedEvent.Load,
});
uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_RENDER_COMPLETE, {
elWidth: this.iFrame.clientWidth,
elHeight: this.iFrame.clientHeight,
timeTookToLoad: loadTimestamp - initTimestamp,
});
});
this.iFrame.addEventListener('error', () => {
nextInQueue();
});
this.handleInsertionIntoDOM(this.iFrame);
const prefetchIframe = document.querySelectorAll('.prefetchIframe');
if (prefetchIframe.length) {
prefetchIframe.forEach((el) => {
el.remove();
});
}
this.subscribeToEvents();
})
.catch((error) => {
nextInQueue();
uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_RENDER_FAILED, {
error: JSON.stringify(error),
});
this.handleInsertionIntoDOM(this.embedConfig.loginFailedMessage);
this.handleError(error);
});
});
}
protected createPreRenderWrapper(): HTMLDivElement {
const preRenderIds = this.getPreRenderIds();
document.getElementById(preRenderIds.wrapper)?.remove();
const preRenderWrapper = document.createElement('div');
preRenderWrapper.id = preRenderIds.wrapper;
const initialPreRenderWrapperStyle = {
position: 'absolute',
width: '100vw',
height: '100vh',
};
setStyleProperties(preRenderWrapper, initialPreRenderWrapperStyle);
return preRenderWrapper;
}
protected preRenderWrapper: HTMLElement;
protected preRenderChild: HTMLElement;
protected connectPreRendered(): boolean {
const preRenderIds = this.getPreRenderIds();
this.preRenderWrapper = this.preRenderWrapper
|| document.getElementById(preRenderIds.wrapper);
this.preRenderChild = this.preRenderChild || document.getElementById(preRenderIds.child);
if (this.preRenderWrapper && this.preRenderChild) {
this.isPreRendered = true;
if (this.preRenderChild instanceof HTMLIFrameElement) {
this.iFrame = this.preRenderChild;
}
this.insertedDomEl = this.preRenderWrapper;
this.isRendered = true;
}
return this.isPreRenderAvailable();
}
protected isPreRenderAvailable(): boolean {
return (
this.isRendered
&& this.isPreRendered
&& Boolean(this.preRenderWrapper && this.preRenderChild)
);
}
protected createPreRenderChild(child: string | Node): HTMLElement {
const preRenderIds = this.getPreRenderIds();
document.getElementById(preRenderIds.child)?.remove();
if (child instanceof HTMLElement) {
child.id = preRenderIds.child;
return child;
}
const divChildNode = document.createElement('div');
setStyleProperties(divChildNode, { width: '100%', height: '100%' });
divChildNode.id = preRenderIds.child;
if (typeof child === 'string') {
divChildNode.innerHTML = child;
} else {
divChildNode.appendChild(child);
}
return divChildNode;
}
protected insertIntoDOMForPreRender(child: string | Node): void {
const preRenderChild = this.createPreRenderChild(child);
const preRenderWrapper = this.createPreRenderWrapper();
preRenderWrapper.appendChild(preRenderChild);
this.preRenderChild = preRenderChild;
this.preRenderWrapper = preRenderWrapper;
if (preRenderChild instanceof HTMLIFrameElement) {
this.iFrame = preRenderChild;
}
this.insertedDomEl = preRenderWrapper;
if (this.showPreRenderByDefault) {
this.showPreRender();
} else {
this.hidePreRender();
}
document.body.appendChild(preRenderWrapper);
}
private showPreRenderByDefault = false;
protected insertIntoDOM(child: string | Node): void {
if (this.viewConfig.insertAsSibling) {
if (typeof child === 'string') {
const div = document.createElement('div');
div.innerHTML = child;
div.id = TS_EMBED_ID;
// eslint-disable-next-line no-param-reassign
child = div;
}
if (this.el.nextElementSibling?.id === TS_EMBED_ID) {
this.el.nextElementSibling.remove();
}
this.el.parentElement.insertBefore(child, this.el.nextSibling);
this.insertedDomEl = child;
} else if (typeof child === 'string') {
this.el.innerHTML = child;
this.insertedDomEl = this.el.children[0];
} else {
this.el.innerHTML = '';
this.el.appendChild(child);
this.insertedDomEl = child;
}
}
/**
* Sets the height of the iframe
*
* @param height The height in pixels
*/
protected setIFrameHeight(height: number | string): void {
this.iFrame.style.height = getCssDimension(height);
}
/**
* Executes all registered event handlers for a particular event type
*
* @param eventType The event type
* @param data The payload invoked with the event handler
* @param eventPort The event Port for a specific MessageChannel
*/
protected executeCallbacks(
eventType: EmbedEvent,
data: any,
eventPort?: MessagePort | void,
): void {
const eventHandlers = this.eventHandlerMap.get(eventType) || [];
const allHandlers = this.eventHandlerMap.get(EmbedEvent.ALL) || [];
const callbacks = [...eventHandlers, ...allHandlers];
const dataStatus = data?.status || embedEventStatus.END;
callbacks.forEach((callbackObj) => {
if (
// When start status is true it trigger only start releated
// payload
(callbackObj.options.start && dataStatus === embedEventStatus.START)
// When start status is false it trigger only end releated
// payload
|| (!callbackObj.options.start && dataStatus === embedEventStatus.END)
) {
callbackObj.callback(data, (payload) => {
this.triggerEventOnPort(eventPort, payload);
});
}
});
}
/**
* Returns the ThoughtSpot hostname or IP address.
*/
protected getThoughtSpotHost(): string {
return this.thoughtSpotHost;
}
/**
* Gets the v1 event type (if applicable) for the EmbedEvent type
*
* @param eventType The v2 event type
* @returns The corresponding v1 event type if one exists
* or else the v2 event type itself
*/
protected getCompatibleEventType(eventType: EmbedEvent): EmbedEvent {
return V1EventMap[eventType] || eventType;
}
/**
* Calculates the iframe center for the current visible viewPort
* of iframe using Scroll position of Host App, offsetTop for iframe
* in Host app. ViewPort height of the tab.
*
* @returns iframe Center in visible viewport,
* Iframe height,
* View port height.
*/
protected getIframeCenter() {
const offsetTopClient = getOffsetTop(this.iFrame);
const scrollTopClient = window.scrollY;
const viewPortHeight = window.innerHeight;
const iframeHeight = this.iFrame.offsetHeight;
const iframeScrolled = scrollTopClient - offsetTopClient;
let iframeVisibleViewPort;
let iframeOffset;
if (iframeScrolled < 0) {
iframeVisibleViewPort = viewPortHeight - (offsetTopClient - scrollTopClient);
iframeVisibleViewPort = Math.min(iframeHeight, iframeVisibleViewPort);
iframeOffset = 0;
} else {
iframeVisibleViewPort = Math.min(iframeHeight - iframeScrolled, viewPortHeight);
iframeOffset = iframeScrolled;
}
const iframeCenter = iframeOffset + iframeVisibleViewPort / 2;
return {
iframeCenter,
iframeScrolled,
iframeHeight,
viewPortHeight,
iframeVisibleViewPort,
};
}
/**
* Registers an event listener to trigger an alert when the ThoughtSpot app
* sends an event of a particular message type to the host application.
*
* @param messageType The message type
* @param callback A callback as a function
* @param options The message options
* @param isSelf
* @param isRegisteredBySDK
* @example
* ```js
* tsEmbed.on(EmbedEvent.Error, (data) => {
* console.error(data);
* });
* ```
* @example
* ```js
* tsEmbed.on(EmbedEvent.Save, (data) => {
* console.log("Answer save clicked", data);
* }, {
* start: true // This will trigger the callback on start of save
* });
* ```
*/
public on(
messageType: EmbedEvent,
callback: MessageCallback,
options: MessageOptions = { start: false },
isRegisteredBySDK = false,
): typeof TsEmbed.prototype {
uploadMixpanelEvent(`${MIXPANEL_EVENT.VISUAL_SDK_ON}-${messageType}`, {
isRegisteredBySDK,
});
if (this.isRendered) {
this.handleError('Please register event handlers before calling render');
}
const callbacks = this.eventHandlerMap.get(messageType) || [];
callbacks.push({ options, callback });
this.eventHandlerMap.set(messageType, callbacks);
return this;
}
/**
* Removes an event listener for a particular event type.
*
* @param messageType The message type
* @param callback The callback to remove
* @example
* ```js
* const errorHandler = (data) => { console.error(data); };
* tsEmbed.on(EmbedEvent.Error, errorHandler);
* tsEmbed.off(EmbedEvent.Error, errorHandler);
* ```
*/
public off(messageType: EmbedEvent, callback: MessageCallback): typeof TsEmbed.prototype {
const callbacks = this.eventHandlerMap.get(messageType) || [];
const index = callbacks.findIndex((cb) => cb.callback === callback);
if (index > -1) {
callbacks.splice(index, 1);
}
return this;
}
/**
* Triggers an event on specific Port registered against
* for the EmbedEvent
*
* @param eventType The message type
* @param data The payload to send
* @param eventPort
* @param payload
*/
private triggerEventOnPort(eventPort: MessagePort | void, payload: any) {
if (eventPort) {
try {
eventPort.postMessage({
type: payload.type,
data: payload.data,
});
} catch (e) {
eventPort.postMessage({ error: e });
logger.log(e);
}
} else {
logger.log('Event Port is not defined');
}
}
/**
* Triggers an event to the embedded app
*
* @param messageType The event type
* @param data The payload to send with the message
*/
public trigger(messageType: HostEvent, data: any = {}): Promise<any> {
uploadMixpanelEvent(`${MIXPANEL_EVENT.VISUAL_SDK_TRIGGER}-${messageType}`);
if (!this.isRendered) {
this.handleError('Please call render before triggering events');
return null;
}
if (!messageType) {
this.handleError('Host event type is undefined');
return null;
}
return processTrigger(this.iFrame, messageType, this.thoughtSpotHost, data);
}
/**
* Marks the ThoughtSpot object to have been rendered
* Needs to be overridden by subclasses to do the actual
* rendering of the iframe.
*
* @param args
*/
public async render(): Promise<TsEmbed> {
this.isRendered = true;
return this;
}
public getIframeSrc(): string {
return '';