-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathutils.js
More file actions
275 lines (248 loc) · 9.15 KB
/
utils.js
File metadata and controls
275 lines (248 loc) · 9.15 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
/**
* @license
* Copyright 2019-2020 CERN and copyright holders of ALICE O2.
* See http://alice-o2.web.cern.ch/copyright for details of the copyright holders.
* All rights not expressly granted are reserved.
*
* This software is distributed under the terms of the GNU General Public
* License v3 (GPL Version 3), copied verbatim in the file "COPYING".
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
import { isUserRoleSufficient } from '../../../../library/userRole.enum.js';
import { generateDrawingOptionString } from '../../library/qcObject/utils.js';
import { RootImageDownloadSupportedTypes } from './enums/rootImageMimes.enum.js';
/* global JSROOT BOOKKEEPING */
/**
* Generates a new ObjectId
* @returns {string} 16 random chars, base 16
*/
export function objectId() {
const timestamp = (new Date().getTime() / 1000 | 0).toString(16);
return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, () => (Math.random() * 16 | 0).toString(16)).toLowerCase();
}
/**
* Make a deep clone of object provided
* @param {object} obj - to be cloned
* @returns {object} a deep copy
*/
export function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// Map storing timers per key
const simpleDebouncerTimers = new Map();
/**
* Produces a debounced function that uses a key to manage timers.
* Each key has its own debounce timer, so calls with different keys
* are debounced independently.
* @template PrimitiveKey extends unknown
* @param {PrimitiveKey} key - The key for this call.
* @param {(key: PrimitiveKey) => void} fn - Function to debounce.
* @param {number} time - Debounce delay in milliseconds.
* @returns {undefined}
*/
export function simpleDebouncer(key, fn, time) {
if (simpleDebouncerTimers.has(key)) {
clearTimeout(simpleDebouncerTimers.get(key));
}
const timerId = setTimeout(() => {
fn(key);
simpleDebouncerTimers.delete(key);
}, time);
simpleDebouncerTimers.set(key, timerId);
}
/**
* Produces a lambda function waiting `time` ms before calling fn.
* No matter how many calls are done to lambda, the last call is the waiting starting point.
* @template K, A extends unknown[]
* @param {(...args: A) => WeakKey} keyFn - Function that returns the key to debounce by.
* @param {(...args: A) => void} debounceFn - Function executed after the debounce delay.
* @param {number} time - Debounce delay in milliseconds.
* @param {(...args: A) => void} [onFirstCall = () => {}] - Optional callback fired once when a new key is added.
* @returns {(...args: A) => void} - Debounced function that can be called multiple times.
*/
export function keyedTimerDebouncer(
keyFn,
debounceFn,
time,
onFirstCall = () => {},
) {
const timers = new WeakMap();
return function (...args) {
const key = keyFn(...args);
if (timers.has(key)) {
clearTimeout(timers.get(key));
} else {
onFirstCall(...args);
}
const timerId = setTimeout(() => {
debounceFn(...args);// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
timers.delete(key);
}, time);
timers.set(key, timerId);
};
}
const pointers = new WeakMap();
let currentAddress = 0;
/**
* Generates a unique number for the provided object like a pointer or id
* Two calls with the same object will provide the same number.
* Uses a WeekMap so no memory leak.
* @param {object} obj - the object that needs to be identified
* @returns {number} a unique pointer number
*/
export function pointerId(obj) {
let ptr = pointers.get(obj);
if (!ptr) {
ptr = currentAddress++;
pointers.set(obj, ptr);
}
return ptr;
}
/**
* Given a string-date or number-timestamp (ms), return it in a format approved by ALICE for QC
* e.g. 7 Mar 2022, 19:08 CET / 18:08 UTC
* If the passed parameter is not a date-valid format, a string 'Invalid Date' will be returned
* @param {string|number} date - value of date to be parsed
* @returns {string} - string representation of the 2 date values combined
*/
export function prettyFormatDate(date) {
try {
if (date) {
return `${new Date(date).toLocaleString('en-GB', {
timeZoneName: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})} / ${new Date(date).toLocaleString('en-GB', {
timeZone: 'UTC',
timeZoneName: 'short',
hour: '2-digit',
minute: '2-digit',
})}`;
} else {
return '-';
}
} catch {
return 'Invalid Date';
}
}
/**
* Given a string, it will attempt to update the tab title if the `document` object exists
* @param {string} title - name that should be updating the browser tab
* @returns {void}
*/
export function setBrowserTabTitle(title = undefined) {
if (document && title) {
document.title = title;
}
}
/**
* Checks if any role in the provided list meets or exceeds the required permission level
* @param {Array<UserRole>} userRoles - List of roles assigned to the user
* @param {UserRole} requiredRole - Minimum role level needed for authorization
* @returns {boolean} True if at least one user role meets or exceeds the required role level
*/
export function hasMinimumRoleAccess(userRoles, requiredRole) {
return userRoles.some((role) => isUserRoleSufficient(role, requiredRole));
}
/**
* Asynchronously writes the given text value to the system clipboard
* @param {string} value - The text string to be copied to the clipboard
* @returns {Promise<void>} - A Promise that resolves with no value when the text has been successfully copied.
* The promise is rejected if the operation fails (e.g., due to lack of user permission
* or an insecure context)
*/
export function copyToClipboard(value) {
return navigator.clipboard.writeText(value);
}
/**
* Converts a camelCase string to a human-readable Title Case string.
* It inserts a space before every uppercase letter and uppercase the
* first character of the resulting string.
* @param {string} text - the camelCase string to tranform (e.g. 'lastModified')
* @returns {string} - the formatted Title Case string (e.g. `Last Modified')
*/
export const camelToTitleCase = (text) => {
const spaced = text.replace(/([A-Z])/g, ' $1');
const titleCase = spaced.charAt(0).toUpperCase() + spaced.slice(1);
return titleCase;
};
/**
* Helper to trigger a download for a file
* @param {string} url - The URL to the file source
* @param {string} filename - The name of the file including the file extension
* @returns {undefined}
*/
export const triggerDownload = (url, filename) => {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
};
/**
* Downloads a file
* @param {Blob|MediaSource} file - The file to download
* @param {string} filename - The name of the file including the file extension
* @returns {undefined}
*/
export const downloadFile = (file, filename) => {
const url = URL.createObjectURL(file);
try {
triggerDownload(url, filename);
} finally {
URL.revokeObjectURL(url);
}
};
/**
* Generates a rasterized image of a JSROOT RootObject and triggers download.
* @param {string} filename - The name of the downloaded file excluding the file extension.
* @param {string} filetype - The file extension of the downloaded file.
* @param {RootObject} root - The JSROOT RootObject to render.
* @param {string[]} [drawingOptions=[]] - Optional array of JSROOT drawing options.
* @returns {undefined}
*/
export const downloadRoot = async (filename, filetype, root, drawingOptions = []) => {
const mime = RootImageDownloadSupportedTypes[filetype.toLocaleUpperCase()];
if (!mime) {
throw new Error(`The file extension (${filetype}) is not supported`);
}
const image = await JSROOT.makeImage({
object: root,
option: generateDrawingOptionString(root, drawingOptions),
format: filetype,
as_buffer: true,
});
const blob = new Blob([image], { type: mime });
downloadFile(blob, `${filename}.${filetype}`);
};
/**
* Determines whether the element is positioned on the left half of the viewport.
* This is used to decide which way a dropdown should anchor to stay within view.
* @param {HTMLElement} element - The DOM element (usually the button or container) to measure.
* @returns {boolean|undefined} Returns true if the element is on the left half of the window,
* false if it is on the right half, or undefined if no element is provided.
*/
export const isOnLeftSideOfViewport = (element) => {
if (!element) {
return;
}
const rect = element.getBoundingClientRect();
const isLeft = rect.left - rect.width < window.innerWidth / 2;
return isLeft;
};
/**
* Retrieves the URL to the run details page in Bookkeeping for the given run number
* @param {number|string} runNumber - The run number to generate the URL for
* @returns {string|null} The URL to the run details page, or null if Bookkeeping is not configured
*/
export const getBkpRunDetailsUrl = (runNumber) => {
if (typeof BOOKKEEPING !== 'undefined' && BOOKKEEPING && BOOKKEEPING.RUN_DETAILS) {
return BOOKKEEPING.RUN_DETAILS + runNumber;
}
return null;
};