forked from appsmithorg/appsmith
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.tsx
More file actions
1386 lines (1181 loc) · 36.9 KB
/
Copy pathhelpers.tsx
File metadata and controls
1386 lines (1181 loc) · 36.9 KB
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
import React from "react";
import {
GridDefaults,
MAIN_CONTAINER_WIDGET_ID,
} from "constants/WidgetConstants";
import lazyLottie from "./lazyLottie";
import welcomeConfettiAnimationURL from "assets/lottie/welcome-confetti.json.txt";
import {
DATA_TREE_KEYWORDS,
DEDICATED_WORKER_GLOBAL_SCOPE_IDENTIFIERS,
JAVASCRIPT_KEYWORDS,
} from "constants/WidgetValidation";
import { get, has, isNil, uniq } from "lodash";
import type { Workspace } from "ee/constants/workspaceConstants";
import { hasCreateNewAppPermission } from "ee/utils/permissionHelpers";
import moment from "moment";
import { isDynamicValue } from "./DynamicBindingUtils";
import type { ApiResponse } from "api/ApiResponses";
import type { DSLWidget } from "WidgetProvider/types";
import { matchPath } from "react-router";
import {
BUILDER_CUSTOM_PATH,
BUILDER_PATH,
BUILDER_PATH_DEPRECATED,
VIEWER_CUSTOM_PATH,
VIEWER_PATH,
VIEWER_PATH_DEPRECATED,
VIEWER_PATH_STATIC,
} from "constants/routes";
import history from "./history";
import { APPSMITH_GLOBAL_FUNCTIONS } from "components/editorComponents/ActionCreator/constants";
import type {
CanvasWidgetsReduxState,
FlattenedWidgetProps,
} from "ee/reducers/entityReducers/canvasWidgetsReducer";
import { checkContainerScrollable } from "widgets/WidgetUtils";
import { getContainerIdForCanvas } from "sagas/WidgetOperationUtils";
import scrollIntoView from "scroll-into-view-if-needed";
import validateColor from "validate-color";
import { CANVAS_VIEWPORT } from "constants/componentClassNameConstants";
import { klona as klonaFull } from "klona/full";
import { klona as klonaRegular } from "klona";
import { klona as klonaLite } from "klona/lite";
import { klona as klonaJson } from "klona/json";
import { startAndEndSpanForFn } from "instrumentation/generateTraces";
import type { Property } from "entities/Action";
import { appsmithTelemetry } from "instrumentation";
export const snapToGrid = (
columnWidth: number,
rowHeight: number,
x: number,
y: number,
) => {
const snappedX = Math.round(x / columnWidth);
const snappedY = Math.round(y / rowHeight);
return [snappedX, snappedY];
};
export const getAbsolutePixels = (size?: string | null) => {
if (!size) return 0;
const _dex = size.indexOf("px");
if (_dex === -1) return 0;
return parseInt(size.slice(0, _dex), 10);
};
export const Directions: { [id: string]: string } = {
UP: "up",
DOWN: "down",
LEFT: "left",
RIGHT: "right",
RIGHT_BOTTOM: "RIGHT_BOTTOM",
};
export type Direction = (typeof Directions)[keyof typeof Directions];
const SCROLL_THRESHOLD = 20;
export const getScrollByPixels = function (
elem: {
top: number;
height: number;
},
scrollParent: Element,
child: Element,
): {
scrollAmount: number;
speed: number;
} {
const scrollParentBounds = scrollParent.getBoundingClientRect();
const scrollChildBounds = child.getBoundingClientRect();
const scrollAmount =
2 *
GridDefaults.CANVAS_EXTENSION_OFFSET *
GridDefaults.DEFAULT_GRID_ROW_HEIGHT;
const topBuff =
elem.top + scrollChildBounds.top > 0
? elem.top +
scrollChildBounds.top -
SCROLL_THRESHOLD -
scrollParentBounds.top
: 0;
const bottomBuff =
scrollParentBounds.bottom -
(elem.top + elem.height + scrollChildBounds.top + SCROLL_THRESHOLD);
if (topBuff < SCROLL_THRESHOLD) {
const speed = Math.max(
(SCROLL_THRESHOLD - topBuff) / (2 * SCROLL_THRESHOLD),
0.1,
);
return {
scrollAmount: 0 - scrollAmount,
speed,
};
}
if (bottomBuff < SCROLL_THRESHOLD) {
const speed = Math.max(
(SCROLL_THRESHOLD - bottomBuff) / (2 * SCROLL_THRESHOLD),
0.1,
);
return {
scrollAmount,
speed,
};
}
return {
scrollAmount: 0,
speed: 0,
};
};
export const scrollElementIntoParentCanvasView = (
el: {
top: number;
height: number;
} | null,
parent: Element | null,
child: Element | null,
) => {
if (el) {
const scrollParent = parent;
if (scrollParent && child) {
const { scrollAmount: scrollBy } = getScrollByPixels(
el,
scrollParent,
child,
);
if (scrollBy < 0 && scrollParent.scrollTop > 0) {
scrollParent.scrollBy({ top: scrollBy, behavior: "smooth" });
}
if (scrollBy > 0) {
scrollParent.scrollBy({ top: scrollBy, behavior: "smooth" });
}
}
}
};
export function hasClass(ele: HTMLElement, cls: string) {
return ele.classList.contains(cls);
}
function addClass(ele: HTMLElement, cls: string) {
if (!hasClass(ele, cls)) ele.classList.add(cls);
}
function removeClass(ele: HTMLElement, cls: string) {
if (hasClass(ele, cls)) {
ele.classList.remove(cls);
}
}
export const removeSpecialChars = (value: string, limit?: number) => {
const separatorRegex = /\W+/;
return value
.split(separatorRegex)
.join("_")
.slice(0, limit || 30);
};
export const flashElement = (
el: HTMLElement,
flashTimeout = 1000,
flashClass = "flash",
) => {
if (!el) return;
addClass(el, flashClass);
setTimeout(() => {
removeClass(el, flashClass);
}, flashTimeout);
};
/**
* flash elements with a background color
*
* @param id
* @param timeout
* @param flashTimeout
* @param flashColor
*/
export const flashElementsById = (
id: string | string[],
timeout = 0,
flashTimeout?: number,
flashClass?: string,
) => {
let ids: string[] = [];
if (Array.isArray(id)) {
ids = ids.concat(id);
} else {
ids = ids.concat([id]);
}
ids.forEach((id) => {
setTimeout(() => {
const el = document.getElementById(id);
if (el) flashElement(el, flashTimeout, flashClass);
}, timeout);
});
};
/**
* Scrolls to the widget of WidgetId without any animantion.
* @param widgetId
* @param canvasWidgets
*/
export const quickScrollToWidget = (
widgetId: string,
widgetIdSelector: string,
canvasWidgets: CanvasWidgetsReduxState,
) => {
if (!widgetId || widgetId === "") return;
window.requestIdleCallback(() => {
const el = document.getElementById(widgetIdSelector);
const canvas = document.getElementById(CANVAS_VIEWPORT);
if (el && canvas && !isElementVisibleInContainer(el, canvas, 5)) {
const scrollElement = getWidgetElementToScroll(
widgetId,
widgetIdSelector,
canvasWidgets,
);
if (scrollElement) {
scrollIntoView(scrollElement, {
block: "center",
inline: "nearest",
behavior: "smooth",
});
}
}
});
};
/** Checks if a percentage of element is visible inside a container or not
The function first retrieves the bounding rectangles of both the
container and the element using the getBoundingClientRect() method.
It then calculates the visible area of the element inside the container
by determining the intersection between the two bounding rectangles.
The function then calculates the percentage of the element that is
visible by dividing the visible area by the total area of the element
and multiplying by 100. Finally, it returns true if the visible percentage
is greater than or equal to the desired percentage, and false otherwise.
Note that this function assumes that the element and the container
are both positioned using the CSS position property, and that the
container is positioned relative to its containing block. If the
element or the container have a different positioning, the
function may need to be adjusted accordingly.
**/
function isElementVisibleInContainer(
element: HTMLElement,
container: HTMLElement,
percentage = 100,
) {
const elementBounds = element.getBoundingClientRect();
const containerBounds = container.getBoundingClientRect();
// Calculate the visible area of the element inside the container
const visibleWidth =
Math.min(elementBounds.right, containerBounds.right) -
Math.max(elementBounds.left, containerBounds.left);
const visibleHeight =
Math.min(elementBounds.bottom, containerBounds.bottom) -
Math.max(elementBounds.top, containerBounds.top);
const visibleArea = visibleWidth * visibleHeight;
// Calculate the percentage of the element that is visible
const elementArea = element.clientWidth * element.clientHeight;
if (elementArea === 0) return false;
const visiblePercentage = (visibleArea / elementArea) * 100;
// Return whether the visible percentage is greater than or equal to the desired percentage
return visiblePercentage >= percentage;
}
/**
* This function provides the correct DOM element to scroll to
* such that the widget (argument) is visible in the viewport.
* This function has been implemented to run when the viewer or editor
* is loaded with a widget ID in the URL.
* This is a part of the Context preserving logic
*
* @param widgetId : Widget ID to scroll to
* @param canvasWidgets : Canvas widgets redux state
* @returns HTMLElement to scroll to or null
*/
function getWidgetElementToScroll(
widgetId: string,
widgetIdSelector: string,
canvasWidgets: CanvasWidgetsReduxState,
): HTMLElement | null {
const widget = canvasWidgets[widgetId];
if (!widget) return null;
const parentId = widget.parentId;
// If the widget doesn't have a parent, scroll to the widget itself
// This is the case for the main container widget, however,
// this scenario is not likely to occur in a normal use case.
if (parentId == undefined) return document.getElementById(widgetIdSelector);
// Get the containing container like widget for the widget
// Note: The parentId is usually pointing to a CANVAS_WIDGET
// However, we can only scroll a container like widget which is the parent
// of the CANVAS_WIDGET. Hence, we need to get the container like widget's Id.
const containerId = getContainerIdForCanvas(parentId);
// If we failed to get the container, try to scroll to the widget itself
if (containerId === undefined) {
return document.getElementById(widgetIdSelector);
} else {
// If the widget is not within a modal widget,
// but is the child of the main container widget,
// scroll to the widget itself
if (containerId === MAIN_CONTAINER_WIDGET_ID) {
if (widget.detachFromLayout) {
return document.getElementById(widgetIdSelector);
}
}
// Get the container widget props from the redux state
const containerWidget: FlattenedWidgetProps = canvasWidgets[containerId];
// If the widget is within a container, check if the container is scrollable
if (checkContainerScrollable(containerWidget)) {
return document.getElementById(widgetIdSelector);
} else {
// If the container is not scrollable, scroll to the container itself
return document.getElementById(containerId);
}
}
}
export const toValidPageName = (value: string) => {
// Ensure that `/`, `\` and `:` are not allowed in page names, aligning with server-side validation.
return value.replaceAll(/[\\/:<>"|?*\x00-\x1f]+/g, "").slice(0, 30);
};
export const PLATFORM_OS = {
MAC: "MAC",
IOS: "IOS",
LINUX: "LINUX",
ANDROID: "ANDROID",
WINDOWS: "WINDOWS",
};
const platformOSRegex = {
[PLATFORM_OS.MAC]: /mac.*/i,
[PLATFORM_OS.IOS]: /(?:iphone|ipod|ipad|Pike v.*)/i,
[PLATFORM_OS.LINUX]: /(?:linux.*)/i,
[PLATFORM_OS.ANDROID]: /android.*|aarch64|arm.*/i,
[PLATFORM_OS.WINDOWS]: /win.*/i,
};
export const getPlatformOS = () => {
const browserPlatform =
typeof navigator !== "undefined" ? navigator.platform : null;
if (browserPlatform) {
const platformOSList = Object.entries(platformOSRegex);
const platform = platformOSList.find(([, regex]) =>
regex.test(browserPlatform),
);
return platform ? platform[0] : null;
}
return null;
};
export const isMacOrIOS = () => {
const platformOS = getPlatformOS();
return platformOS === PLATFORM_OS.MAC || platformOS === PLATFORM_OS.IOS;
};
export const getBrowserInfo = () => {
const userAgent =
typeof navigator !== "undefined" ? navigator.userAgent : null;
if (userAgent) {
let specificMatch;
let match =
userAgent.match(
/(opera|chrome|safari|firefox|msie|CriOS|trident(?=\/))\/?\s*(\d+)/i,
) || [];
// browser
if (/CriOS/i.test(match[1])) match[1] = "Chrome";
if (match[1] === "Chrome") {
specificMatch = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
if (specificMatch) {
const opera = specificMatch.slice(1);
return {
browser: opera[0].replace("OPR", "Opera"),
version: opera[1],
};
}
specificMatch = userAgent.match(/\b(Edg)\/(\d+)/);
if (specificMatch) {
const edge = specificMatch.slice(1);
return {
browser: edge[0].replace("Edg", "Edge (Chromium)"),
version: edge[1],
};
}
}
// version
match = match[2]
? [match[1], match[2]]
: [navigator.appName, navigator.appVersion, "-?"];
const version = userAgent.match(/version\/(\d+)/i);
version && match.splice(1, 1, version[1]);
return { browser: match[0], version: match[1] };
}
return null;
};
/**
* Removes the trailing slashes from the path
* @param path
* @example
* ```js
* let trimmedUrl = trimTrailingSlash('/url/')
* console.log(trimmedUrl) //will output /url
* ```
* @example
* ```js
* let trimmedUrl = trimTrailingSlash('/yet-another-url//')
* console.log(trimmedUrl) // will output /yet-another-url
* ```
*/
export const trimTrailingSlash = (path: string) => {
const trailingUrlRegex = /\/+$/;
return path.replace(trailingUrlRegex, "");
};
/**
* checks if ellipsis is active
* this function is meant for checking the existence of ellipsis by CSS.
* Since ellipsis by CSS are not part of DOM, we are checking with scroll width\height and offsetidth\height.
* ScrollWidth\ScrollHeight is always greater than the offsetWidth\OffsetHeight when ellipsis made by CSS is active.
* Using clientWidth to fix this https://stackoverflow.com/a/21064102/8692954
* @param element
*/
export const isEllipsisActive = (element: HTMLElement | null) => {
return element && element.clientWidth < element.scrollWidth;
};
export const isVerticalEllipsisActive = (element: HTMLElement | null) => {
return element && element.clientHeight < element.scrollHeight;
};
/**
* converts array to sentences
* for e.g - ['Pawan', 'Abhinav', 'Hetu'] --> 'Pawan, Abhinav and Hetu'
*
* @param arr string[]
*/
export const convertArrayToSentence = (arr: string[]) => {
return arr.join(", ").replace(/,\s([^,]+)$/, " and $1");
};
/**
* checks if the name is conflicting with
* 1. API names,
* 2. Queries name
* 3. Javascript reserved names
* 4. Few internal function names that are in the evaluation tree
*
* return if false name conflicts with anything from the above list
*
* @param name
* @param invalidNames
*/
export const isNameValid = (
name: string,
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
invalidNames: Record<string, any>,
) => {
return !(
has(JAVASCRIPT_KEYWORDS, name) ||
has(DATA_TREE_KEYWORDS, name) ||
has(DEDICATED_WORKER_GLOBAL_SCOPE_IDENTIFIERS, name) ||
has(APPSMITH_GLOBAL_FUNCTIONS, name) ||
has(invalidNames, name)
);
};
/*
* Filter out empty items from an array
* for e.g - ['Pawan', undefined, 'Hetu'] --> ['Pawan', 'Hetu']
*
* @param array any[]
*/
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const removeFalsyEntries = (arr: any[]): any[] => {
return arr.filter(Boolean);
};
/**
* checks if variable passed is of type string or not
*
* for e.g -> 'Pawan' -> true
* ['Pawan', 'Goku'] -> false
* { name: "Pawan"} -> false
*/
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isString = (str: any): str is string => {
return typeof str === "string" || str instanceof String;
};
/**
* Returns substring between two set of strings
* eg ->
* getSubstringBetweenTwoWords("abcdefgh", "abc", "fgh") -> de
*/
export const getSubstringBetweenTwoWords = (
str: string,
startWord: string,
endWord: string,
) => {
const endIndexOfStartWord = str.indexOf(startWord) + startWord.length;
const startIndexOfEndWord = str.lastIndexOf(endWord);
if (startIndexOfEndWord < endIndexOfStartWord) return "";
return str.substring(startIndexOfEndWord, endIndexOfStartWord);
};
export const playWelcomeAnimation = (container: string) => {
playLottieAnimation(container, welcomeConfettiAnimationURL);
};
const playLottieAnimation = (
selector: string,
animationURL: string,
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
styles?: any,
) => {
const container: Element = document.querySelector(selector) as Element;
if (!container) return;
const el = document.createElement("div");
Object.assign(el.style, {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
"z-index": 99,
width: "100%",
height: "100%",
...styles,
});
container.appendChild(el);
const animObj = lazyLottie.loadAnimation({
container: el,
path: animationURL,
loop: false,
});
animObj.play();
animObj.addEventListener("complete", () => {
container.removeChild(el);
});
};
export const getSelectedText = () => {
if (typeof window.getSelection === "function") {
const selectionObj = window.getSelection();
return selectionObj && selectionObj.toString();
}
};
/**
* calculates and returns the scrollwidth
*
* @returns
*/
export const scrollbarWidth = () => {
const scrollDiv = document.createElement("div");
scrollDiv.setAttribute(
"style",
"width: 100px; height: 100px; overflow: scroll; position:absolute; top:-9999px;",
);
document.body.appendChild(scrollDiv);
const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
// Flatten object
// From { isValid: false, settings: { color: false}}
// To { isValid: false, settings.color: false}
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const flattenObject = (data: Record<string, any>) => {
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = {};
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function recurse(cur: any, prop: any) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for (let i = 0, l = cur.length; i < l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (cur.length == 0) result[prop] = [];
} else {
let isEmpty = true;
for (const p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop + "." + p : p);
}
if (isEmpty && prop) result[prop] = {};
}
}
recurse(data, "");
return result;
};
// Can be used to check if the user has developer role access to workspace
export const getCanCreateApplications = (currentWorkspace: Workspace) => {
const userWorkspacePermissions = currentWorkspace.userPermissions || [];
const canManage = hasCreateNewAppPermission(userWorkspacePermissions ?? []);
return canManage;
};
export const getIsSafeRedirectURL = (redirectURL: string) => {
try {
return (
new URL(redirectURL, window.location.origin).origin ===
window.location.origin
);
} catch (e) {
return false;
}
};
export const stopClickEventPropagation = (
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
) => {
e.stopPropagation();
};
/**
*
* Get text for how much time before an action happened
* Eg: 1 Month, 12 Seconds
*
* @param date 2021-09-08T14:14:12Z
*
*/
export const howMuchTimeBeforeText = (
date: string,
options: { lessThanAMinute: boolean } = { lessThanAMinute: false },
) => {
if (!date || !moment.isMoment(moment(date))) {
return "";
}
const { lessThanAMinute } = options;
const now = moment();
const checkDate = moment(date);
const years = now.diff(checkDate, "years");
const months = now.diff(checkDate, "months");
const days = now.diff(checkDate, "days");
const hours = now.diff(checkDate, "hours");
const minutes = now.diff(checkDate, "minutes");
const seconds = now.diff(checkDate, "seconds");
if (years > 0) return `${years} yr${years > 1 ? "s" : ""}`;
else if (months > 0) return `${months} mth${months > 1 ? "s" : ""}`;
else if (days > 0) return `${days} day${days > 1 ? "s" : ""}`;
else if (hours > 0) return `${hours} hr${hours > 1 ? "s" : ""}`;
else if (minutes > 0) return `${minutes} min${minutes > 1 ? "s" : ""}`;
else
return lessThanAMinute
? "less than a minute"
: `${seconds} sec${seconds > 1 ? "s" : ""}`;
};
/**
*
* Truncate string and append given string in the end
* eg: Flint Lockwood Diatonic Super Mutating Dynamic Food Replicator
* -> Flint...
*
*/
export const truncateString = (
str: string,
limit: number,
appendStr = "...",
) => {
if (str.length <= limit) return str;
let _subString = str.substring(0, limit);
_subString = _subString.trim() + appendStr;
return _subString;
};
/**
* returns the modText ( ctrl or command ) based on the user machine
*
* @returns
*/
export const modText = () => (isMacOrIOS() ? "\u2318" : "Ctrl +");
export const altText = () => (isMacOrIOS() ? "\u2325" : "Alt +");
export const shiftText = () => (isMacOrIOS() ? "\u21EA" : "Shift +");
export const undoShortCut = () => <span>{modText()} Z</span>;
export const redoShortCut = () =>
isMacOrIOS() ? (
<span>
{modText()} {shiftText()} Z
</span>
) : (
<span>{modText()} Y</span>
);
/**
* @returns the original string after trimming the string past `?`
*/
export const trimQueryString = (value = "") => {
const index = value.indexOf("?");
if (index === -1) return value;
return value.slice(0, index);
};
/**
* returns the value in the query string for a key
*/
export const getSearchQuery = (search = "", key: string) => {
const params = new URLSearchParams(search);
return decodeURIComponent(params.get(key) || "");
};
/*
* unfocus all window selection
*
* @param document
* @param window
*/
export function unFocus(document: Document, window: Window) {
if (document.getSelection()) {
document.getSelection()?.empty();
} else {
try {
window.getSelection()?.removeAllRanges();
// eslint-disable-next-line no-empty
} catch (e) {}
}
}
export function getLogToSentryFromResponse(response?: ApiResponse) {
return response && response?.responseMeta?.status >= 500;
}
/**
* extract colors from string
*
* @returns
* @param widgets
*/
export function extractColorsFromString(widgets: CanvasWidgetsReduxState) {
const colors = new Set();
Object.values(widgets).forEach((widget) => {
Object.values(widget).forEach((widgetProp) => {
if (isString(widgetProp) && validateColor(widgetProp)) {
colors.add(widgetProp);
}
});
});
return Array.from(colors) as Array<string>;
}
/**
* validate color string
*
* @returns {boolean} true if empty string or includes url or is valid color
* @param color
*/
export function isValidColor(color: string) {
return color?.includes("url") || validateColor(color) || isEmptyOrNill(color);
}
function klonaWithTelemetryWrapper<T>(
value: T,
codeSegment: string,
variant: string,
klonaFn: (input: T) => T,
): T {
return startAndEndSpanForFn(
"klona",
{
codeSegment,
variant,
},
() => klonaFn(value),
);
}
export function klonaFullWithTelemetry<T>(value: T, codeSegment: string): T {
return klonaWithTelemetryWrapper(value, codeSegment, "full", klonaFull);
}
export function klonaRegularWithTelemetry<T>(value: T, codeSegment: string): T {
return klonaWithTelemetryWrapper(value, codeSegment, "regular", klonaRegular);
}
export function klonaLiteWithTelemetry<T>(value: T, codeSegment: string): T {
return klonaWithTelemetryWrapper(value, codeSegment, "lite", klonaLite);
}
export function klonaJsonWithTelemetry<T>(value: T, codeSegment: string): T {
return klonaWithTelemetryWrapper(value, codeSegment, "json", klonaJson);
}
/*
* Function to merge property pane config of a widget
*
*/
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const mergeWidgetConfig = (target: any, source: any) => {
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sectionMap: Record<string, any> = {};
const mergedConfig = klonaFullWithTelemetry(
target,
"helpers.mergeWidgetConfig",
);
mergedConfig.forEach((section: { sectionName: string }) => {
sectionMap[section.sectionName] = section;
});
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
source.forEach((section: { sectionName: string; children: any[] }) => {
const targetSection = sectionMap[section.sectionName];
if (targetSection) {
Array.prototype.push.apply(targetSection.children, section.children);
} else {
mergedConfig.push(section);
}
});
return mergedConfig;
};
export const getLocale = () => {
return navigator.languages?.[0] || "en-US";
};
/**
* Function to check if the DynamicBindingPathList is valid
* @param currentDSL
* @returns
*/
export const captureInvalidDynamicBindingPath = (
currentDSL: Readonly<DSLWidget>,
) => {
//Get the dynamicBindingPathList of the current DSL
const dynamicBindingPathList = get(currentDSL, "dynamicBindingPathList");
dynamicBindingPathList?.forEach((dBindingPath) => {
const pathValue = get(currentDSL, dBindingPath.key); //Gets the value for the given dynamic binding path
/**
* Checks if dynamicBindingPathList contains a property path that doesn't have a binding
*/
if (!isDynamicValue(pathValue)) {
appsmithTelemetry.captureException(
new Error(
`INVALID_DynamicPathBinding_CLIENT_ERROR: Invalid dynamic path binding list: ${currentDSL.widgetName}.${dBindingPath.key}`,
),
{ errorName: "InvalidDynamicPathBinding" },
);
return;
}
});
if (currentDSL.children) {
currentDSL.children.map(captureInvalidDynamicBindingPath);
}
return currentDSL;
};
/**
* Function to handle undefined returned in case of using [].find()
* @param result
* @param errorMessage
* @returns the result if not undefined or throws an Error
*/
export function shouldBeDefined<T>(
result: T | undefined | null,
errorMessage: string,
): T {
if (result === undefined || result === null) {
throw new TypeError(errorMessage);
}
return result;
}
/*
* Check if a value is null / undefined / empty string
*
* @param value: any
*/
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isEmptyOrNill = (value: any) => {
return isNil(value) || (isString(value) && value === "");
};
export const isURLDeprecated = (url: string) => {
return !!matchPath(url, {
path: [
trimQueryString(BUILDER_PATH_DEPRECATED),
trimQueryString(VIEWER_PATH_DEPRECATED),