-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathutil.ts
1812 lines (1667 loc) · 48.1 KB
/
util.ts
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
// utility functions
// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
const ASPDateRegex = /^\/?Date\((-?\d+)/i;
// Color REs
const fullHexRE = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
const shortHexRE = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const rgbRE =
/^rgb\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *\)$/i;
const rgbaRE =
/^rgba\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *([01]|0?\.\d+) *\)$/i;
/**
* Hue, Saturation, Value.
*/
export interface HSV {
/**
* Hue \<0, 1\>.
*/
h: number;
/**
* Saturation \<0, 1\>.
*/
s: number;
/**
* Value \<0, 1\>.
*/
v: number;
}
/**
* Red, Green, Blue.
*/
export interface RGB {
/**
* Red \<0, 255\> integer.
*/
r: number;
/**
* Green \<0, 255\> integer.
*/
g: number;
/**
* Blue \<0, 255\> integer.
*/
b: number;
}
/**
* Red, Green, Blue, Alpha.
*/
export interface RGBA {
/**
* Red \<0, 255\> integer.
*/
r: number;
/**
* Green \<0, 255\> integer.
*/
g: number;
/**
* Blue \<0, 255\> integer.
*/
b: number;
/**
* Alpha \<0, 1\>.
*/
a: number;
}
/**
* Test whether given object is a number.
*
* @param value - Input value of unknown type.
* @returns True if number, false otherwise.
*/
export function isNumber(value: unknown): value is number {
return value instanceof Number || typeof value === "number";
}
/**
* Remove everything in the DOM object.
*
* @param DOMobject - Node whose child nodes will be recursively deleted.
*/
export function recursiveDOMDelete(DOMobject: Node | null | undefined): void {
if (DOMobject) {
while (DOMobject.hasChildNodes() === true) {
const child = DOMobject.firstChild;
if (child) {
recursiveDOMDelete(child);
DOMobject.removeChild(child);
}
}
}
}
/**
* Test whether given object is a string.
*
* @param value - Input value of unknown type.
* @returns True if string, false otherwise.
*/
export function isString(value: unknown): value is string {
return value instanceof String || typeof value === "string";
}
/**
* Test whether given object is a object (not primitive or null).
*
* @param value - Input value of unknown type.
* @returns True if not null object, false otherwise.
*/
export function isObject(value: unknown): value is object {
return typeof value === "object" && value !== null;
}
/**
* Test whether given object is a Date, or a String containing a Date.
*
* @param value - Input value of unknown type.
* @returns True if Date instance or string date representation, false otherwise.
*/
export function isDate(value: unknown): value is Date | string {
if (value instanceof Date) {
return true;
} else if (isString(value)) {
// test whether this string contains a date
const match = ASPDateRegex.exec(value);
if (match) {
return true;
} else if (!isNaN(Date.parse(value))) {
return true;
}
}
return false;
}
/**
* Copy property from b to a if property present in a.
* If property in b explicitly set to null, delete it if `allowDeletion` set.
*
* Internal helper routine, should not be exported. Not added to `exports` for that reason.
*
* @param a - Target object.
* @param b - Source object.
* @param prop - Name of property to copy from b to a.
* @param allowDeletion - If true, delete property in a if explicitly set to null in b.
*/
function copyOrDelete(
a: any,
b: any,
prop: string,
allowDeletion: boolean
): void {
let doDeletion = false;
if (allowDeletion === true) {
doDeletion = b[prop] === null && a[prop] !== undefined;
}
if (doDeletion) {
delete a[prop];
} else {
a[prop] = b[prop]; // Remember, this is a reference copy!
}
}
/**
* Fill an object with a possibly partially defined other object.
*
* Only copies values for the properties already present in a.
* That means an object is not created on a property if only the b object has it.
*
* @param a - The object that will have it's properties updated.
* @param b - The object with property updates.
* @param allowDeletion - If true, delete properties in a that are explicitly set to null in b.
*/
export function fillIfDefined<T extends object>(
a: T,
b: Partial<T>,
allowDeletion = false
): void {
// NOTE: iteration of properties of a
// NOTE: prototype properties iterated over as well
for (const prop in a) {
if (b[prop] !== undefined) {
if (b[prop] === null || typeof b[prop] !== "object") {
// Note: typeof null === 'object'
copyOrDelete(a, b, prop, allowDeletion);
} else {
const aProp = a[prop];
const bProp = b[prop];
if (isObject(aProp) && isObject(bProp)) {
fillIfDefined(aProp, bProp, allowDeletion);
}
}
}
}
}
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
*
* @param target - The target object to copy to.
* @param source - The source object from which to copy properties.
* @returns The target object.
*/
export const extend = Object.assign;
/**
* Extend object a with selected properties of object b or a series of objects.
*
* @remarks
* Only properties with defined values are copied.
* @param props - Properties to be copied to a.
* @param a - The target.
* @param others - The sources.
* @returns Argument a.
*/
export function selectiveExtend(
props: string[],
a: any,
...others: any[]
): any {
if (!Array.isArray(props)) {
throw new Error("Array with property names expected as first argument");
}
for (const other of others) {
for (let p = 0; p < props.length; p++) {
const prop = props[p];
if (other && Object.prototype.hasOwnProperty.call(other, prop)) {
a[prop] = other[prop];
}
}
}
return a;
}
/**
* Extend object a with selected properties of object b.
* Only properties with defined values are copied.
*
* @remarks
* Previous version of this routine implied that multiple source objects could
* be used; however, the implementation was **wrong**. Since multiple (\>1)
* sources weren't used anywhere in the `vis.js` code, this has been removed
* @param props - Names of first-level properties to copy over.
* @param a - Target object.
* @param b - Source object.
* @param allowDeletion - If true, delete property in a if explicitly set to null in b.
* @returns Argument a.
*/
export function selectiveDeepExtend(
props: string[],
a: any,
b: any,
allowDeletion = false
): any {
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError("Arrays are not supported by deepExtend");
}
for (let p = 0; p < props.length; p++) {
const prop = props[p];
if (Object.prototype.hasOwnProperty.call(b, prop)) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
deepExtend(a[prop], b[prop], false, allowDeletion);
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
throw new TypeError("Arrays are not supported by deepExtend");
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
}
return a;
}
/**
* Extend object `a` with properties of object `b`, ignoring properties which
* are explicitly specified to be excluded.
*
* @remarks
* The properties of `b` are considered for copying. Properties which are
* themselves objects are are also extended. Only properties with defined
* values are copied.
* @param propsToExclude - Names of properties which should *not* be copied.
* @param a - Object to extend.
* @param b - Object to take properties from for extension.
* @param allowDeletion - If true, delete properties in a that are explicitly
* set to null in b.
* @returns Argument a.
*/
export function selectiveNotDeepExtend(
propsToExclude: string[],
a: any,
b: any,
allowDeletion = false
): any {
// TODO: add support for Arrays to deepExtend
// NOTE: array properties have an else-below; apparently, there is a problem here.
if (Array.isArray(b)) {
throw new TypeError("Arrays are not supported by deepExtend");
}
for (const prop in b) {
if (!Object.prototype.hasOwnProperty.call(b, prop)) {
continue;
} // Handle local properties only
if (propsToExclude.includes(prop)) {
continue;
} // In exclusion list, skip
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
deepExtend(a[prop], b[prop]); // NOTE: allowDeletion not propagated!
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
a[prop] = [];
for (let i = 0; i < b[prop].length; i++) {
a[prop].push(b[prop][i]);
}
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
return a;
}
/**
* Deep extend an object a with the properties of object b.
*
* @param a - Target object.
* @param b - Source object.
* @param protoExtend - If true, the prototype values will also be extended.
* (That is the options objects that inherit from others will also get the
* inherited options).
* @param allowDeletion - If true, the values of fields that are null will be deleted.
* @returns Argument a.
*/
export function deepExtend(
a: any,
b: any,
protoExtend = false,
allowDeletion = false
): any {
for (const prop in b) {
if (Object.prototype.hasOwnProperty.call(b, prop) || protoExtend === true) {
if (
typeof b[prop] === "object" &&
b[prop] !== null &&
Object.getPrototypeOf(b[prop]) === Object.prototype
) {
if (a[prop] === undefined) {
a[prop] = deepExtend({}, b[prop], protoExtend); // NOTE: allowDeletion not propagated!
} else if (
typeof a[prop] === "object" &&
a[prop] !== null &&
Object.getPrototypeOf(a[prop]) === Object.prototype
) {
deepExtend(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
a[prop] = b[prop].slice();
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
}
return a;
}
/**
* Test whether all elements in two arrays are equal.
*
* @param a - First array.
* @param b - Second array.
* @returns True if both arrays have the same length and same elements (1 = '1').
*/
export function equalArray(a: unknown[], b: unknown[]): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0, len = a.length; i < len; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
/**
* Get the type of an object, for example exports.getType([]) returns 'Array'.
*
* @param object - Input value of unknown type.
* @returns Detected type.
*/
export function getType(object: unknown): string {
const type = typeof object;
if (type === "object") {
if (object === null) {
return "null";
}
if (object instanceof Boolean) {
return "Boolean";
}
if (object instanceof Number) {
return "Number";
}
if (object instanceof String) {
return "String";
}
if (Array.isArray(object)) {
return "Array";
}
if (object instanceof Date) {
return "Date";
}
return "Object";
}
if (type === "number") {
return "Number";
}
if (type === "boolean") {
return "Boolean";
}
if (type === "string") {
return "String";
}
if (type === undefined) {
return "undefined";
}
return type;
}
export function copyAndExtendArray<T>(arr: ReadonlyArray<T>, newValue: T): T[];
export function copyAndExtendArray<A, V>(
arr: ReadonlyArray<A>,
newValue: V
): (A | V)[];
/**
* Used to extend an array and copy it. This is used to propagate paths recursively.
*
* @param arr - First part.
* @param newValue - The value to be aadded into the array.
* @returns A new array with all items from arr and newValue (which is last).
*/
export function copyAndExtendArray<A, V>(
arr: ReadonlyArray<A>,
newValue: V
): (A | V)[] {
return [...arr, newValue];
}
/**
* Used to extend an array and copy it. This is used to propagate paths recursively.
*
* @param arr - The array to be copied.
* @returns Shallow copy of arr.
*/
export function copyArray<T>(arr: ReadonlyArray<T>): T[] {
return arr.slice();
}
/**
* Retrieve the absolute left value of a DOM element.
*
* @param elem - A dom element, for example a div.
* @returns The absolute left position of this element in the browser page.
*/
export function getAbsoluteLeft(elem: Element): number {
return elem.getBoundingClientRect().left;
}
/**
* Retrieve the absolute right value of a DOM element.
*
* @param elem - A dom element, for example a div.
* @returns The absolute right position of this element in the browser page.
*/
export function getAbsoluteRight(elem: Element): number {
return elem.getBoundingClientRect().right;
}
/**
* Retrieve the absolute top value of a DOM element.
*
* @param elem - A dom element, for example a div.
* @returns The absolute top position of this element in the browser page.
*/
export function getAbsoluteTop(elem: Element): number {
return elem.getBoundingClientRect().top;
}
/**
* Add a className to the given elements style.
*
* @param elem - The element to which the classes will be added.
* @param classNames - Space separated list of classes.
*/
export function addClassName(elem: Element, classNames: string): void {
let classes = elem.className.split(" ");
const newClasses = classNames.split(" ");
classes = classes.concat(
newClasses.filter(function (className): boolean {
return !classes.includes(className);
})
);
elem.className = classes.join(" ");
}
/**
* Remove a className from the given elements style.
*
* @param elem - The element from which the classes will be removed.
* @param classNames - Space separated list of classes.
*/
export function removeClassName(elem: Element, classNames: string): void {
let classes = elem.className.split(" ");
const oldClasses = classNames.split(" ");
classes = classes.filter(function (className): boolean {
return !oldClasses.includes(className);
});
elem.className = classes.join(" ");
}
export function forEach<V>(
array: undefined | null | V[],
callback: (value: V, index: number, object: V[]) => void
): void;
export function forEach<O extends object>(
object: undefined | null | O,
callback: <Key extends keyof O>(value: O[Key], key: Key, object: O) => void
): void;
/**
* For each method for both arrays and objects.
* In case of an array, the built-in Array.forEach() is applied (**No, it's not!**).
* In case of an Object, the method loops over all properties of the object.
*
* @param object - An Object or Array to be iterated over.
* @param callback - Array.forEach-like callback.
*/
export function forEach(object: any, callback: any): void {
if (Array.isArray(object)) {
// array
const len = object.length;
for (let i = 0; i < len; i++) {
callback(object[i], i, object);
}
} else {
// object
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
}
}
/**
* Convert an object into an array: all objects properties are put into the array. The resulting array is unordered.
*
* @param o - Object that contains the properties and methods.
* @returns An array of unordered values.
*/
export const toArray = Object.values;
/**
* Update a property in an object.
*
* @param object - The object whose property will be updated.
* @param key - Name of the property to be updated.
* @param value - The new value to be assigned.
* @returns Whether the value was updated (true) or already strictly the same in the original object (false).
*/
export function updateProperty<K extends string, V>(
object: Record<K, V>,
key: K,
value: V
): boolean {
if (object[key] !== value) {
object[key] = value;
return true;
} else {
return false;
}
}
/**
* Throttle the given function to be only executed once per animation frame.
*
* @param fn - The original function.
* @returns The throttled function.
*/
export function throttle(fn: () => void): () => void {
let scheduled = false;
return (): void => {
if (!scheduled) {
scheduled = true;
requestAnimationFrame((): void => {
scheduled = false;
fn();
});
}
};
}
/**
* Cancels the event's default action if it is cancelable, without stopping further propagation of the event.
*
* @param event - The event whose default action should be prevented.
*/
export function preventDefault(event: Event | undefined): void {
if (!event) {
event = window.event;
}
if (!event) {
// No event, no work.
} else if (event.preventDefault) {
event.preventDefault(); // non-IE browsers
} else {
// @TODO: IE types? Does anyone care?
(event as any).returnValue = false; // IE browsers
}
}
/**
* Get HTML element which is the target of the event.
*
* @param event - The event.
* @returns The element or null if not obtainable.
*/
export function getTarget(
event: Event | undefined = window.event
): Element | null {
// code from http://www.quirksmode.org/js/events_properties.html
// @TODO: EventTarget can be almost anything, is it okay to return only Elements?
let target: null | EventTarget = null;
if (!event) {
// No event, no target.
} else if (event.target) {
target = event.target;
} else if (event.srcElement) {
target = event.srcElement;
}
if (!(target instanceof Element)) {
return null;
}
if (target.nodeType != null && target.nodeType == 3) {
// defeat Safari bug
target = target.parentNode;
if (!(target instanceof Element)) {
return null;
}
}
return target;
}
/**
* Check if given element contains given parent somewhere in the DOM tree.
*
* @param element - The element to be tested.
* @param parent - The ancestor (not necessarily parent) of the element.
* @returns True if parent is an ancestor of the element, false otherwise.
*/
export function hasParent(element: Element, parent: Element): boolean {
let elem: Node = element;
while (elem) {
if (elem === parent) {
return true;
} else if (elem.parentNode) {
elem = elem.parentNode;
} else {
return false;
}
}
return false;
}
export const option = {
/**
* Convert a value into a boolean.
*
* @param value - Value to be converted intoboolean, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding boolean value, if none then the default value, if none then null.
*/
asBoolean(value: unknown, defaultValue?: boolean): boolean | null {
if (typeof value == "function") {
value = value();
}
if (value != null) {
return value != false;
}
return defaultValue || null;
},
/**
* Convert a value into a number.
*
* @param value - Value to be converted intonumber, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding **boxed** number value, if none then the default value, if none then null.
*/
asNumber(value: unknown, defaultValue?: number): number | null {
if (typeof value == "function") {
value = value();
}
if (value != null) {
return Number(value) || defaultValue || null;
}
return defaultValue || null;
},
/**
* Convert a value into a string.
*
* @param value - Value to be converted intostring, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding **boxed** string value, if none then the default value, if none then null.
*/
asString(value: unknown, defaultValue?: string): string | null {
if (typeof value == "function") {
value = value();
}
if (value != null) {
return String(value);
}
return defaultValue || null;
},
/**
* Convert a value into a size.
*
* @param value - Value to be converted intosize, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding string value (number + 'px'), if none then the default value, if none then null.
*/
asSize(value: unknown, defaultValue?: string): string | null {
if (typeof value == "function") {
value = value();
}
if (isString(value)) {
return value;
} else if (isNumber(value)) {
return value + "px";
} else {
return defaultValue || null;
}
},
/**
* Convert a value into a DOM Element.
*
* @param value - Value to be converted into DOM Element, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns The DOM Element, if none then the default value, if none then null.
*/
asElement<T extends Node>(
value: T | (() => T | undefined) | undefined,
defaultValue: T
): T | null {
if (typeof value == "function") {
value = value();
}
return value || defaultValue || null;
},
};
/**
* Convert hex color string into RGB color object.
*
* @remarks
* {@link http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb}
* @param hex - Hex color string (3 or 6 digits, with or without #).
* @returns RGB color object.
*/
export function hexToRGB(hex: string): RGB | null {
let result;
switch (hex.length) {
case 3:
case 4:
result = shortHexRE.exec(hex);
return result
? {
r: parseInt(result[1] + result[1], 16),
g: parseInt(result[2] + result[2], 16),
b: parseInt(result[3] + result[3], 16),
}
: null;
case 6:
case 7:
result = fullHexRE.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
default:
return null;
}
}
/**
* This function takes string color in hex or RGB format and adds the opacity, RGBA is passed through unchanged.
*
* @param color - The color string (hex, RGB, RGBA).
* @param opacity - The new opacity.
* @returns RGBA string, for example 'rgba(255, 0, 127, 0.3)'.
*/
export function overrideOpacity(color: string, opacity: number): string {
if (color.includes("rgba")) {
return color;
} else if (color.includes("rgb")) {
const rgb = color
.substr(color.indexOf("(") + 1)
.replace(")", "")
.split(",");
return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
} else {
const rgb = hexToRGB(color);
if (rgb == null) {
return color;
} else {
return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")";
}
}
}
/**
* Convert RGB \<0, 255\> into hex color string.
*
* @param red - Red channel.
* @param green - Green channel.
* @param blue - Blue channel.
* @returns Hex color string (for example: '#0acdc0').
*/
export function RGBToHex(red: number, green: number, blue: number): string {
return (
"#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)
);
}
export interface ColorObject {
background?: string;
border?: string;
hover?:
| string
| {
border?: string;
background?: string;
};
highlight?:
| string
| {
border?: string;
background?: string;
};
}
export interface FullColorObject {
background: string;
border: string;
hover: {
border: string;
background: string;
};
highlight: {
border: string;
background: string;
};
}
export function parseColor(inputColor: string): FullColorObject;
export function parseColor(inputColor: FullColorObject): FullColorObject;
export function parseColor(inputColor: ColorObject): ColorObject;
export function parseColor(
inputColor: ColorObject,
defaultColor: FullColorObject
): FullColorObject;
/**
* Parse a color property into an object with border, background, and highlight colors.
*
* @param inputColor - Shorthand color string or input color object.
* @param defaultColor - Full color object to fill in missing values in inputColor.
* @returns Color object.
*/
export function parseColor(
inputColor: ColorObject | string,
defaultColor?: FullColorObject
): ColorObject | FullColorObject {
if (isString(inputColor)) {
let colorStr: string = inputColor;
if (isValidRGB(colorStr)) {
const rgb = colorStr
.substr(4)
.substr(0, colorStr.length - 5)
.split(",")
.map(function (value): number {
return parseInt(value);
});
colorStr = RGBToHex(rgb[0], rgb[1], rgb[2]);
}
if (isValidHex(colorStr) === true) {
const hsv = hexToHSV(colorStr);
const lighterColorHSV = {
h: hsv.h,
s: hsv.s * 0.8,
v: Math.min(1, hsv.v * 1.02),
};
const darkerColorHSV = {
h: hsv.h,
s: Math.min(1, hsv.s * 1.25),
v: hsv.v * 0.8,
};
const darkerColorHex = HSVToHex(
darkerColorHSV.h,
darkerColorHSV.s,
darkerColorHSV.v
);
const lighterColorHex = HSVToHex(
lighterColorHSV.h,
lighterColorHSV.s,
lighterColorHSV.v
);
return {
background: colorStr,
border: darkerColorHex,
highlight: {
background: lighterColorHex,
border: darkerColorHex,
},
hover: {
background: lighterColorHex,
border: darkerColorHex,
},
};
} else {
return {
background: colorStr,
border: colorStr,
highlight: {
background: colorStr,
border: colorStr,
},
hover: {
background: colorStr,
border: colorStr,
},
};
}
} else {
if (defaultColor) {
const color: FullColorObject = {
background: inputColor.background || defaultColor.background,
border: inputColor.border || defaultColor.border,
highlight: isString(inputColor.highlight)