-
Notifications
You must be signed in to change notification settings - Fork 117
/
hterm_all.js
23131 lines (20571 loc) · 698 KB
/
hterm_all.js
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
// This file was generated by libdot/bin/concat.sh.
// It has been marked read-only for your safety. Rather than
// edit it directly, please modify one of these source files.
//
// libdot/js/lib.js
// libdot/js/lib_polyfill.js
// libdot/js/lib_array.js
// libdot/js/lib_codec.js
// libdot/js/lib_colors.js
// libdot/js/lib_f.js
// libdot/js/lib_i18n.js
// libdot/js/lib_message_manager.js
// libdot/js/lib_preference_manager.js
// libdot/js/lib_resource.js
// libdot/js/lib_storage.js
// libdot/js/lib_storage_chrome.js
// libdot/js/lib_storage_local.js
// libdot/js/lib_storage_memory.js
// libdot/js/lib_storage_terminal_private.js
// libdot/third_party/intl-segmenter/intl-segmenter.js
// libdot/third_party/wcwidth/lib_wc.js
// hterm/js/hterm.js
// hterm/js/hterm_accessibility_reader.js
// hterm/js/hterm_contextmenu.js
// hterm/js/hterm_find_bar.js
// hterm/js/hterm_frame.js
// hterm/js/hterm_keyboard.js
// hterm/js/hterm_keyboard_bindings.js
// hterm/js/hterm_keyboard_keymap.js
// hterm/js/hterm_keyboard_keypattern.js
// hterm/js/hterm_options.js
// hterm/js/hterm_parser.js
// hterm/js/hterm_parser_identifiers.js
// hterm/js/hterm_preference_manager.js
// hterm/js/hterm_pubsub.js
// hterm/js/hterm_screen.js
// hterm/js/hterm_scrollport.js
// hterm/js/hterm_terminal.js
// hterm/js/hterm_terminal_io.js
// hterm/js/hterm_text_attributes.js
// hterm/js/hterm_vt.js
// hterm/js/hterm_vt_character_map.js
// hterm/audio/bell.ogg
// hterm/images/copy.svg
// hterm/images/close.svg
// hterm/images/keyboard_arrow_down.svg
// hterm/images/keyboard_arrow_up.svg
// hterm/html/find_bar.html
// hterm/html/find_screen.html
// hterm/images/icon-96.png
'use strict';
// SOURCE FILE: libdot/js/lib.js
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const lib = {};
/**
* List of functions that need to be invoked during library initialization.
*
* Each element in the initCallbacks_ array is itself a two-element array.
* Element 0 is a short string describing the owner of the init routine, useful
* for debugging. Element 1 is the callback function.
*/
lib.initCallbacks_ = [];
/**
* Register an initialization function.
*
* The initialization functions are invoked in registration order when
* lib.init() is invoked. Each function will receive a single parameter, which
* is a function to be invoked when it completes its part of the initialization.
*
* @param {string} name A short descriptive name of the init routine useful for
* debugging.
* @param {function()} callback The initialization function to register.
*/
lib.registerInit = function(name, callback) {
lib.initCallbacks_.push([name, callback]);
};
/**
* Initialize the library.
*
* This will ensure that all registered runtime dependencies are met, and
* invoke any registered initialization functions.
*
* Initialization is asynchronous. The library is not ready for use until
* the returned promise resolves.
*
* @param {function(*)=} logFunction An optional function to send initialization
* related log messages to.
* @return {!Promise<void>} Promise that resolves once all inits finish.
*/
lib.init = async function(logFunction = undefined) {
const ary = lib.initCallbacks_;
while (ary.length) {
const [name, init] = ary.shift();
if (logFunction) {
logFunction(`init: ${name}`);
}
const ret = init();
if (ret && typeof ret.then === 'function') {
await ret;
}
}
};
/**
* Verify |condition| is truthy else throw Error.
*
* This function is primarily for satisfying the JS compiler and should be
* used only when you are certain that your condition is true. The function is
* designed to have a version that throws Errors in tests if condition fails,
* and a nop version for production code. It configures itself the first time
* it runs.
*
* @param {boolean} condition A condition to check.
* @closurePrimitive {asserts.truthy}
*/
lib.assert = function(condition) {
if (window.chai) {
lib.assert = window.chai.assert;
} else {
lib.assert = function(condition) {};
}
lib.assert(condition);
};
/**
* Verify |value| is not null and return |value| if so, else throw Error.
* See lib.assert.
*
* @template T
* @param {T} value A value to check for null.
* @return {T} A non-null |value|.
* @closurePrimitive {asserts.truthy}
*/
lib.notNull = function(value) {
lib.assert(value !== null);
return value;
};
/**
* Verify |value| is not undefined and return |value| if so, else throw Error.
* See lib.assert.
*
* @template T
* @param {T} value A value to check for null.
* @return {T} A non-undefined |value|.
* @closurePrimitive {asserts.truthy}
*/
lib.notUndefined = function(value) {
lib.assert(value !== undefined);
return value;
};
// SOURCE FILE: libdot/js/lib_polyfill.js
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Polyfills for ES2019+ features we want to use.
* @suppress {duplicate} This file redefines many functions.
*/
/** @const */
lib.polyfill = {};
/**
* https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer
*
* @return {!Promise<!ArrayBuffer>}
*/
lib.polyfill.BlobArrayBuffer = function() {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onabort = reader.onerror = () => reject(reader);
reader.readAsArrayBuffer(this);
});
};
if (typeof Blob.prototype.arrayBuffer != 'function') {
Blob.prototype.arrayBuffer = lib.polyfill.BlobArrayBuffer;
}
/**
* https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
*
* @return {!Promise<string>}
*/
lib.polyfill.BlobText = function() {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onabort = reader.onerror = () => reject(reader);
reader.readAsText(this);
});
};
if (typeof Blob.prototype.arrayBuffer != 'function') {
Blob.prototype.text = lib.polyfill.BlobText;
}
// SOURCE FILE: libdot/js/lib_array.js
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Helper functions for (typed) arrays.
*/
lib.array = {};
/**
* Concatenate an arbitrary number of typed arrays of the same type into a new
* typed array of this type.
*
* @template TYPED_ARRAY
* @param {...!TYPED_ARRAY} arrays
* @return {!TYPED_ARRAY}
*/
lib.array.concatTyped = function(...arrays) {
let resultLength = 0;
for (const array of arrays) {
resultLength += array.length;
}
const result = new arrays[0].constructor(resultLength);
let pos = 0;
for (const array of arrays) {
result.set(array, pos);
pos += array.length;
}
return result;
};
/**
* Compare two array-like objects entrywise.
*
* @template ARRAY_LIKE
* @param {?ARRAY_LIKE} a The first array to compare.
* @param {?ARRAY_LIKE} b The second array to compare.
* @return {boolean} true if both arrays are null or they agree entrywise;
* false otherwise.
*/
lib.array.compare = function(a, b) {
if (a === null || b === null) {
return a === null && b === null;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
// SOURCE FILE: libdot/js/lib_codec.js
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
lib.codec = {};
/**
* Join an array of code units to a string.
*
* The code units must not be larger than 65535. The individual code units may
* be for UTF-8 or UTF-16 -- it doesn't matter since UTF-16 can handle all UTF-8
* code units.
*
* The input array type may be an Array or a typed Array (e.g. Uint8Array).
*
* @param {!Uint8Array|!Array<number>} array The code units to generate for
* the string.
* @return {string} A UTF-16 encoded string.
*/
lib.codec.codeUnitArrayToString = function(array) {
// String concat is faster than Array.join.
//
// String.fromCharCode.apply is faster than this if called less frequently
// and with smaller array sizes (like <32K). But it's a recursive call so
// larger arrays will blow the stack and fail. We also seem to be faster
// (or at least more constant time) when called frequently.
let ret = '';
for (let i = 0; i < array.length; ++i) {
ret += String.fromCharCode(array[i]);
}
return ret;
};
/**
* Create an array of code units from a UTF-16 encoded string.
*
* @param {string} str The string to extract code units from.
* @param {!ArrayBufferView=} ret The buffer to hold the result. If not set, a
* new Uint8Array is created.
* @return {!ArrayBufferView} The array of code units.
*/
lib.codec.stringToCodeUnitArray = function(
str, ret = new Uint8Array(str.length)) {
// Indexing string directly is faster than Array.map.
for (let i = 0; i < str.length; ++i) {
ret[i] = str.charCodeAt(i);
}
return ret;
};
// SOURCE FILE: libdot/js/lib_colors.js
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Namespace for color utilities.
*/
lib.colors = {};
/**
* First, some canned regular expressions we're going to use in this file.
*
*
* BRACE YOURSELF
*
* ,~~~~.
* |>_< ~~
* 3`---'-/.
* 3:::::\v\
* =o=:::::\,\
* | :::::\,,\
*
* THE REGULAR EXPRESSIONS
* ARE COMING.
*
* There's no way to break long RE literals in JavaScript. Fix that why don't
* you? Oh, and also there's no way to write a string that doesn't interpret
* escapes.
*
* Instead, we stoop to this .replace() trick.
*/
lib.colors.re_ = {
// CSS hex color, #RGB or RGBA.
hex16: /^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?$/i,
// CSS hex color, #RRGGBB or #RRGGBBAA.
hex24: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?$/i,
// CSS rgb color, rgb(rrr,ggg,bbb).
rgb: new RegExp(
('^/s*rgb/s*/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*,' +
'/s*(/d{1,3})/s*/)/s*$'
).replace(/\//g, '\\'), 'i'),
// CSS rgb color, rgba(rrr,ggg,bbb,aaa).
rgba: new RegExp(
('^/s*rgba/s*' +
'/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*,/s*(/d{1,3})/s*' +
'(?:,/s*(/d+(?:/./d+)?)/s*)/)/s*$'
).replace(/\//g, '\\'), 'i'),
// Either RGB or RGBA.
rgbx: new RegExp(
('^/s*rgba?/s*' +
'/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*,/s*(/d{1,3})/s*' +
'(?:,/s*(/d+(?:/./d+)?)/s*)?/)/s*$'
).replace(/\//g, '\\'), 'i'),
// CSS hsl color, hsl(hhh,sss%,lll%).
hsl: new RegExp(
('^/s*hsl/s*' +
'/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*%/s*,/s*(/d{1,3})/s*%/s*/)/s*$'
).replace(/\//g, '\\'), 'i'),
// CSS hsl color, hsla(hhh,sss%,lll%,aaa).
hsla: new RegExp(
('^/s*hsla/s*' +
'/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*%/s*,/s*(/d{1,3})/s*%/s*' +
'(?:,/s*(/d+(?:/./d+)?)/s*)/)/s*$'
).replace(/\//g, '\\'), 'i'),
// Either HSL or HSLA.
hslx: new RegExp(
('^/s*hsla?/s*' +
'/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*%/s*,/s*(/d{1,3})/s*%/s*' +
'(?:,/s*(/d+(?:/./d+)?)/s*)?/)/s*$'
).replace(/\//g, '\\'), 'i'),
// An X11 "rgb:dddd/dddd/dddd" value.
x11rgb: /^\s*rgb:([a-f0-9]{1,4})\/([a-f0-9]{1,4})\/([a-f0-9]{1,4})\s*$/i,
// English color name.
name: /[a-z][a-z0-9\s]+/,
};
/**
* Convert a CSS rgb(ddd,ddd,ddd) color value into an X11 color value.
*
* Other CSS color values are ignored to ensure sanitary data handling.
*
* Each 'ddd' component is a one byte value specified in decimal.
*
* @param {string} value The CSS color value to convert.
* @return {?string} The X11 color value or null if the value could not be
* converted.
*/
lib.colors.rgbToX11 = function(value) {
function scale(v) {
v = (Math.min(v, 255) * 257).toString(16);
return lib.f.zpad(v, 4);
}
const ary = value.match(lib.colors.re_.rgbx);
if (!ary) {
return null;
}
return 'rgb:' + scale(ary[1]) + '/' + scale(ary[2]) + '/' + scale(ary[3]);
};
/**
* Convert a legacy X11 color value into an CSS rgb(...) color value.
*
* They take the form:
* 12 bit: #RGB -> #R000G000B000
* 24 bit: #RRGGBB -> #RR00GG00BB00
* 36 bit: #RRRGGGBBB -> #RRR0GGG0BBB0
* 48 bit: #RRRRGGGGBBBB
* These are the most significant bits.
*
* Truncate values back down to 24 bit since that's all CSS supports.
*
* @param {string} v The X11 hex color value to convert.
* @return {?string} The CSS color value or null if the value could not be
* converted.
*/
lib.colors.x11HexToCSS = function(v) {
if (!v.startsWith('#')) {
return null;
}
// Strip the leading # off.
v = v.substr(1);
// Reject unknown sizes.
if ([3, 6, 9, 12].indexOf(v.length) == -1) {
return null;
}
// Reject non-hex values.
if (v.match(/[^a-f0-9]/i)) {
return null;
}
// Split the colors out.
const size = v.length / 3;
const r = v.substr(0, size);
const g = v.substr(size, size);
const b = v.substr(size + size, size);
// Normalize to 16 bits.
function norm16(v) {
v = parseInt(v, 16);
return size == 2 ? v : // 16 bit
size == 1 ? v << 4 : // 8 bit
v >> (4 * (size - 2)); // 24 or 32 bit
}
return lib.colors.arrayToRGBA([r, g, b].map(norm16));
};
/**
* Convert an X11 color value into an CSS rgb(...) color value.
*
* The X11 value may be an X11 color name, or an RGB value of the form
* rgb:hhhh/hhhh/hhhh. If a component value is less than 4 digits it is
* padded out to 4, then scaled down to fit in a single byte.
*
* @param {string} v The X11 color value to convert.
* @return {?string} The CSS color value or null if the value could not be
* converted.
*/
lib.colors.x11ToCSS = function(v) {
function scale(v) {
// Pad out values with less than four digits. This padding (probably)
// matches xterm. It's difficult to say for sure since xterm seems to
// arrive at a padded value and then perform some combination of
// gamma correction, color space transformation, and quantization.
if (v.length == 1) {
// Single digits pad out to four by repeating the character. "f" becomes
// "ffff". Scaling down a hex value of this pattern by 257 is the same
// as cutting off one byte. We skip the middle step and just double
// the character.
return parseInt(v + v, 16);
}
if (v.length == 2) {
// Similar deal here. X11 pads two digit values by repeating the
// byte (or scale up by 257). Since we're going to scale it back
// down anyway, we can just return the original value.
return parseInt(v, 16);
}
if (v.length == 3) {
// Three digit values seem to be padded by repeating the final digit.
// e.g. 10f becomes 10ff.
v = v + v.substr(2);
}
// Scale down the 2 byte value.
return Math.round(parseInt(v, 16) / 257);
}
const ary = v.match(lib.colors.re_.x11rgb);
if (!ary) {
// Handle the legacy format.
if (v.startsWith('#')) {
return lib.colors.x11HexToCSS(v);
} else {
return lib.colors.nameToRGB(v);
}
}
ary.splice(0, 1);
return lib.colors.arrayToRGBA(ary.map(scale));
};
/**
* Converts one or more CSS '#RRGGBB' or '#RRGGBBAA' color values into their
* rgb(...) or rgba(...) form respectively.
*
* Arrays are converted in place. If a value cannot be converted, it is
* replaced with null.
*
* @param {string} hex A single RGB or RGBA value to convert.
* @return {?string} The converted value.
*/
lib.colors.hexToRGB = function(hex) {
const hex16 = lib.colors.re_.hex16;
const hex24 = lib.colors.re_.hex24;
if (hex16.test(hex)) {
// Convert from RGB to RRGGBB and from RGBA to RRGGBBAA.
hex = `#${hex.match(/[a-f0-9]/gi).map((x) => `${x}${x}`).join('')}`;
}
const ary = hex.match(hex24);
if (!ary) {
return null;
}
const val = (index) => parseInt(ary[index + 1], 16);
return ary[4] === undefined || val(3) === 255
? `rgb(${val(0)}, ${val(1)}, ${val(2)})`
: `rgba(${val(0)}, ${val(1)}, ${val(2)}, ${val(3) / 255})`;
};
/**
* Converts one or more CSS rgb(...) or rgba(...) forms into their '#RRGGBB' or
* '#RRGGBBAA' color values respectively.
*
* Arrays are converted in place. If a value cannot be converted, it is
* replaced with null.
*
* @param {string} rgb A single rgb(...) or rgba(...) value to convert.
* @return {?string} The converted value.
*/
lib.colors.rgbToHex = function(rgb) {
const ary = lib.colors.crackRGB(rgb);
if (!ary) {
return null;
}
const hex = '#' + lib.f.zpad((
(parseInt(ary[0], 10) << 16) |
(parseInt(ary[1], 10) << 8) |
(parseInt(ary[2], 10) << 0)).toString(16), 6);
if (ary[3] === undefined || ary[3] === '1') {
return hex;
} else {
const alpha = Math.round(255 * parseFloat(ary[3])).toString(16);
return `${hex}${lib.f.zpad(alpha, 2)}`;
}
};
/**
* Split an hsl/hsla color into an array of its components.
*
* On success, a 4 element array will be returned. For hsl values, the alpha
* will be set to 1.
*
* @param {string} color The HSL/HSLA CSS color spec.
* @return {?Array<string>} The HSL/HSLA values split out.
*/
lib.colors.crackHSL = function(color) {
if (color.startsWith('hsla')) {
const ary = color.match(lib.colors.re_.hsla);
if (ary) {
ary.shift();
return Array.from(ary);
}
} else {
const ary = color.match(lib.colors.re_.hsl);
if (ary) {
ary.shift();
ary.push('1');
return Array.from(ary);
}
}
console.error(`Couldn't crack: ${color}`);
return null;
};
/**
* Converts hslx array to rgba array.
*
* The returned alpha component defaults to 1 if it isn't present in the input.
*
* The returned values are not rounded to preserve precision for computations,
* so should be rounded before they are used in CSS strings.
*
* @param {?Array<string|number>} hslx The HSL or HSLA elements to convert.
* @return {!Array<number>} The RGBA values.
*/
lib.colors.hslxArrayToRgbaArray = function(hslx) {
const hue = parseInt(hslx[0], 10) / 60;
const sat = parseInt(hslx[1], 10) / 100;
const light = parseInt(hslx[2], 10) / 100;
// The following algorithm has been adapted from:
// https://www.w3.org/TR/css-color-4/#hsl-to-rgb
const hueToRgb = (t1, t2, hue) => {
if (hue < 0) {
hue += 6;
}
if (hue >= 6) {
hue -= 6;
}
if (hue < 1) {
return (t2 - t1) * hue + t1;
} else if (hue < 3) {
return t2;
} else if (hue < 4) {
return (t2 - t1) * (4 - hue) + t1;
} else {
return t1;
}
};
const t2 = light <= 0.5 ? light * (sat + 1) : light + sat - (light * sat);
const t1 = light * 2 - t2;
return [
255 * hueToRgb(t1, t2, hue + 2),
255 * hueToRgb(t1, t2, hue),
255 * hueToRgb(t1, t2, hue - 2),
hslx[3] !== undefined ? +hslx[3] : 1,
];
};
/**
* Converts a hsvx array to a hsla array. The hsvx array is an array of [hue
* (>=0, <=360), saturation (>=0, <=100), value (>=0, <=100), alpha] (alpha can
* be missing).
*
* The returned alpha component defaults to 1 if it isn't present in the input.
*
* The returned values are not rounded to preserve precision for computations,
* so should be rounded before they are used in CSS strings.
*
* @param {?Array<string|number>} hsvx The hsv or hsva array.
* @return {!Array<number>} The hsla array.
*/
lib.colors.hsvxArrayToHslaArray = function(hsvx) {
const clamp = (x) => lib.f.clamp(x, 0, 100);
const [hue, saturation, value] = hsvx.map(parseFloat);
const hslLightness = clamp(value * (100 - saturation / 2) / 100);
let hslSaturation = 0;
if (hslLightness !== 0 && hslLightness !== 100) {
hslSaturation = clamp((value - hslLightness) /
Math.min(hslLightness, 100 - hslLightness) * 100);
}
return [
hue,
hslSaturation,
hslLightness,
hsvx.length === 4 ? +hsvx[3] : 1,
];
};
/**
* Converts a hslx array to a hsva array. The hsva array is an array of [hue
* (>=0, <=360), saturation (>=0, <=100), value (>=0, <=100), alpha].
*
* The returned alpha component defaults to 1 if it isn't present in the input.
*
* @param {?Array<string|number>} hslx The hsl or hsla array.
* @return {!Array<number>} The hsva array.
*/
lib.colors.hslxArrayToHsvaArray = function(hslx) {
const clamp = (x) => lib.f.clamp(x, 0, 100);
const [hue, saturation, lightness] = hslx.map(parseFloat);
const hsvValue = clamp(
lightness + saturation * Math.min(lightness, 100 - lightness) / 100);
let hsvSaturation = 0;
if (hsvValue !== 0) {
hsvSaturation = clamp(200 * (1 - lightness / hsvValue));
}
return [hue, hsvSaturation, hsvValue, hslx.length === 4 ? +hslx[3] : 1];
};
/**
* Converts one or more CSS hsl(...) or hsla(...) forms into their rgb(...) or
* rgba(...) color values respectively.
*
* Arrays are converted in place. If a value cannot be converted, it is
* replaced with null.
*
* @param {string} hsl A single hsl(...) or hsla(...) value to convert.
* @return {?string} The converted value.
*/
lib.colors.hslToRGB = function(hsl) {
const ary = lib.colors.crackHSL(hsl);
if (!ary) {
return null;
}
const [r, g, b, a] = lib.colors.hslxArrayToRgbaArray(ary);
const rgb = [r, g, b].map(Math.round).join(', ');
return a === 1 ? `rgb(${rgb})` : `rgba(${rgb}, ${a})`;
};
/**
* Converts rgbx array to hsla array.
*
* The returned alpha component defaults to 1 if it isn't present in the input.
*
* The returned values are not rounded to preserve precision for computations,
* so should be rounded before they are used in CSS strings.
*
* @param {?Array<string|number>} rgbx The RGB or RGBA elements to convert.
* @return {!Array<number>} The HSLA values.
*/
lib.colors.rgbxArrayToHslaArray = function(rgbx) {
const r = parseInt(rgbx[0], 10) / 255;
const g = parseInt(rgbx[1], 10) / 255;
const b = parseInt(rgbx[2], 10) / 255;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const spread = max - min;
/* eslint-disable id-blacklist */
const l = (max + min) / 2;
if (spread == 0) {
return [0, 0, 100 * l, rgbx[3] !== undefined ? +rgbx[3] : 1];
}
let h = (() => {
switch (max) {
case r: return ((g - b) / spread) % 6;
case g: return (b - r) / spread + 2;
case b: return (r - g) / spread + 4;
}
})();
h *= 60;
if (h < 0) {
h += 360;
}
const s = spread / (1 - Math.abs(2 * l - 1));
return [h, 100 * s, 100 * l, rgbx[3] !== undefined ? +rgbx[3] : 1];
/* eslint-enable id-blacklist */
};
/**
* Converts one or more CSS rgb(...) or rgba(...) forms into their hsl(...) or
* hsla(...) color values respectively.
*
* Arrays are converted in place. If a value cannot be converted, it is
* replaced with null.
*
* @param {string} rgb A single rgb(...) or rgba(...) value to convert.
* @return {?string} The converted value.
*/
lib.colors.rgbToHsl = function(rgb) {
const ary = lib.colors.crackRGB(rgb);
if (!ary) {
return null;
}
/* eslint-disable id-blacklist */
// eslint-disable-next-line prefer-const
let [h, s, l, a] = lib.colors.rgbxArrayToHslaArray(ary);
h = Math.round(h);
s = Math.round(s);
l = Math.round(l);
return a === 1 ? `hsl(${h}, ${s}%, ${l}%)` : `hsla(${h}, ${s}%, ${l}%, ${a})`;
/* eslint-enable id-blacklist */
};
/**
* Take any valid CSS color definition and turn it into an rgb or rgba value.
*
* @param {string} def The CSS color spec to normalize.
* @return {?string} The converted value.
*/
lib.colors.normalizeCSS = function(def) {
if (def.startsWith('#')) {
return lib.colors.hexToRGB(def);
}
if (lib.colors.re_.rgbx.test(def)) {
return def;
}
if (lib.colors.re_.hslx.test(def)) {
return lib.colors.hslToRGB(def);
}
return lib.colors.nameToRGB(def);
};
/**
* Take any valid CSS color definition and turn it into an hsl or hsla value.
*
* @param {string} def The CSS color spec to normalize.
* @return {?string} The converted value.
*/
lib.colors.normalizeCSSToHSL = function(def) {
if (lib.colors.re_.hslx.test(def)) {
return def;
}
const rgb = lib.colors.normalizeCSS(def);
if (!rgb) {
return rgb;
}
return lib.colors.rgbToHsl(rgb);
};
/**
* Convert a 3 or 4 element array into an rgb(...) or rgba(...) string.
*
* @param {?Array<string|number>} ary The RGB or RGBA elements to convert.
* @return {string} The normalized CSS color spec.
*/
lib.colors.arrayToRGBA = function(ary) {
if (ary.length == 3) {
return `rgb(${ary[0]}, ${ary[1]}, ${ary[2]})`;
}
return `rgba(${ary[0]}, ${ary[1]}, ${ary[2]}, ${ary[3]})`;
};
/**
* Convert a 3 or 4 element array into an hsla(...) string.
*
* @param {?Array<string|number>} ary The HSL or HSLA elements to convert.
* @return {string} The normalized CSS color spec.
*/
lib.colors.arrayToHSLA = function(ary) {
const alpha = (ary.length > 3) ? ary[3] : 1;
return `hsla(${Math.round(ary[0])}, ${Math.round(ary[1])}%, ` +
`${Math.round(ary[2])}%, ${alpha})`;
};
/**
* Overwrite the alpha channel of an rgb/rgba color.
*
* @param {string} rgb The normalized CSS color spec.
* @param {number} alpha The alpha channel.
* @return {string} The normalized CSS color spec with updated alpha channel.
*/
lib.colors.setAlpha = function(rgb, alpha) {
const ary = lib.colors.crackRGB(rgb);
ary[3] = alpha.toString();
return lib.colors.arrayToRGBA(ary);
};
/**
* Mix a percentage of a tint color into a base color.
*
* @param {string} base The normalized CSS base color spec.
* @param {string} tint The normalized CSS color to tint with.
* @param {number} percent The percentage of the tinting.
* @return {string} The new tinted CSS color spec.
*/
lib.colors.mix = function(base, tint, percent) {
const ary1 = lib.colors.crackRGB(base);
const ary2 = lib.colors.crackRGB(tint);
for (let i = 0; i < 4; ++i) {
const basecol = parseInt(ary1[i], 10);
const tintcol = parseInt(ary2[i], 10);
const diff = tintcol - basecol;
ary1[i] = Math.round(base + diff * percent).toString();
}
return lib.colors.arrayToRGBA(ary1);
};
/**
* Split an rgb/rgba color into an array of its components.
*
* On success, a 4 element array will be returned. For rgb values, the alpha
* will be set to 1.
*
* @param {string} color The RGB/RGBA CSS color spec.
* @return {?Array<string>} The RGB/RGBA values split out.
*/
lib.colors.crackRGB = function(color) {
if (color.startsWith('rgba')) {
const ary = color.match(lib.colors.re_.rgba);
if (ary) {
ary.shift();
return Array.from(ary);
}
} else {
const ary = color.match(lib.colors.re_.rgb);
if (ary) {
ary.shift();
ary.push('1');
return Array.from(ary);
}
}
console.error('Couldn\'t crack: ' + color);
return null;
};
/**
* Convert an X11 color name into a CSS rgb(...) value.
*
* Names are stripped of spaces and converted to lowercase. If the name is
* unknown, null is returned.
*
* This list of color name to RGB mapping is derived from the stock X11
* rgb.txt file.
*
* @param {string} name The color name to convert.
* @return {?string} The corresponding CSS rgb(...) value.
*/
lib.colors.nameToRGB = function(name) {
if (name in lib.colors.colorNames) {
return lib.colors.colorNames[name];
}
name = name.toLowerCase();
if (name in lib.colors.colorNames) {
return lib.colors.colorNames[name];
}
name = name.replace(/\s+/g, '');
if (name in lib.colors.colorNames) {
return lib.colors.colorNames[name];
}
return null;
};
/**
* Calculate the relative luminance as per
* https://www.w3.org/TR/WCAG20/#relativeluminancedef
*
* @param {number} r The value (>=0 and <= 255) of the rgb component.
* @param {number} g The value (>=0 and <= 255) of the rgb component.
* @param {number} b The value (>=0 and <= 255) of the rgb component.
* @return {number} The relative luminance.
*/
lib.colors.luminance = function(r, g, b) {
const [rr, gg, bb] = [r, g, b].map((value) => {
value /= 255;
if (value <= 0.03928) {
return value / 12.92;
} else {
return Math.pow((value + 0.055) / 1.055, 2.4);
}
});
return 0.2126 * rr + 0.7152 * gg + 0.0722 * bb;
};
/**
* Calculate the contrast ratio of two relative luminance values as per
* https://www.w3.org/TR/WCAG20/#contrast-ratiodef
*
* @param {number} l1 Relative luminance value.
* @param {number} l2 Relative luminance value.