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

thoughtspot / visual-embed-sdk / #3059

16 Dec 2025 01:41PM UTC coverage: 93.663% (-0.7%) from 94.364%
#3059

Pull #388

ruchI9897
poc
Pull Request #388: poc

1366 of 1551 branches covered (88.07%)

Branch coverage included in aggregate %.

5 of 17 new or added lines in 3 files covered. (29.41%)

33 existing lines in 6 files now uncovered.

3216 of 3341 relevant lines covered (96.26%)

107.9 hits per line

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

95.31
/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) {
422✔
30
        const filters = runtimeFilters.map((filter, valueIndex) => {
20✔
31
            const index = valueIndex + 1;
22✔
32
            const filterExpr = [];
22✔
33
            filterExpr.push(`col${index}=${encodeURIComponent(filter.columnName)}`);
22✔
34
            filterExpr.push(`op${index}=${filter.operator}`);
22✔
35
            filterExpr.push(
22✔
36
                filter.values.map((value) => {
37
                    const encodedValue = typeof value === 'bigint' ? value.toString() : value;
23!
38
                    return `val${index}=${encodeURIComponent(String(encodedValue))}`;
23✔
39
                }).join('&'),
40
            );
41

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

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

48
    return null;
402✔
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) {
421✔
57
        const params = runtimeParameters.map((param, valueIndex) => {
11✔
58
            const index = valueIndex + 1;
14✔
59
            const filterExpr = [];
14✔
60
            filterExpr.push(`param${index}=${encodeURIComponent(param.name)}`);
14✔
61
            filterExpr.push(`paramVal${index}=${encodeURIComponent(param.value)}`);
14✔
62

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

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

69
    return null;
410✔
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') {
15,623✔
80
        return value;
15,044✔
81
    }
82

83
    return JSON.stringify(value);
579✔
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[] = [];
576✔
104
    const params = Object.keys(queryParams);
576✔
105
    params.forEach((key) => {
576✔
106
        const val = queryParams[key];
16,198✔
107
        if (val !== undefined) {
16,198✔
108
            const serializedValue = shouldSerializeParamValues
15,640✔
109
                ? serializeParam(val)
110
                : paramToString(val);
111
            qp.push(`${key}=${serializedValue}`);
15,640✔
112
        }
113
    });
114

115
    if (qp.length) {
576✔
116
        return qp.join('&');
575✔
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') {
809✔
129
        return `${value}px`;
574✔
130
    }
131

132
    return value;
235✔
133
};
134

135
/**
136
 * Validates if a string is a valid CSS margin value.
137
 * @param value - The string to validate
138
 * @returns true if the value is a valid CSS margin value, false otherwise
139
 */
140
export const isValidCssMargin = (value: string): boolean => {
35✔
141
    if(isUndefined(value)) {
25!
UNCOV
142
        return false;
×
143
    }
144
    if (typeof value !== 'string') {
25!
UNCOV
145
        logger.error('Please provide a valid lazyLoadingMargin value (e.g., "10px")');
×
146
        return false;
×
147
    }
148

149
    // This pattern allows for an optional negative sign, and numbers that can be integers or decimals (including leading dot).
150
    const cssUnitPattern = /^-?(\d+(\.\d*)?|\.\d+)(px|em|rem|%|vh|vw)$/i;
25✔
151
    const parts = value.trim().split(/\s+/);
25✔
152

153
    if (parts.length > 4) {
25!
UNCOV
154
        logger.error('Please provide a valid lazyLoadingMargin value (e.g., "10px")');
×
155
        return false;
×
156
    }
157

158
    const isValid = parts.every(part => {
25✔
159
        const trimmedPart = part.trim();
27✔
160
        return trimmedPart.toLowerCase() === 'auto' || trimmedPart === '0' || cssUnitPattern.test(trimmedPart);
27✔
161
    });
162
    if (!isValid) {
25✔
163
        logger.error('Please provide a valid lazyLoadingMargin value (e.g., "10px")');
4✔
164
        return false;
4✔
165
    }
166
    return true;
21✔
167
};
168

169
export const getSSOMarker = (markerId: string) => {
35✔
170
    const encStringToAppend = encodeURIComponent(markerId);
18✔
171
    return `tsSSOMarker=${encStringToAppend}`;
18✔
172
};
173

174
/**
175
 * Append a string to a URL's hash fragment
176
 * @param url A URL
177
 * @param stringToAppend The string to append to the URL hash
178
 */
179
export const appendToUrlHash = (url: string, stringToAppend: string) => {
35✔
180
    let outputUrl = url;
12✔
181
    const encStringToAppend = encodeURIComponent(stringToAppend);
12✔
182

183
    const marker = `tsSSOMarker=${encStringToAppend}`;
12✔
184

185
    let splitAdder = '';
12✔
186

187
    if (url.indexOf('#') >= 0) {
12✔
188
        // If second half of hash contains a '?' already add a '&' instead of
189
        // '?' which appends to query params.
190
        splitAdder = url.split('#')[1].indexOf('?') >= 0 ? '&' : '?';
8✔
191
    } else {
192
        splitAdder = '#?';
4✔
193
    }
194
    outputUrl = `${outputUrl}${splitAdder}${marker}`;
12✔
195

196
    return outputUrl;
12✔
197
};
198

199
/**
200
 *
201
 * @param url
202
 * @param stringToAppend
203
 * @param path
204
 */
205
export function getRedirectUrl(url: string, stringToAppend: string, path = '') {
35✔
206
    const targetUrl = path ? new URL(path, window.location.origin).href : url;
10✔
207
    return appendToUrlHash(targetUrl, stringToAppend);
10✔
208
}
209

210
export const getEncodedQueryParamsString = (queryString: string) => {
35✔
211
    if (!queryString) {
4✔
212
        return queryString;
1✔
213
    }
214
    return btoa(queryString).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
3✔
215
};
216

217
export const getOffsetTop = (element: any) => {
35✔
218
    const rect = element.getBoundingClientRect();
5✔
219
    return rect.top + window.scrollY;
5✔
220
};
221

222
export const embedEventStatus = {
35✔
223
    START: 'start',
224
    END: 'end',
225
};
226

227
export const setAttributes = (
35✔
228
    element: HTMLElement,
229
    attributes: { [key: string]: string | number | boolean },
230
): void => {
231
    Object.keys(attributes).forEach((key) => {
401✔
232
        element.setAttribute(key, attributes[key].toString());
21✔
233
    });
234
};
235

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

238
/* For Search Embed: ReleaseVersionInBeta */
239
export const checkReleaseVersionInBeta = (
35✔
240
    releaseVersion: string,
241
    suppressBetaWarning: boolean,
242
): boolean => {
243
    if (releaseVersion !== '' && !isCloudRelease(releaseVersion)) {
110✔
244
        const splittedReleaseVersion = releaseVersion.split('.');
34✔
245
        const majorVersion = Number(splittedReleaseVersion[0]);
34✔
246
        const isBetaVersion = majorVersion < 8;
34✔
247
        return !suppressBetaWarning && isBetaVersion;
34✔
248
    }
249
    return false;
76✔
250
};
251

252
export const getCustomisations = (
35✔
253
    embedConfig: EmbedConfig,
254
    viewConfig: AllEmbedViewConfig,
255
): CustomisationsInterface => {
256
    const customizationsFromViewConfig = viewConfig.customizations;
20✔
257
    const customizationsFromEmbedConfig = embedConfig.customizations
20✔
258
        || ((embedConfig as any).customisations as CustomisationsInterface);
259

260
    const customizations: CustomisationsInterface = {
20✔
261
        style: {
262
            ...customizationsFromEmbedConfig?.style,
60✔
263
            ...customizationsFromViewConfig?.style,
60✔
264
            customCSS: {
265
                ...customizationsFromEmbedConfig?.style?.customCSS,
120✔
266
                ...customizationsFromViewConfig?.style?.customCSS,
120✔
267
            },
268
            customCSSUrl:
269
                customizationsFromViewConfig?.style?.customCSSUrl
160✔
270
                || customizationsFromEmbedConfig?.style?.customCSSUrl,
120✔
271
        },
272
        content: {
273
            ...customizationsFromEmbedConfig?.content,
60✔
274
            ...customizationsFromViewConfig?.content,
60✔
275
        },
276
    };
277
    return customizations;
20✔
278
};
279

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

282
/**
283
 * Gets a reference to the DOM node given
284
 * a selector.
285
 * @param domSelector
286
 */
287
export function getDOMNode(domSelector: DOMSelector): HTMLElement {
35✔
288
    return typeof domSelector === 'string' ? document.querySelector(domSelector) : domSelector;
467✔
289
}
290

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

293
export const getOperationNameFromQuery = (query: string) => {
35✔
294
    const regex = /(?:query|mutation)\s+(\w+)/;
88✔
295
    const matches = query.match(regex);
88✔
296
    return matches?.[1];
88!
297
};
298

299
/**
300
 *
301
 * @param obj
302
 */
303
export function removeTypename(obj: any) {
35✔
304
    if (!obj || typeof obj !== 'object') return obj;
47✔
305

306

307
    for (const key in obj) {
36✔
308
        if (key === '__typename') {
90✔
309
            delete obj[key];
2✔
310
        } else if (typeof obj[key] === 'object') {
88✔
311
            removeTypename(obj[key]);
18✔
312
        }
313
    }
314
    return obj;
36✔
315
}
316

317
/**
318
 * Sets the specified style properties on an HTML element.
319
 * @param {HTMLElement} element - The HTML element to which the styles should be applied.
320
 * @param {Partial<CSSStyleDeclaration>} styleProperties - An object containing style
321
 * property names and their values.
322
 * @example
323
 * // Apply styles to an element
324
 * const element = document.getElementById('myElement');
325
 * const styles = {
326
 *   backgroundColor: 'red',
327
 *   fontSize: '16px',
328
 * };
329
 * setStyleProperties(element, styles);
330
 */
331
export const setStyleProperties = (
35✔
332
    element: HTMLElement,
333
    styleProperties: Partial<CSSStyleDeclaration>,
334
): void => {
335
    if (!element?.style) return;
37✔
336
    Object.keys(styleProperties).forEach((styleProperty) => {
36✔
337
        const styleKey = styleProperty as keyof CSSStyleDeclaration;
124✔
338
        const value = styleProperties[styleKey];
124✔
339
        if (value !== undefined) {
124✔
340
            (element.style as any)[styleKey] = value.toString();
124✔
341
        }
342
    });
343
};
344
/**
345
 * Removes specified style properties from an HTML element.
346
 * @param {HTMLElement} element - The HTML element from which the styles should be removed.
347
 * @param {string[]} styleProperties - An array of style property names to be removed.
348
 * @example
349
 * // Remove styles from an element
350
 * const element = document.getElementById('myElement');
351
 * element.style.backgroundColor = 'red';
352
 * const propertiesToRemove = ['backgroundColor'];
353
 * removeStyleProperties(element, propertiesToRemove);
354
 */
355
export const removeStyleProperties = (element: HTMLElement, styleProperties: string[]): void => {
35✔
356
    if (!element?.style) return;
9✔
357
    styleProperties.forEach((styleProperty) => {
8✔
358
        element.style.removeProperty(styleProperty);
22✔
359
    });
360
};
361

362
export const isUndefined = (value: any): boolean => value === undefined;
334✔
363

364
// Return if the value is a string, double or boolean.
365
export const getTypeFromValue = (value: any): [string, string] => {
35✔
366
    if (typeof value === 'string') {
9✔
367
        return ['char', 'string'];
1✔
368
    }
369
    if (typeof value === 'number') {
8✔
370
        return ['double', 'double'];
2✔
371
    }
372
    if (typeof value === 'boolean') {
6✔
373
        return ['boolean', 'boolean'];
2✔
374
    }
375
    return ['', ''];
4✔
376
};
377

378
const sdkWindowKey = '_tsEmbedSDK' as any;
35✔
379

380
/**
381
 * Stores a value in the global `window` object under the `_tsEmbedSDK` namespace.
382
 * @param key - The key under which the value will be stored.
383
 * @param value - The value to store.
384
 * @param options - Additional options.
385
 * @param options.ignoreIfAlreadyExists - Does not set if value for key is set.
386
 *
387
 * @returns The stored value.
388
 *
389
 * @version SDK: 1.36.2 | ThoughtSpot: *
390
 */
391
export function storeValueInWindow<T>(
35✔
392
    key: string,
393
    value: T,
394
    options: { ignoreIfAlreadyExists?: boolean } = {},
459✔
395
): T {
396
    if (!window[sdkWindowKey]) {
479✔
397
        (window as any)[sdkWindowKey] = {};
22✔
398
    }
399

400
    if (options.ignoreIfAlreadyExists && key in (window as any)[sdkWindowKey]) {
479✔
401
        return (window as any)[sdkWindowKey][key];
1✔
402
    }
403

404
    (window as any)[sdkWindowKey][key] = value;
478✔
405
    return value;
478✔
406
}
407

408
/**
409
 * Retrieves a stored value from the global `window` object under the `_tsEmbedSDK` namespace.
410
 * @param key - The key whose value needs to be retrieved.
411
 * @returns The stored value or `undefined` if the key is not found.
412
 */
413
export const getValueFromWindow = <T = any>
35✔
414
    (key: string): T => (window as any)?.[sdkWindowKey]?.[key];
3,257!
415

416
/**
417
 * Check if an array includes a string value
418
 * @param arr - The array to check
419
 * @param key - The string to search for
420
 * @returns boolean indicating if the string is found in the array
421
 */
422
export const arrayIncludesString = (arr: readonly unknown[], key: string): boolean => {
35✔
423
    return arr.some(item => typeof item === 'string' && item === key);
397✔
424
};
425

426
/**
427
 * Resets the key if it exists in the `window` object under the `_tsEmbedSDK` key.
428
 * Returns true if the key was reset, false otherwise.
429
 * @param key - Key to reset
430
 * @returns - boolean indicating if the key was reset
431
 */
432
export function resetValueFromWindow(key: string): boolean {
35✔
433
    if (key in window[sdkWindowKey]) {
3✔
434
        delete (window as any)[sdkWindowKey][key];
3✔
435
        return true;
3✔
436
    }
UNCOV
437
    return false;
×
438
}
439

440
/**
441
 * Check if the document is currently in fullscreen mode
442
 */
443
const isInFullscreen = (): boolean => {
35✔
444
    return !!(
6✔
445
        document.fullscreenElement ||
15✔
446
        (document as any).webkitFullscreenElement ||
447
        (document as any).mozFullScreenElement ||
448
        (document as any).msFullscreenElement
449
    );
450
};
451

452
/**
453
 * Handle Present HostEvent by entering fullscreen mode
454
 * @param iframe The iframe element to make fullscreen
455
 */
456
export const handlePresentEvent = async (iframe: HTMLIFrameElement): Promise<void> => {
35✔
457
    if (isInFullscreen()) {
3✔
458
        return; // Already in fullscreen
1✔
459
    }
460

461
    // Browser-specific methods to enter fullscreen mode
462
    const fullscreenMethods = [
2✔
463
        'requestFullscreen',      // Standard API
464
        'webkitRequestFullscreen', // WebKit browsers
465
        'mozRequestFullScreen',   // Firefox
466
        'msRequestFullscreen'     // IE/Edge
467
    ];
468

469
    for (const method of fullscreenMethods) {
2✔
470
        if (typeof (iframe as any)[method] === 'function') {
5✔
471
            try {
1✔
472
                const result = (iframe as any)[method]();
1✔
473
                await Promise.resolve(result);
1✔
474
                return;
1✔
475
            } catch (error) {
UNCOV
476
                logger.warn(`Failed to enter fullscreen using ${method}:`, error);
×
477
            }
478
        }
479
    }
480

481
    logger.error('Fullscreen API is not supported by this browser.');
1✔
482
};
483

484
/**
485
 * Handle ExitPresentMode EmbedEvent by exiting fullscreen mode
486
 */
487
export const handleExitPresentMode = async (): Promise<void> => {
35✔
488
    if (!isInFullscreen()) {
3✔
489
        return; // Not in fullscreen
1✔
490
    }
491

492
    const exitFullscreenMethods = [
2✔
493
        'exitFullscreen',        // Standard API
494
        'webkitExitFullscreen',  // WebKit browsers
495
        'mozCancelFullScreen',   // Firefox
496
        'msExitFullscreen'       // IE/Edge
497
    ];
498

499
    // Try each method until one works
500
    for (const method of exitFullscreenMethods) {
2✔
501
        if (typeof (document as any)[method] === 'function') {
5✔
502
            try {
1✔
503
                const result = (document as any)[method]();
1✔
504
                await Promise.resolve(result);
1✔
505
                return;
1✔
506
            } catch (error) {
UNCOV
507
                logger.warn(`Failed to exit fullscreen using ${method}:`, error);
×
508
            }
509
        }
510
    }
511

512
    logger.warn('Exit fullscreen API is not supported by this browser.');
1✔
513
};
514

515
export const calculateVisibleElementData = (element: HTMLElement) => {
35✔
516
    const rect = element.getBoundingClientRect();
19✔
517

518
    const windowHeight = window.innerHeight;
19✔
519
    const windowWidth = window.innerWidth;
19✔
520

521
    const frameRelativeTop = Math.max(rect.top, 0);
19✔
522
    const frameRelativeLeft = Math.max(rect.left, 0);
19✔
523

524
    const frameRelativeBottom = Math.min(windowHeight, rect.bottom);
19✔
525
    const frameRelativeRight = Math.min(windowWidth, rect.right);
19✔
526

527
    const data = {
19✔
528
        top: Math.max(0, rect.top * -1),
529
        height: Math.max(0, frameRelativeBottom - frameRelativeTop),
530
        left: Math.max(0, rect.left * -1),
531
        width: Math.max(0, frameRelativeRight - frameRelativeLeft),
532
    };
533

534
    return data;
19✔
535
}
536

537
/**
538
 * Replaces placeholders in a template string with provided values.
539
 * Placeholders should be in the format {key}.
540
 * @param template - The template string with placeholders
541
 * @param values - An object containing key-value pairs to replace placeholders
542
 * @returns The template string with placeholders replaced
543
 * @example
544
 * formatTemplate('Hello {name}, you are {age} years old', { name: 'John', age: 30 })
545
 * // Returns: 'Hello John, you are 30 years old'
546
 *
547
 * formatTemplate('Expected {type}, but received {actual}', { type: 'string', actual: 'number' })
548
 * // Returns: 'Expected string, but received number'
549
 */
550
export const formatTemplate = (template: string, values: Record<string, any>): string => {
35✔
551
    // This regex /\{(\w+)\}/g finds all placeholders in the format {word} 
552
    // and captures the word inside the braces for replacement.
553
    return template.replace(/\{(\w+)\}/g, (match, key) => {
7✔
554
        return values[key] !== undefined ? String(values[key]) : match;
10✔
555
    });
556
};
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