-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutil.ts
More file actions
630 lines (535 loc) · 15.8 KB
/
util.ts
File metadata and controls
630 lines (535 loc) · 15.8 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
import { html, isServer, nothing, type TemplateResult } from 'lit';
import type IgcFileInputComponent from '../file-input/file-input.js';
export const asPercent = (part: number, whole: number) => (part / whole) * 100;
export const clamp = (number: number, min: number, max: number) =>
Math.max(min, Math.min(number, max));
export function numberOfDecimals(number: number): number {
const [_, decimals] = number.toString().split('.');
return decimals ? decimals.length : 0;
}
export function roundPrecise(number: number, magnitude = 1): number {
const factor = 10 ** magnitude;
return Math.round(number * factor) / factor;
}
export function numberInRangeInclusive(
value: number,
min: number,
max: number
) {
return value >= min && value <= max;
}
/**
* Returns whether an element has a Left-to-Right directionality.
*/
export function isLTR(element: HTMLElement) {
return element.matches(':dir(ltr)');
}
/**
* Builds a string from format specifiers and replacement parameters.
* Will coerce non-string parameters to their string representations.
*
* @example
* ```typescript
* formatString('{0} says "{1}".', 'John', 'Hello'); // 'John says "Hello".'
* formatString('{1} is greater than {0}', 0, 1); // '1 is greater than 0'
* ```
*/
export function formatString(template: string, ...params: unknown[]): string {
const length = params.length;
return template.replace(/{(\d+)}/g, (match: string, index: number) =>
index >= length ? match : `${params[index]}`
);
}
/**
* Parse the passed `value` as a number or return the `fallback` if it can't be done.
*
* @example
* ```typescript
* asNumber('5'); // 5
* asNumber('3.14'); // 3.14
* asNumber('five'); // 0
* asNUmber('five', 5); // 5
* ```
*/
export function asNumber(value: unknown, fallback = 0) {
const parsed = Number.parseFloat(value as string);
return Number.isNaN(parsed) ? fallback : parsed;
}
/**
* Returns the value wrapped between the min and max bounds.
*
* If the value is greater than max, returns the min and vice-versa.
* If the value is between the bounds, it is returned unchanged.
*
* @example
* ```typescript
* wrap(1, 4, 2); // 2
* wrap(1, 4, 5); // 1
* wrap(1, 4, -1); // 4
* ```
*/
export function wrap(min: number, max: number, value: number) {
if (value < min) {
return max;
}
if (value > max) {
return min;
}
return value;
}
export function isDefined<T = unknown>(value: T) {
return value !== undefined;
}
export type IterNodesOptions<T = Node> = {
show?: keyof typeof NodeFilter;
filter?: (node: T) => boolean;
};
function createNodeFilter<T extends Node>(predicate: (node: T) => boolean) {
return {
acceptNode: (node: T): number =>
!predicate || predicate(node)
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_SKIP,
};
}
export function* iterNodes<T extends Node>(
root: Node,
options?: IterNodesOptions<T>
): Generator<T> {
if (!isDefined(globalThis.document)) {
return;
}
const whatToShow = options?.show
? NodeFilter[options.show]
: NodeFilter.SHOW_ALL;
const nodeFilter = options?.filter
? createNodeFilter(options.filter)
: undefined;
const treeWalker = document.createTreeWalker(root, whatToShow, nodeFilter);
while (treeWalker.nextNode()) {
yield treeWalker.currentNode as T;
}
}
export function getRoot(
element: Element,
options?: GetRootNodeOptions
): Document | ShadowRoot {
return element.getRootNode(options) as Document | ShadowRoot;
}
export function getElementByIdFromRoot(root: HTMLElement, id: string) {
return getRoot(root).getElementById(id);
}
export function isElement(node: unknown): node is Element {
return node instanceof Node && node.nodeType === Node.ELEMENT_NODE;
}
export function findElementFromEventPath<K extends keyof HTMLElementTagNameMap>(
predicate: K,
event: Event
): HTMLElementTagNameMap[K] | undefined;
export function findElementFromEventPath<T extends Element>(
predicate: string | ((element: Element) => boolean),
event: Event
): T | undefined;
export function findElementFromEventPath(
predicate: string | ((element: Element) => boolean),
event: Event
) {
const func = isString(predicate)
? (e: Element) => e.matches(predicate)
: (e: Element) => predicate(e);
return Iterator.from(event.composedPath()).find(
(item) => isElement(item) && func(item)
) as Element | undefined;
}
export function first<T>(arr: T[]) {
return arr.at(0) as T;
}
export function last<T>(arr: T[]) {
return arr.at(-1) as T;
}
export function modulo(n: number, d: number) {
return ((n % d) + d) % d;
}
/**
* Splits an array into chunks of a specified size and returns a generator that yields each chunk.
*
* @example
* ```typescript
* [...chunk([1, 2, 3, 4, 5], 2)]; // [[1, 2], [3, 4], [5]]
* ```
*
* @throws If the `size` parameter is not a safe integer greater than or equal to 1.
*/
export function* chunk<T>(arr: T[], size: number): Generator<T[]> {
if (!Number.isSafeInteger(size) || size < 1) {
throw new Error('size must be an integer >= 1');
}
const iterator = Iterator.from(arr);
const length = arr.length;
let i = 0;
while (i < length) {
yield iterator.take(size).toArray();
i += size;
}
}
export function splitToWords(text: string) {
const input = text.replaceAll(/[^a-zA-Z0-9\s-_]/g, '');
if (/[\s-_]+/.test(input)) return input.split(/[\s-_]+/);
return input.split(/(?=[A-Z])+/);
}
export function toKebabCase(text: string): string {
const input = text.trim();
return splitToWords(input).join('-').toLocaleLowerCase();
}
export function isFunction(value: unknown): value is CallableFunction {
return typeof value === 'function';
}
export function isString(value: unknown): value is string {
return typeof value === 'string';
}
export function isObject(value: unknown): value is object {
return value != null && typeof value === 'object';
}
export function isPlainObject(
value: unknown
): value is Record<PropertyKey, unknown> {
if (!isObject(value)) {
return false;
}
const proto = Object.getPrototypeOf(value) as typeof Object.prototype | null;
const hasObjectPrototype =
proto === null ||
proto === Object.prototype ||
Object.getPrototypeOf(proto) === null;
return hasObjectPrototype
? Object.prototype.toString.call(value) === '[object Object]'
: false;
}
function isUnsafeProperty(key: PropertyKey) {
return key === '__proto__' || key === 'constructor' || key === 'prototype';
}
export function isEventListenerObject(x: unknown): x is EventListenerObject {
return isObject(x) && 'handleEvent' in x;
}
export function addWeakEventListener(
element: Element,
event: string,
listener: EventListenerOrEventListenerObject,
options?: AddEventListenerOptions | boolean
): void {
const weakRef = new WeakRef(listener);
const wrapped = (evt: Event) => {
const handler = weakRef.deref();
return isEventListenerObject(handler)
? handler.handleEvent(evt)
: handler?.(evt);
};
element.addEventListener(event, wrapped, options);
}
type EventTypeOf<T extends keyof HTMLElementEventMap | keyof WindowEventMap> =
(HTMLElementEventMap & WindowEventMap)[T];
/**
* Safely adds an event listener to an HTMLElement, automatically handling
* server-side rendering environments by doing nothing if `isServer` is true.
* This function also correctly binds the `handler`'s `this` context to the `target` element
* and ensures proper event type inference.
*/
export function addSafeEventListener<
E extends keyof HTMLElementEventMap | keyof WindowEventMap,
>(
target: HTMLElement,
eventName: E,
handler: (event: EventTypeOf<E>) => unknown,
options?: boolean | AddEventListenerOptions
): void {
if (isServer) {
return;
}
const boundHandler = (event: Event) =>
handler.call(target, event as EventTypeOf<E>);
target.addEventListener(eventName, boundHandler, options);
}
/**
* Returns whether a given collection is empty.
*/
export function isEmpty<T, U extends object>(
x: ArrayLike<T> | Set<T> | Map<U, T>
): boolean {
return 'length' in x ? x.length < 1 : x.size < 1;
}
export function asArray<T>(value?: T | T[]): T[] {
if (!isDefined(value)) return [];
return Array.isArray(value) ? value : [value];
}
export function partition<T>(
array: T[],
isTruthy: (value: T) => boolean
): [truthy: T[], falsy: T[]] {
const truthy: T[] = [];
const falsy: T[] = [];
for (const item of array) {
(isTruthy(item) ? truthy : falsy).push(item);
}
return [truthy, falsy];
}
/** Returns the center x/y coordinate of a given element. */
export function getCenterPoint(element: Element): { x: number; y: number } {
const { left, top, width, height } = element.getBoundingClientRect();
return {
x: left + width * 0.5,
y: top + height * 0.5,
};
}
/** Returns the scale factor of a given element based on its bounding client rect and offset dimensions. */
export function getScaleFactor(element: HTMLElement): { x: number; y: number } {
const { offsetWidth, offsetHeight } = element;
const { width, height } = element.getBoundingClientRect();
return { x: offsetWidth / width || 1, y: offsetHeight / height || 1 };
}
export function roundByDPR(value: number): number {
const dpr = globalThis.devicePixelRatio || 1;
return Math.round(value * dpr) / dpr;
}
export function scrollIntoView(
element?: HTMLElement | null,
config?: ScrollIntoViewOptions
): void {
if (!element) {
return;
}
element.scrollIntoView(
Object.assign(
{
behavior: 'auto',
block: 'nearest',
inline: 'nearest',
},
config
)
);
}
export function isRegExp(value: unknown): value is RegExp {
return value != null && value.constructor === RegExp;
}
export function equal<T>(a: unknown, b: T, visited = new WeakSet()): boolean {
// Early return
if (Object.is(a, b)) {
return true;
}
if (isObject(a) && isObject(b)) {
if (a.constructor !== b.constructor) {
return false;
}
// Circular references
if (visited.has(a) && visited.has(b)) {
return true;
}
visited.add(a);
visited.add(b);
// RegExp
if (isRegExp(a) && isRegExp(b)) {
return a.source === b.source && a.flags === b.flags;
}
// Maps
if (a instanceof Map && b instanceof Map) {
if (a.size !== b.size) {
return false;
}
for (const [keyA, valueA] of a.entries()) {
let found = false;
for (const [keyB, valueB] of b.entries()) {
if (equal(keyA, keyB, visited) && equal(valueA, valueB, visited)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
// Sets
if (a instanceof Set && b instanceof Set) {
if (a.size !== b.size) {
return false;
}
for (const valueA of a) {
let found = false;
for (const valueB of b) {
if (equal(valueA, valueB, visited)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
// Arrays
if (Array.isArray(a) && Array.isArray(b)) {
const length = a.length;
if (length !== b.length) {
return false;
}
for (let i = 0; i < length; i++) {
if (!equal(a[i], b[i], visited)) {
return false;
}
}
return true;
}
// toPrimitive
if (a.valueOf !== Object.prototype.valueOf) {
return a.valueOf() === b.valueOf();
}
// Strings based
if (a.toString !== Object.prototype.toString) {
return a.toString() === b.toString();
}
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (const key of aKeys) {
if (!Object.hasOwn(b, key)) {
return false;
}
}
for (const key of aKeys) {
if (!equal(a[key as keyof typeof a], b[key as keyof typeof b], visited)) {
return false;
}
}
visited.delete(a);
visited.delete(b);
return true;
}
return false;
}
/**
* Escapes any potential regex syntax characters in a string, and returns a new string
* that can be safely used as a literal pattern for the `RegExp()` constructor.
*
* @remarks
* Substitute with `RegExp.escape` once it has enough support:
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape#browser_compatibility
*/
export function escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/** Required utility type for specific props */
export type RequiredProps<T, K extends keyof T> = T & {
[P in K]-?: T[P];
};
export function setStyles(
element: HTMLElement,
styles: Partial<CSSStyleDeclaration>
): void {
merge(element.style, styles);
}
/**
* Merges the properties of `source` into `target` performing a recursive deep merge over POJOs and arrays.
*
* @remarks
* This function mutates the `target` object.
* If that is not the desired outcome, see {@link toMerged} for another approach.
*/
export function merge<
T extends Record<PropertyKey, any>,
S extends Record<PropertyKey, any>,
>(target: T, source: S): T & S {
const sourceKeys = Object.keys(source) as Array<keyof S>;
const length = sourceKeys.length;
for (let i = 0; i < length; i++) {
const key = sourceKeys[i];
if (isUnsafeProperty(key)) {
continue;
}
const sourceValue = source[key];
const targetValue = target[key];
if (Array.isArray(sourceValue)) {
if (Array.isArray(targetValue)) {
target[key] = merge(targetValue, sourceValue);
} else {
target[key] = merge([], sourceValue);
}
} else if (isPlainObject(sourceValue)) {
if (isPlainObject(targetValue)) {
target[key] = merge(targetValue, sourceValue);
} else {
target[key] = merge({}, sourceValue);
}
} else if (targetValue === undefined || sourceValue !== undefined) {
target[key] = sourceValue;
}
}
return target;
}
/**
* Just like {@link merge} but it does not mutate the `target` object instead
* mutating a structured clone of it.
*/
export function toMerged<
T extends Record<PropertyKey, any>,
S extends Record<PropertyKey, any>,
>(target: T, source: S): T & S {
return merge(structuredClone(target), source);
}
/**
* Similar to Lit's `ifDefined` directive except one can check `assertion`
* and bind a different `value` through this wrapper.
*/
export function bindIf<T>(assertion: unknown, value: T): NonNullable<T> {
return assertion
? (value ?? (nothing as NonNullable<T>))
: (nothing as NonNullable<T>);
}
let pool: Uint8Array<ArrayBuffer>;
let poolOffset: number;
const urlAlphabet =
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
function fillPool(bytes: number): void {
if (!pool || pool.length < bytes) {
pool = new Uint8Array(new ArrayBuffer(bytes * 128));
crypto.getRandomValues(pool);
poolOffset = 0;
} else if (poolOffset + bytes > pool.length) {
crypto.getRandomValues(pool);
poolOffset = 0;
}
poolOffset += bytes;
}
export function nanoid(size = 21): string {
const bytes = size | 0;
fillPool(bytes);
let id = '';
for (let i = poolOffset - bytes; i < poolOffset; i++) {
id += urlAlphabet[pool[i] & 63];
}
return id;
}
export function hasFiles(
input: HTMLInputElement | IgcFileInputComponent
): boolean {
return input.files != null && input.files.length > 0;
}
const trimmedCache = new WeakMap<TemplateStringsArray, TemplateStringsArray>();
/** @internal */
export function trimmedHtml(
strings: TemplateStringsArray,
...values: unknown[]
): TemplateResult {
if (!trimmedCache.has(strings)) {
const trimmedStrings = strings.map((s) => s.trim().replaceAll('\n', ''));
trimmedCache.set(
strings,
Object.assign([...trimmedStrings], { raw: [...strings.raw] })
);
}
return html(trimmedCache.get(strings)!, ...values);
}