forked from appsmithorg/appsmith
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppsmithUtils.tsx
More file actions
471 lines (393 loc) · 12.6 KB
/
Copy pathAppsmithUtils.tsx
File metadata and controls
471 lines (393 loc) · 12.6 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
import { ERROR_CODES } from "ee/constants/ApiConstants";
import { createMessage, ERROR_500 } from "ee/constants/messages";
import type { AppIconName } from "@appsmith/ads-old";
import { AppIconCollection } from "@appsmith/ads-old";
import _, { isPlainObject } from "lodash";
import log from "loglevel";
import { osName } from "react-device-detect";
import type { ActionDataState } from "ee/reducers/entityReducers/actionsReducer";
import type { JSCollectionData } from "ee/reducers/entityReducers/jsActionsReducer";
import type { CreateNewActionKeyInterface } from "ee/entities/Engine/actionHelpers";
import { CreateNewActionKey } from "ee/entities/Engine/actionHelpers";
export const INTERACTION_ANALYTICS_EVENT = "INTERACTION_ANALYTICS_EVENT";
export interface InteractionAnalyticsEventDetail {
key?: string;
propertyName?: string;
propertyType?: string;
widgetType?: string;
}
export const interactionAnalyticsEvent = (
detail: InteractionAnalyticsEventDetail = {},
) =>
new CustomEvent(INTERACTION_ANALYTICS_EVENT, {
bubbles: true,
detail,
});
export function emitInteractionAnalyticsEvent<T extends HTMLElement>(
element: T | null,
args: Record<string, unknown>,
) {
element?.dispatchEvent(interactionAnalyticsEvent(args));
}
export const DS_EVENT = "DS_EVENT";
export enum DSEventTypes {
KEYPRESS = "KEYPRESS",
}
export interface DSEventDetail {
component: string;
event: DSEventTypes;
meta: Record<string, unknown>;
}
export function createDSEvent(detail: DSEventDetail) {
return new CustomEvent(DS_EVENT, {
bubbles: true,
detail,
});
}
export function emitDSEvent<T extends HTMLElement>(
element: T | null,
args: DSEventDetail,
) {
element?.dispatchEvent(createDSEvent(args));
}
export const getNextEntityName = (
prefix: string,
existingNames: string[],
startWithoutIndex?: boolean,
) => {
const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`^${escapedPrefix}(\\d+)$`);
const usedIndices: number[] = existingNames.map((name) => {
if (name && regex.test(name)) {
const matches = name.match(regex);
const ind =
matches && Array.isArray(matches) ? parseInt(matches[1], 10) : 0;
return Number.isNaN(ind) ? 0 : ind;
}
return 0;
}) as number[];
const lastIndex = Math.max(...usedIndices, ...[0]);
if (startWithoutIndex && lastIndex === 0) {
const exactMatchFound = existingNames.some(
(name) => prefix && name.trim() === prefix.trim(),
);
if (!exactMatchFound) {
return prefix.trim();
}
}
return prefix + (lastIndex + 1);
};
export const getDuplicateName = (prefix: string, existingNames: string[]) => {
const trimmedPrefix = prefix.replace(/ /g, "");
const escapedPrefix = trimmedPrefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`^${escapedPrefix}(\\d+)$`);
const usedIndices: number[] = existingNames.map((name) => {
if (name && regex.test(name)) {
const matches = name.match(regex);
const ind =
matches && Array.isArray(matches) ? parseInt(matches[1], 10) : 0;
return Number.isNaN(ind) ? 0 : ind;
}
return 0;
}) as number[];
const lastIndex = Math.max(...usedIndices, ...[0]);
return trimmedPrefix + `_${lastIndex + 1}`;
};
export const createNewApiName = (
actions: ActionDataState,
entityId: string,
key: CreateNewActionKeyInterface = CreateNewActionKey.PAGE,
) => {
const pageApiNames = actions // TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.filter((a: any) => a.config[key] === entityId)
.map((a) => a.config.name);
return getNextEntityName("Api", pageApiNames);
};
export const createNewJSFunctionName = (
jsActions: JSCollectionData[],
entityId: string,
key: CreateNewActionKeyInterface = CreateNewActionKey.PAGE,
) => {
const pageJsFunctionNames = jsActions // TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.filter((a: any) => a.config[key] === entityId)
.map((a) => a.config.name);
return getNextEntityName("JSObject", pageJsFunctionNames);
};
export const noop = () => {
log.debug("noop");
};
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const stopEventPropagation = (e: any) => {
e.stopPropagation();
};
export const createNewQueryName = (
queries: ActionDataState,
entityId: string,
prefix = "Query",
key: CreateNewActionKeyInterface = CreateNewActionKey.PAGE,
) => {
const pageApiNames = queries // TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.filter((a: any) => a.config[key] === entityId)
.map((a) => a.config.name);
return getNextEntityName(prefix, pageApiNames);
};
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const convertToString = (value: any): string => {
if (_.isUndefined(value)) {
return "";
}
if (_.isObject(value)) {
return JSON.stringify(value, null, 2);
}
if (_.isString(value)) return value;
return value.toString();
};
export const getInitialsFromName = (fullName: string) => {
let inits = "";
// if name contains space. eg: "Full Name"
if (fullName && fullName.includes(" ")) {
const namesArr = fullName.split(" ");
let initials = namesArr
.map((name: string) => name.charAt(0))
.join("")
.toUpperCase();
initials = initials;
inits = initials.slice(0, 2);
} else {
// handle for camelCase
const str = fullName ? fullName.replace(/([a-z])([A-Z])/g, "$1 $2") : "";
const namesArr = str.split(" ");
const initials = namesArr
.map((name: string) => name.charAt(0))
.join("")
.toUpperCase();
inits = initials.slice(0, 2);
}
return inits;
};
export const getInitialsAndColorCode = (
fullName = "",
colorPalette: string[],
): string[] => {
const initials = getInitialsFromName(fullName);
const colorCode = getColorCode(initials, colorPalette);
return [initials, colorCode];
};
export const getInitials = (
// colorPalette: string[],
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fullName: any,
): string => {
let inits = "";
// if name contains space. eg: "Full Name"
if (fullName && fullName.includes(" ")) {
const namesArr = fullName.split(" ");
let initials = namesArr.map((name: string) => name.charAt(0));
initials = initials.join("").toUpperCase();
inits = initials.slice(0, 2);
} else {
// handle for camelCase
const str = fullName ? fullName.replace(/([a-z])([A-Z])/g, "$1 $2") : "";
const namesArr = str.split(" ");
let initials = namesArr.map((name: string) => name.charAt(0));
initials = initials.join("").toUpperCase();
inits = initials.slice(0, 2);
}
// const colorCode = getColorCode(inits, colorPalette);
return inits;
};
export const getColorCode = (
initials: string,
colorPalette: string[],
): string => {
let asciiSum = 0;
for (let i = 0; i < initials.length; i++) {
asciiSum += initials[i].charCodeAt(0);
}
return colorPalette[asciiSum % colorPalette.length];
};
export const getApplicationIcon = (initials: string): AppIconName => {
let asciiSum = 0;
for (let i = 0; i < initials.length; i++) {
asciiSum += initials[i].charCodeAt(0);
}
return AppIconCollection[asciiSum % AppIconCollection.length];
};
export function hexToRgb(hex: string): {
r: number;
g: number;
b: number;
} {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: {
r: -1,
g: -1,
b: -1,
};
}
/*
* Function to call the given function until the promise it returns resolves or the max retries are reached
*
* @param fn - function that returns a promise
* @param retriesLeft - number of retries
* @param interval - interval between retries
* @param shouldRetry - function to determine if the promise should be retried, helpful when we want to retry only on specific errors
* @returns Promise
*
*/
export const retryPromise = async (
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fn: () => Promise<any>,
retriesLeft = 5,
interval = 1000,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
shouldRetry = (e: Error) => true, // default to retry on all errors
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch((e) => {
if (shouldRetry(e)) {
setTimeout(async () => {
if (retriesLeft === 1) {
reject({
code: ERROR_CODES.SERVER_ERROR,
message: createMessage(ERROR_500),
show: false,
});
return;
}
// Passing on "reject" is the important part
retryPromise(fn, retriesLeft - 1, interval).then(resolve, reject);
}, interval);
}
});
});
};
export const getRandomPaletteColor = (colorPalette: string[]) => {
return colorPalette[Math.floor(Math.random() * colorPalette.length)];
};
export const isBlobUrl = (url: string) => {
return typeof url === "string" && url.startsWith("blob:");
};
/**
*
* @param data string file data
* @param type string file type
* @returns string containing blob id and type
*/
export const createBlobUrl = (data: Blob | MediaSource, type: string) => {
let url = URL.createObjectURL(data);
url = url.replace(`${window.location.origin}/`, "");
return `${url}?type=${type}`;
};
/**
*
* @param blobId string blob id along with type.
* @returns [string,string] [blobUrl, type]
*/
export const parseBlobUrl = (blobId: string) => {
const url = `blob:${window.location.origin}/${blobId.substring(5)}`;
return url.split("?type=");
};
/**
* Convert a string into camelCase
* @param sourceString input string
* @returns camelCase string
*/
export const getCamelCaseString = (sourceString: string) => {
let out = "";
// Split the input string to separate words using RegEx
const regEx =
/[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
const words = sourceString.match(regEx);
if (words) {
words.forEach(function (el, idx) {
const add = el.toLowerCase();
out += idx === 0 ? add : add[0].toUpperCase() + add.slice(1);
});
}
return out;
};
/**
* Convert Base64 string to Blob
* @param base64Data
* @param contentType
* @param sliceSize
* @returns
*/
export const base64ToBlob = (
base64Data: string,
contentType = "",
sliceSize = 512,
) => {
const byteCharacters = atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
};
// util function to detect current os is Mac
export const isMacOs = () => {
return osName === "Mac OS";
};
/**
* checks if array of strings are equal regardless of order
* @param arr1
* @param arr2
* @returns
*/
export function areArraysEqual(arr1: string[], arr2: string[]) {
if (arr1.length !== arr2.length) return false;
// Because the array is frozen in strict mode, you'll need to copy the array before sorting it
return [...arr1].sort().every((val, i) => val === [...arr2].sort()[i]);
}
export enum DataType {
OBJECT = "OBJECT",
NUMBER = "NUMBER",
ARRAY = "ARRAY",
BOOLEAN = "BOOLEAN",
STRING = "STRING",
NULL = "NULL",
UNDEFINED = "UNDEFINED",
}
export function getDatatype(value: unknown) {
if (typeof value === "string") {
return DataType.STRING;
} else if (typeof value === "number") {
return DataType.NUMBER;
} else if (typeof value === "boolean") {
return DataType.BOOLEAN;
} else if (isPlainObject(value)) {
return DataType.OBJECT;
} else if (Array.isArray(value)) {
return DataType.ARRAY;
} else if (value === null) {
return DataType.NULL;
} else if (value === undefined) {
return DataType.UNDEFINED;
}
}