• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

thoughtspot / visual-embed-sdk / #2148

16 Jul 2025 06:25AM UTC coverage: 93.602% (+0.1%) from 93.486%
#2148

push

web-flow
SCAL-259434 Added list page sdk flag (#264)

1146 of 1309 branches covered (87.55%)

Branch coverage included in aggregate %.

5 of 6 new or added lines in 3 files covered. (83.33%)

20 existing lines in 3 files now uncovered.

2775 of 2880 relevant lines covered (96.35%)

76.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.39
/src/utils.ts
1
/**
2
 * Copyright (c) 2023
3
 *
4
 * Common utility functions for ThoughtSpot Visual Embed SDK
5
 * @summary Utils
6
 * @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
7
 */
8

9
import merge from 'ts-deepmerge';
35✔
10
import {
11
    EmbedConfig,
12
    QueryParams,
13
    RuntimeFilter,
14
    CustomisationsInterface,
15
    DOMSelector,
16
    RuntimeParameter,
17
    AllEmbedViewConfig,
18
} from './types';
19
import { logger } from './utils/logger';
35✔
20

21
/**
22
 * Construct a runtime filters query string from the given filters.
23
 * Refer to the following docs for more details on runtime filter syntax:
24
 * https://cloud-docs.thoughtspot.com/admin/ts-cloud/apply-runtime-filter.html
25
 * https://cloud-docs.thoughtspot.com/admin/ts-cloud/runtime-filter-operators.html
26
 * @param runtimeFilters
27
 */
28
export const getFilterQuery = (runtimeFilters: RuntimeFilter[]): string | null => {
35✔
29
    if (runtimeFilters && runtimeFilters.length) {
325✔
30
        const filters = runtimeFilters.map((filter, valueIndex) => {
18✔
31
            const index = valueIndex + 1;
20✔
32
            const filterExpr = [];
20✔
33
            filterExpr.push(`col${index}=${encodeURIComponent(filter.columnName)}`);
20✔
34
            filterExpr.push(`op${index}=${filter.operator}`);
20✔
35
            filterExpr.push(
20✔
36
                filter.values.map((value) => {
37
                    const encodedValue = typeof value === 'bigint' ? value.toString() : value;
21!
38
                    return `val${index}=${encodeURIComponent(String(encodedValue))}`;
21✔
39
                }).join('&'),
40
            );
41

42
            return filterExpr.join('&');
20✔
43
        });
44

45
        return `${filters.join('&')}`;
18✔
46
    }
47

48
    return null;
307✔
49
};
50

51
/**
52
 * Construct a runtime parameter override query string from the given option.
53
 * @param runtimeParameters
54
 */
55
export const getRuntimeParameters = (runtimeParameters: RuntimeParameter[]): string => {
35✔
56
    if (runtimeParameters && runtimeParameters.length) {
324✔
57
        const params = runtimeParameters.map((param, valueIndex) => {
7✔
58
            const index = valueIndex + 1;
9✔
59
            const filterExpr = [];
9✔
60
            filterExpr.push(`param${index}=${encodeURIComponent(param.name)}`);
9✔
61
            filterExpr.push(`paramVal${index}=${encodeURIComponent(param.value)}`);
9✔
62

63
            return filterExpr.join('&');
9✔
64
        });
65

66
        return `${params.join('&')}`;
7✔
67
    }
68

69
    return null;
317✔
70
};
71

72
/**
73
 * Convert a value to a string representation to be sent as a query
74
 * parameter to the ThoughtSpot app.
75
 * @param value Any parameter value
76
 */
77
const serializeParam = (value: any) => {
35✔
78
    // do not serialize primitive types
79
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
8,127✔
80
        return value;
7,782✔
81
    }
82

83
    return JSON.stringify(value);
345✔
84
};
85

86
/**
87
 * Convert a value to a string:
88
 * in case of an array, we convert it to CSV.
89
 * in case of any other type, we directly return the value.
90
 * @param value
91
 */
92
const paramToString = (value: any) => (Array.isArray(value) ? value.join(',') : value);
35!
93

94
/**
95
 * Return a query param string composed from the given params object
96
 * @param queryParams
97
 * @param shouldSerializeParamValues
98
 */
99
export const getQueryParamString = (
35✔
100
    queryParams: QueryParams,
101
    shouldSerializeParamValues = false,
9✔
102
): string => {
103
    const qp: string[] = [];
347✔
104
    const params = Object.keys(queryParams);
347✔
105
    params.forEach((key) => {
347✔
106
        const val = queryParams[key];
8,490✔
107
        if (val !== undefined) {
8,490✔
108
            const serializedValue = shouldSerializeParamValues
8,144✔
109
                ? serializeParam(val)
110
                : paramToString(val);
111
            qp.push(`${key}=${serializedValue}`);
8,144✔
112
        }
113
    });
114

115
    if (qp.length) {
347✔
116
        return qp.join('&');
346✔
117
    }
118

119
    return null;
1✔
120
};
121

122
/**
123
 * Get a string representation of a dimension value in CSS
124
 * If numeric, it is considered in pixels.
125
 * @param value
126
 */
127
export const getCssDimension = (value: number | string): string => {
35✔
128
    if (typeof value === 'number') {
642✔
129
        return `${value}px`;
443✔
130
    }
131

132
    return value;
199✔
133
};
134

135
export const getSSOMarker = (markerId: string) => {
35✔
136
    const encStringToAppend = encodeURIComponent(markerId);
18✔
137
    return `tsSSOMarker=${encStringToAppend}`;
18✔
138
};
139

140
/**
141
 * Append a string to a URL's hash fragment
142
 * @param url A URL
143
 * @param stringToAppend The string to append to the URL hash
144
 */
145
export const appendToUrlHash = (url: string, stringToAppend: string) => {
35✔
146
    let outputUrl = url;
12✔
147
    const encStringToAppend = encodeURIComponent(stringToAppend);
12✔
148

149
    const marker = `tsSSOMarker=${encStringToAppend}`;
12✔
150

151
    let splitAdder = '';
12✔
152

153
    if (url.indexOf('#') >= 0) {
12✔
154
        // If second half of hash contains a '?' already add a '&' instead of
155
        // '?' which appends to query params.
156
        splitAdder = url.split('#')[1].indexOf('?') >= 0 ? '&' : '?';
8✔
157
    } else {
158
        splitAdder = '#?';
4✔
159
    }
160
    outputUrl = `${outputUrl}${splitAdder}${marker}`;
12✔
161

162
    return outputUrl;
12✔
163
};
164

165
/**
166
 *
167
 * @param url
168
 * @param stringToAppend
169
 * @param path
170
 */
171
export function getRedirectUrl(url: string, stringToAppend: string, path = '') {
35✔
172
    const targetUrl = path ? new URL(path, window.location.origin).href : url;
10✔
173
    return appendToUrlHash(targetUrl, stringToAppend);
10✔
174
}
175

176
export const getEncodedQueryParamsString = (queryString: string) => {
35✔
177
    if (!queryString) {
4✔
178
        return queryString;
1✔
179
    }
180
    return btoa(queryString).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
3✔
181
};
182

183
export const getOffsetTop = (element: any) => {
35✔
184
    const rect = element.getBoundingClientRect();
4✔
185
    return rect.top + window.scrollY;
4✔
186
};
187

188
export const embedEventStatus = {
35✔
189
    START: 'start',
190
    END: 'end',
191
};
192

193
export const setAttributes = (
35✔
194
    element: HTMLElement,
195
    attributes: { [key: string]: string | number | boolean },
196
): void => {
197
    Object.keys(attributes).forEach((key) => {
318✔
198
        element.setAttribute(key, attributes[key].toString());
21✔
199
    });
200
};
201

202
const isCloudRelease = (version: string) => version.endsWith('.cl');
35✔
203

204
/* For Search Embed: ReleaseVersionInBeta */
205
export const checkReleaseVersionInBeta = (
35✔
206
    releaseVersion: string,
207
    suppressBetaWarning: boolean,
208
): boolean => {
209
    if (releaseVersion !== '' && !isCloudRelease(releaseVersion)) {
90✔
210
        const splittedReleaseVersion = releaseVersion.split('.');
34✔
211
        const majorVersion = Number(splittedReleaseVersion[0]);
34✔
212
        const isBetaVersion = majorVersion < 8;
34✔
213
        return !suppressBetaWarning && isBetaVersion;
34✔
214
    }
215
    return false;
56✔
216
};
217

218
export const getCustomisations = (
35✔
219
    embedConfig: EmbedConfig,
220
    viewConfig: AllEmbedViewConfig,
221
): CustomisationsInterface => {
222
    const customizationsFromViewConfig = viewConfig.customizations;
17✔
223
    const customizationsFromEmbedConfig = embedConfig.customizations
17✔
224
        || ((embedConfig as any).customisations as CustomisationsInterface);
225

226
    const customizations: CustomisationsInterface = {
17✔
227
        style: {
228
            ...customizationsFromEmbedConfig?.style,
51✔
229
            ...customizationsFromViewConfig?.style,
51✔
230
            customCSS: {
231
                ...customizationsFromEmbedConfig?.style?.customCSS,
102✔
232
                ...customizationsFromViewConfig?.style?.customCSS,
102✔
233
            },
234
            customCSSUrl:
235
                customizationsFromViewConfig?.style?.customCSSUrl
136✔
236
                || customizationsFromEmbedConfig?.style?.customCSSUrl,
102✔
237
        },
238
        content: {
239
            ...customizationsFromEmbedConfig?.content,
51✔
240
            ...customizationsFromViewConfig?.content,
51✔
241
        },
242
    };
243
    return customizations;
17✔
244
};
245

246
export const getRuntimeFilters = (runtimefilters: any) => getFilterQuery(runtimefilters || []);
35!
247

248
/**
249
 * Gets a reference to the DOM node given
250
 * a selector.
251
 * @param domSelector
252
 */
253
export function getDOMNode(domSelector: DOMSelector): HTMLElement {
35✔
254
    return typeof domSelector === 'string' ? document.querySelector(domSelector) : domSelector;
357✔
255
}
256

257
export const deepMerge = (target: any, source: any) => merge(target, source);
35✔
258

259
export const getOperationNameFromQuery = (query: string) => {
35✔
260
    const regex = /(?:query|mutation)\s+(\w+)/;
88✔
261
    const matches = query.match(regex);
88✔
262
    return matches?.[1];
88!
263
};
264

265
/**
266
 *
267
 * @param obj
268
 */
269
export function removeTypename(obj: any) {
35✔
270
    if (!obj || typeof obj !== 'object') return obj;
47✔
271

272
    // eslint-disable-next-line no-restricted-syntax
273
    for (const key in obj) {
36✔
274
        if (key === '__typename') {
90✔
275
            delete obj[key];
2✔
276
        } else if (typeof obj[key] === 'object') {
88✔
277
            removeTypename(obj[key]);
18✔
278
        }
279
    }
280
    return obj;
36✔
281
}
282

283
/**
284
 * Sets the specified style properties on an HTML element.
285
 * @param {HTMLElement} element - The HTML element to which the styles should be applied.
286
 * @param {Partial<CSSStyleDeclaration>} styleProperties - An object containing style
287
 * property names and their values.
288
 * @example
289
 * // Apply styles to an element
290
 * const element = document.getElementById('myElement');
291
 * const styles = {
292
 *   backgroundColor: 'red',
293
 *   fontSize: '16px',
294
 * };
295
 * setStyleProperties(element, styles);
296
 */
297
export const setStyleProperties = (
35✔
298
    element: HTMLElement,
299
    styleProperties: Partial<CSSStyleDeclaration>,
300
): void => {
301
    if (!element?.style) return;
26✔
302
    Object.keys(styleProperties).forEach((styleProperty) => {
25✔
303
        element.style[styleProperty] = styleProperties[styleProperty].toString();
85✔
304
    });
85✔
305
};
85✔
306
/**
85✔
307
 * Removes specified style properties from an HTML element.
308
 * @param {HTMLElement} element - The HTML element from which the styles should be removed.
309
 * @param {string[]} styleProperties - An array of style property names to be removed.
310
 * @example
311
 * // Remove styles from an element
312
 * const element = document.getElementById('myElement');
313
 * element.style.backgroundColor = 'red';
314
 * const propertiesToRemove = ['backgroundColor'];
315
 * removeStyleProperties(element, propertiesToRemove);
316
 */
317
export const removeStyleProperties = (element: HTMLElement, styleProperties: string[]): void => {
318
    if (!element?.style) return;
319
    styleProperties.forEach((styleProperty) => {
320
        element.style.removeProperty(styleProperty);
321
    });
35✔
322
};
7✔
323

6✔
324
export const isUndefined = (value: any): boolean => value === undefined;
16✔
325

326
// Return if the value is a string, double or boolean.
327
export const getTypeFromValue = (value: any): [string, string] => {
328
    if (typeof value === 'string') {
143✔
329
        return ['char', 'string'];
330
    }
331
    if (typeof value === 'number') {
35✔
332
        return ['double', 'double'];
9✔
333
    }
1✔
334
    if (typeof value === 'boolean') {
335
        return ['boolean', 'boolean'];
8✔
336
    }
2✔
337
    return ['', ''];
338
};
6✔
339

2✔
340
const sdkWindowKey = '_tsEmbedSDK' as any;
341

4✔
342
/**
343
 * Stores a value in the global `window` object under the `_tsEmbedSDK` namespace.
344
 * @param key - The key under which the value will be stored.
35✔
345
 * @param value - The value to store.
346
 * @param options - Additional options.
347
 * @param options.ignoreIfAlreadyExists - Does not set if value for key is set.
348
 *
349
 * @returns The stored value.
350
 *
351
 * @version SDK: 1.36.2 | ThoughtSpot: *
352
 */
353
export function storeValueInWindow<T>(
354
    key: string,
355
    value: T,
356
    options: { ignoreIfAlreadyExists?: boolean } = {},
357
): T {
35✔
358
    if (!window[sdkWindowKey]) {
359
        (window as any)[sdkWindowKey] = {};
360
    }
359✔
361

362
    if (options.ignoreIfAlreadyExists && key in (window as any)[sdkWindowKey]) {
379✔
363
        return (window as any)[sdkWindowKey][key];
22✔
364
    }
365

366
    (window as any)[sdkWindowKey][key] = value;
379✔
367
    return value;
1✔
368
}
369

370
/**
378✔
371
 * Retrieves a stored value from the global `window` object under the `_tsEmbedSDK` namespace.
378✔
372
 * @param key - The key whose value needs to be retrieved.
373
 * @returns The stored value or `undefined` if the key is not found.
374
 */
375
export const getValueFromWindow = <T = any>
376
    (key: string): T => (window as any)?.[sdkWindowKey]?.[key];
377

378
/**
379
 * Resets the key if it exists in the `window` object under the `_tsEmbedSDK` key.
35✔
380
 * Returns true if the key was reset, false otherwise.
2,354!
381
 * @param key - Key to reset
382
 * @returns - boolean indicating if the key was reset
383
 */
384
export function resetValueFromWindow(key: string): boolean {
385
    if (key in window[sdkWindowKey]) {
386
        delete (window as any)[sdkWindowKey][key];
387
        return true;
388
    }
35✔
389
    return false;
3✔
390
}
3✔
391

3✔
392
/**
UNCOV
393
 * Check if the document is currently in fullscreen mode
×
394
 */
395
const isInFullscreen = (): boolean => {
396
    return !!(
397
        document.fullscreenElement ||
398
        (document as any).webkitFullscreenElement ||
399
        (document as any).mozFullScreenElement ||
35✔
400
        (document as any).msFullscreenElement
6✔
401
    );
15✔
402
};
403

404
/**
405
 * Handle Present HostEvent by entering fullscreen mode
406
 * @param iframe The iframe element to make fullscreen
407
 */
408
export const handlePresentEvent = async (iframe: HTMLIFrameElement): Promise<void> => {
409
    if (isInFullscreen()) {
410
        return; // Already in fullscreen
411
    }
412

35✔
413
    // Browser-specific methods to enter fullscreen mode
3✔
414
    const fullscreenMethods = [
1✔
415
        'requestFullscreen',      // Standard API
416
        'webkitRequestFullscreen', // WebKit browsers
417
        'mozRequestFullScreen',   // Firefox
418
        'msRequestFullscreen'     // IE/Edge
2✔
419
    ];
420

421
    for (const method of fullscreenMethods) {
422
        if (typeof (iframe as any)[method] === 'function') {
423
            try {
424
                const result = (iframe as any)[method]();
425
                await Promise.resolve(result);
2✔
426
                return;
5✔
427
            } catch (error) {
1✔
428
                logger.warn(`Failed to enter fullscreen using ${method}:`, error);
1✔
429
            }
1✔
430
        }
1✔
431
    }
UNCOV
432

×
433
    logger.error('Fullscreen API is not supported by this browser.');
434
};
435

436
/**
437
 * Handle ExitPresentMode EmbedEvent by exiting fullscreen mode
1✔
438
 */
439
export const handleExitPresentMode = async (): Promise<void> => {
440
    if (!isInFullscreen()) {
441
        return; // Not in fullscreen
442
    }
443

35✔
444
    const exitFullscreenMethods = [
3✔
445
        'exitFullscreen',        // Standard API
1✔
446
        'webkitExitFullscreen',  // WebKit browsers
447
        'mozCancelFullScreen',   // Firefox
448
        'msExitFullscreen'       // IE/Edge
2✔
449
    ];
450

451
    // Try each method until one works
452
    for (const method of exitFullscreenMethods) {
453
        if (typeof (document as any)[method] === 'function') {
454
            try {
455
                const result = (document as any)[method]();
456
                await Promise.resolve(result);
2✔
457
                return;
5✔
458
            } catch (error) {
1✔
459
                logger.warn(`Failed to exit fullscreen using ${method}:`, error);
1✔
460
            }
1✔
461
        }
1✔
462
    }
UNCOV
463

×
464
    logger.warn('Exit fullscreen API is not supported by this browser.');
465
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc