-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.cjs.js
1691 lines (1400 loc) · 49.7 KB
/
index.cjs.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
'use strict';
var parser = require('postcss-value-parser');
var fs = require('fs');
var path = require('path');
var postcss = require('postcss');
var convertColors = require('@csstools/convert-colors');
// return custom selectors from the css root, conditionally removing them
function getCustomProperties(root, opts) {
// initialize custom selectors
const customPropertiesFromHtmlElement = {};
const customPropertiesFromRootPsuedo = {};
// for each html or :root rule
root.nodes.slice().forEach(rule => {
const customPropertiesObject = isHtmlRule(rule)
? customPropertiesFromHtmlElement
: isRootRule(rule)
? customPropertiesFromRootPsuedo
: null;
// for each custom property
if (customPropertiesObject) {
rule.nodes.slice().forEach(decl => {
if (isCustomDecl(decl)) {
const { prop } = decl;
// write the parsed value to the custom property
customPropertiesObject[prop] = parser(decl.value);
// conditionally remove the custom property declaration
if (!opts.preserve) {
decl.remove();
}
}
});
// conditionally remove the empty html or :root rule
if (!opts.preserve && isEmptyParent(rule)) {
rule.remove();
}
}
});
// return all custom properties, preferring :root properties over html properties
return { ...customPropertiesFromHtmlElement, ...customPropertiesFromRootPsuedo };
}
// match html and :root rules
const htmlSelectorRegExp = /^html$/i;
const rootSelectorRegExp = /^:root$/i;
const customPropertyRegExp = /^--[A-z][\w-]*$/;
// whether the node is an html or :root rule
const isHtmlRule = node => node.type === 'rule' && htmlSelectorRegExp.test(node.selector) && Object(node.nodes).length;
const isRootRule = node => node.type === 'rule' && rootSelectorRegExp.test(node.selector) && Object(node.nodes).length;
// whether the node is an custom property
const isCustomDecl = node => node.type === 'decl' && customPropertyRegExp.test(node.prop);
// whether the node is a parent without children
const isEmptyParent = node => Object(node.nodes).length === 0;
/* Import Custom Properties from CSS AST
/* ========================================================================== */
function importCustomPropertiesFromCSSAST(root) {
return getCustomProperties(root, { preserve: true });
}
/* Import Custom Properties from CSS File
/* ========================================================================== */
async function importCustomPropertiesFromCSSFile(from) {
const css = await readFile(from);
const root = postcss.parse(css, { from });
return importCustomPropertiesFromCSSAST(root);
}
/* Import Custom Properties from Object
/* ========================================================================== */
function importCustomPropertiesFromObject(object) {
const customProperties = Object.assign(
{},
Object(object).customProperties || Object(object)['custom-properties']
);
for (const prop in customProperties) {
customProperties[prop] = parser(customProperties[prop]);
}
return customProperties;
}
/* Import Custom Properties from JSON file
/* ========================================================================== */
async function importCustomPropertiesFromJSONFile(from) {
const object = await readJSON(from);
return importCustomPropertiesFromObject(object);
}
/* Import Custom Properties from JS file
/* ========================================================================== */
async function importCustomPropertiesFromJSFile(from) {
const object = await import(from);
return importCustomPropertiesFromObject(('default' in object) ? object.default : object);
}
/* Import Custom Properties from Sources
/* ========================================================================== */
function importCustomPropertiesFromSources(sources) {
return sources.map(source => {
if (source instanceof Promise) {
return source;
} else if (source instanceof Function) {
return source();
}
// read the source as an object
const opts = source === Object(source) ? source : { from: String(source) };
// skip objects with Custom Properties
if (opts.customProperties || opts['custom-properties']) {
return opts
}
// source pathname
const from = path.resolve(String(opts.from || ''));
// type of file being read from
const type = (opts.type || path.extname(from).slice(1)).toLowerCase();
return { type, from };
}).reduce(async (customProperties, source) => {
const { type, from } = await source;
if (type === 'ast') {
return Object.assign(await customProperties, importCustomPropertiesFromCSSAST(from));
}
if (type === 'css') {
return Object.assign(await customProperties, await importCustomPropertiesFromCSSFile(from));
}
if (type === 'js') {
return Object.assign(await customProperties, await importCustomPropertiesFromJSFile(from));
}
if (type === 'json') {
return Object.assign(await customProperties, await importCustomPropertiesFromJSONFile(from));
}
return Object.assign(await customProperties, await importCustomPropertiesFromObject(await source));
}, {});
}
/* Helper utilities
/* ========================================================================== */
const readFile = from => new Promise((resolve, reject) => {
fs.readFile(from, 'utf8', (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
const readJSON = async from => JSON.parse(await readFile(from));
/* Convert Degree to Hue Degree
/* ========================================================================== */
function convertDtoD(deg) {
return deg % 360;
}
/* Convert Gradian to Hue Degree
/* ========================================================================== */
function convertGtoD(grad) {
return grad * 0.9 % 360;
}
/* Convert Radian to Hue Degree
/* ========================================================================== */
function convertRtoD(rad) {
return rad * 180 / Math.PI % 360;
}
/* Convert Turn to Hue Degree
/* ========================================================================== */
function convertTtoD(turn) {
return turn * 360 % 360;
}
/* Convert a Name to Red/Green/Blue
/* ========================================================================== */
function convertNtoRGB(name) {
const names = {
aliceblue: [240, 248, 255],
antiquewhite: [250, 235, 215],
aqua: [0, 255, 255],
aquamarine: [127, 255, 212],
azure: [240, 255, 255],
beige: [245, 245, 220],
bisque: [255, 228, 196],
black: [0, 0, 0],
blanchedalmond: [255, 235, 205],
blue: [0, 0, 255],
blueviolet: [138, 43, 226],
brown: [165, 42, 42],
burlywood: [222, 184, 135],
cadetblue: [95, 158, 160],
chartreuse: [127, 255, 0],
chocolate: [210, 105, 30],
coral: [255, 127, 80],
cornflowerblue: [100, 149, 237],
cornsilk: [255, 248, 220],
crimson: [220, 20, 60],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgoldenrod: [184, 134, 11],
darkgray: [169, 169, 169],
darkgreen: [0, 100, 0],
darkgrey: [169, 169, 169],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkseagreen: [143, 188, 143],
darkslateblue: [72, 61, 139],
darkslategray: [47, 79, 79],
darkslategrey: [47, 79, 79],
darkturquoise: [0, 206, 209],
darkviolet: [148, 0, 211],
deeppink: [255, 20, 147],
deepskyblue: [0, 191, 255],
dimgray: [105, 105, 105],
dimgrey: [105, 105, 105],
dodgerblue: [30, 144, 255],
firebrick: [178, 34, 34],
floralwhite: [255, 250, 240],
forestgreen: [34, 139, 34],
fuchsia: [255, 0, 255],
gainsboro: [220, 220, 220],
ghostwhite: [248, 248, 255],
gold: [255, 215, 0],
goldenrod: [218, 165, 32],
gray: [128, 128, 128],
green: [0, 128, 0],
greenyellow: [173, 255, 47],
grey: [128, 128, 128],
honeydew: [240, 255, 240],
hotpink: [255, 105, 180],
indianred: [205, 92, 92],
indigo: [75, 0, 130],
ivory: [255, 255, 240],
khaki: [240, 230, 140],
lavender: [230, 230, 250],
lavenderblush: [255, 240, 245],
lawngreen: [124, 252, 0],
lemonchiffon: [255, 250, 205],
lightblue: [173, 216, 230],
lightcoral: [240, 128, 128],
lightcyan: [224, 255, 255],
lightgoldenrodyellow: [250, 250, 210],
lightgray: [211, 211, 211],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightsalmon: [255, 160, 122],
lightseagreen: [32, 178, 170],
lightskyblue: [135, 206, 250],
lightslategray: [119, 136, 153],
lightslategrey: [119, 136, 153],
lightsteelblue: [176, 196, 222],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
limegreen: [50, 205, 50],
linen: [250, 240, 230],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
mediumaquamarine: [102, 205, 170],
mediumblue: [0, 0, 205],
mediumorchid: [186, 85, 211],
mediumpurple: [147, 112, 219],
mediumseagreen: [60, 179, 113],
mediumslateblue: [123, 104, 238],
mediumspringgreen: [0, 250, 154],
mediumturquoise: [72, 209, 204],
mediumvioletred: [199, 21, 133],
midnightblue: [25, 25, 112],
mintcream: [245, 255, 250],
mistyrose: [255, 228, 225],
moccasin: [255, 228, 181],
navajowhite: [255, 222, 173],
navy: [0, 0, 128],
oldlace: [253, 245, 230],
olive: [128, 128, 0],
olivedrab: [107, 142, 35],
orange: [255, 165, 0],
orangered: [255, 69, 0],
orchid: [218, 112, 214],
palegoldenrod: [238, 232, 170],
palegreen: [152, 251, 152],
paleturquoise: [175, 238, 238],
palevioletred: [219, 112, 147],
papayawhip: [255, 239, 213],
peachpuff: [255, 218, 185],
peru: [205, 133, 63],
pink: [255, 192, 203],
plum: [221, 160, 221],
powderblue: [176, 224, 230],
purple: [128, 0, 128],
rebeccapurple: [102, 51, 153],
red: [255, 0, 0],
rosybrown: [188, 143, 143],
royalblue: [65, 105, 225],
saddlebrown: [139, 69, 19],
salmon: [250, 128, 114],
sandybrown: [244, 164, 96],
seagreen: [46, 139, 87],
seashell: [255, 245, 238],
sienna: [160, 82, 45],
silver: [192, 192, 192],
skyblue: [135, 206, 235],
slateblue: [106, 90, 205],
slategray: [112, 128, 144],
slategrey: [112, 128, 144],
snow: [255, 250, 250],
springgreen: [0, 255, 127],
steelblue: [70, 130, 180],
tan: [210, 180, 140],
teal: [0, 128, 128],
thistle: [216, 191, 216],
tomato: [255, 99, 71],
transparent: [0, 0, 0],
turquoise: [64, 224, 208],
violet: [238, 130, 238],
wheat: [245, 222, 179],
white: [255, 255, 255],
whitesmoke: [245, 245, 245],
yellow: [255, 255, 0],
yellowgreen: [154, 205, 50]
};
return names[name] && names[name].map(c => c / 2.55);
}
/* Convert a Hex to Red/Green/Blue
/* ========================================================================== */
function convertHtoRGB(hex) {
// #<hex-color>{3,4,6,8}
const [r, g, b, a, rr, gg, bb, aa] = (hex.match(hexColorMatch$1) || []).slice(1);
if (rr !== undefined || r !== undefined) {
const red = rr !== undefined ? parseInt(rr, 16) : r !== undefined ? parseInt(r + r, 16) : 0;
const green = gg !== undefined ? parseInt(gg, 16) : g !== undefined ? parseInt(g + g, 16) : 0;
const blue = bb !== undefined ? parseInt(bb, 16) : b !== undefined ? parseInt(b + b, 16) : 0;
const alpha = aa !== undefined ? parseInt(aa, 16) : a !== undefined ? parseInt(a + a, 16) : 255;
return [red, green, blue, alpha].map(c => c / 2.55);
}
return undefined;
}
const hexColorMatch$1 = /^#(?:([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?|([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?)$/i;
class Color {
constructor(color) {
this.color = Object(Object(color).color || color);
this.color.colorspace = this.color.colorspace
? this.color.colorspace
: 'red' in color && 'green' in color && 'blue' in color
? 'rgb'
: 'hue' in color && 'saturation' in color && 'lightness' in color
? 'hsl'
: 'hue' in color && 'whiteness' in color && 'blackness' in color
? 'hwb'
: 'unknown';
if (color.colorspace === 'rgb') {
this.color.hue = convertColors.rgb2hue(color.red, color.green, color.blue, color.hue || 0);
}
}
alpha(alpha) {
const color = this.color;
return alpha === undefined
? color.alpha
: new Color(assign(color, { alpha }));
}
blackness(blackness) {
const hwb = color2hwb(this.color);
return blackness === undefined
? hwb.blackness
: new Color(assign(hwb, { blackness }));
}
blend(color, percentage, colorspace = 'rgb') {
const base = this.color;
return new Color(blend(base, color, percentage, colorspace));
}
blenda(color, percentage, colorspace = 'rgb') {
const base = this.color;
return new Color(blend(base, color, percentage, colorspace, true));
}
blue(blue) {
const rgb = color2rgb(this.color);
return blue === undefined
? rgb.blue
: new Color(assign(rgb, { blue }));
}
contrast(percentage) {
const base = this.color;
return new Color(contrast(base, percentage));
}
green(green) {
const rgb = color2rgb(this.color);
return green === undefined
? rgb.green
: new Color(assign(rgb, { green }));
}
hue(hue) {
const hsl = color2hsl(this.color);
return hue === undefined
? hsl.hue
: new Color(assign(hsl, { hue }));
}
lightness(lightness) {
const hsl = color2hsl(this.color);
return lightness === undefined
? hsl.lightness
: new Color(assign(hsl, { lightness }))
}
red(red) {
const rgb = color2rgb(this.color);
return red === undefined
? rgb.red
: new Color(assign(rgb, { red }));
}
rgb(red, green, blue) {
const rgb = color2rgb(this.color);
return new Color(assign(rgb, { red, green, blue }));
}
saturation(saturation) {
const hsl = color2hsl(this.color);
return saturation === undefined
? hsl.saturation
: new Color(assign(hsl, { saturation }));
}
shade(percentage) {
const hwb = color2hwb(this.color);
const shade = { hue: 0, whiteness: 0, blackness: 100, colorspace: 'hwb' };
const colorspace = 'rgb';
return percentage === undefined
? hwb.blackness
: new Color(blend(hwb, shade, percentage, colorspace));
}
tint(percentage) {
const hwb = color2hwb(this.color);
const tint = { hue: 0, whiteness: 100, blackness: 0, colorspace: 'hwb' };
const colorspace = 'rgb';
return percentage === undefined
? hwb.blackness
: new Color(blend(hwb, tint, percentage, colorspace));
}
whiteness(whiteness) {
const hwb = color2hwb(this.color);
return whiteness === undefined
? hwb.whiteness
: new Color(assign(hwb, { whiteness }));
}
toHSL() {
return color2hslString(this.color);
}
toHWB() {
return color2hwbString(this.color);
}
toLegacy() {
return color2legacyString(this.color);
}
toRGB() {
return color2rgbString(this.color);
}
toRGBLegacy() {
return color2rgbLegacyString(this.color);
}
toString() {
return color2string(this.color);
}
}
/* Blending
/* ========================================================================== */
function blend(base, color, percentage, colorspace, isBlendingAlpha) {
const addition = percentage / 100;
const subtraction = 1 - addition;
if (colorspace === 'hsl') {
const { hue: h1, saturation: s1, lightness: l1, alpha: a1 } = color2hsl(base);
const { hue: h2, saturation: s2, lightness: l2, alpha: a2 } = color2hsl(color);
const [hue, saturation, lightness, alpha] = [
h1 * subtraction + h2 * addition,
s1 * subtraction + s2 * addition,
l1 * subtraction + l2 * addition,
isBlendingAlpha
? a1 * subtraction + a2 * addition
: a1
];
return { hue, saturation, lightness, alpha, colorspace: 'hsl' };
} else if (colorspace === 'hwb') {
const { hue: h1, whiteness: w1, blackness: b1, alpha: a1 } = color2hwb(base);
const { hue: h2, whiteness: w2, blackness: b2, alpha: a2 } = color2hwb(color);
const [hue, whiteness, blackness, alpha] = [
h1 * subtraction + h2 * addition,
w1 * subtraction + w2 * addition,
b1 * subtraction + b2 * addition,
isBlendingAlpha
? a1 * subtraction + a2 * addition
: a1
];
return { hue, whiteness, blackness, alpha, colorspace: 'hwb' };
} else {
const { red: r1, green: g1, blue: b1, alpha: a1 } = color2rgb(base);
const { red: r2, green: g2, blue: b2, alpha: a2 } = color2rgb(color);
const [red, green, blue, alpha] = [
r1 * subtraction + r2 * addition,
g1 * subtraction + g2 * addition,
b1 * subtraction + b2 * addition,
isBlendingAlpha
? a1 * subtraction + a2 * addition
: a1
];
return { red, green, blue, alpha, colorspace: 'rgb' };
}
}
/* Assign channels to a new instance of a base color
/* ========================================================================== */
function assign(base, channels) {
const color = Object.assign({}, base);
Object.keys(channels).forEach(
channel => {
// detect channel
const channelIsHue = channel === 'hue';
const isRGB = !channelIsHue && blueGreenRedMatch.test(channel);
// normalized value of the channel
const value = normalize(channels[channel], channel);
// assign channel to new object
color[channel] = value;
if (isRGB) {
// conditionally preserve the hue
color.hue = convertColors.rgb2hue(color.red, color.green, color.blue, base.hue || 0);
}
}
);
return color;
}
function normalize(value, channel) {
// detect channel
const channelIsHue = channel === 'hue';
// value limitations
const min = 0;
const max = channelIsHue ? 360 : 100;
const normalizedValue = Math.min(Math.max(channelIsHue
? value % 360
: value, min), max);
return normalizedValue;
}
/* Convert colors
/* ========================================================================== */
function color2rgb(color) {
const [ red, green, blue ] = color.colorspace === 'hsl'
? convertColors.hsl2rgb(color.hue, color.saturation, color.lightness)
: color.colorspace === 'hwb'
? convertColors.hwb2rgb(color.hue, color.whiteness, color.blackness)
: [ color.red, color.green, color.blue ];
return { red, green, blue, hue: color.hue, alpha: color.alpha, colorspace: 'rgb' };
}
function color2hsl(color) {
const [ hue, saturation, lightness ] = color.colorspace === 'rgb'
? convertColors.rgb2hsl(color.red, color.green, color.blue, color.hue)
: color.colorspace === 'hwb'
? convertColors.hwb2hsl(color.hue, color.whiteness, color.blackness)
: [ color.hue, color.saturation, color.lightness ];
return { hue, saturation, lightness, alpha: color.alpha, colorspace: 'hsl' };
}
function color2hwb(color) {
const [ hue, whiteness, blackness ] = color.colorspace === 'rgb'
? convertColors.rgb2hwb(color.red, color.green, color.blue, color.hue)
: color.colorspace === 'hsl'
? convertColors.hsl2hwb(color.hue, color.saturation, color.lightness)
: [ color.hue, color.whiteness, color.blackness ];
return { hue, whiteness, blackness, alpha: color.alpha, colorspace: 'hwb' };
}
/* Contrast functions
/* ========================================================================== */
function contrast(color, percentage) {
// https://drafts.csswg.org/css-color/#contrast-adjuster
const hwb = color2hwb(color);
const rgb = color2rgb(color);
// compute the luminance of the color.
const luminance = rgb2luminance(rgb.red, rgb.green, rgb.blue);
// the maximum-contrast color, if it is less than .5
const maxContrastColor = luminance < 0.5
// hwb(X, 100%, 0%), where X is the hue angle of the color
? { hue: hwb.hue, whiteness: 100, blackness: 0, alpha: hwb.alpha, colorspace: 'hwb' }
// otherwise, hwb(X, 0%, 100%), where X is the hue angle of the color
: { hue: hwb.hue, whiteness: 0, blackness: 100, alpha: hwb.alpha, colorspace: 'hwb' };
// contrast ratio
const contrastRatio = colors2contrast(color, maxContrastColor);
const minContrastColor = contrastRatio > 4.5
// the color with the smallest contrast ratio with the base color that is greater than 4.5
? colors2contrastRatioColor(hwb, maxContrastColor)
// otherwise, the maximum-contrast color
: maxContrastColor;
// color(maximum-contrast blend(minimum-contrast <percentage> hwb)));
return blend(maxContrastColor, minContrastColor, percentage, 'hwb', false);
}
function colors2contrast(color1, color2) {
// https://drafts.csswg.org/css-color/#contrast-ratio
const rgb1 = color2rgb(color1);
const rgb2 = color2rgb(color2);
const l1 = rgb2luminance(rgb1.red, rgb1.green, rgb1.blue);
const l2 = rgb2luminance(rgb2.red, rgb2.green, rgb2.blue);
return l1 > l2
// if l1 is the relative luminance of the lighter of the colors
? (l1 + 0.05) / (l2 + 0.05)
// otherwise, if l2 is the relative luminance of the lighter of the colors
: (l2 + 0.05) / (l1 + 0.05);
}
function rgb2luminance(red, green, blue) {
const [ redLuminance, greenLuminance, blueLuminance ] = [
channel2luminance(red),
channel2luminance(green),
channel2luminance(blue)
];
// https://drafts.csswg.org/css-color/#luminance
const luminance = 0.2126 * redLuminance + 0.7152 * greenLuminance + 0.0722 * blueLuminance;
return luminance;
}
function channel2luminance(value) {
// https://drafts.csswg.org/css-color/#luminance
const luminance = value <= 0.03928 ? value / 12.92 : Math.pow((value + 0.055) /1.055, 2.4);
return luminance;
}
// return the smallest contrast ratio from a color and a maximum contrast (credit: @thetalecrafter)
function colors2contrastRatioColor(hwb, maxHWB) {
const modifiedHWB = Object.assign({}, hwb);
// values to be used for linear interpolations in HWB space
let minW = hwb.whiteness;
let minB = hwb.blackness;
let maxW = maxHWB.whiteness;
let maxB = maxHWB.blackness;
// find the color with the smallest contrast ratio with the base color that is greater than 4.5
while (Math.abs(minW - maxW) > 100 || Math.abs(minB - maxB) > 100) {
const midW = Math.round((maxW + minW) / 2);
const midB = Math.round((maxB + minB) / 2);
modifiedHWB.whiteness = midW;
modifiedHWB.blackness = midB;
if (colors2contrast(modifiedHWB, hwb) > 4.5) {
maxW = midW;
maxB = midB;
} else {
minW = midW;
minB = midB;
}
}
return modifiedHWB;
}
/* Match
/* ========================================================================== */
const blueGreenRedMatch = /^(blue|green|red)$/i;
/* Stringifiers
/* ========================================================================== */
function color2string(color) {
return color.colorspace === 'hsl'
? color2hslString(color)
: color.colorspace === 'hwb'
? color2hwbString(color)
: color2rgbString(color);
}
function color2hslString(color) {
const hsl = color2hsl(color);
const isOpaque = hsl.alpha === 100;
const hue = hsl.hue;
const saturation = Math.round(hsl.saturation * 10000000000) / 10000000000;
const lightness = Math.round(hsl.lightness * 10000000000) / 10000000000;
const alpha = Math.round(hsl.alpha * 10000000000) / 10000000000;
return `hsl(${hue} ${saturation}% ${lightness}%${isOpaque
? ''
: ` / ${alpha}%`})`;
}
function color2hwbString(color) {
const hwb = color2hwb(color);
const isOpaque = hwb.alpha === 100;
const hue = hwb.hue;
const whiteness = Math.round(hwb.whiteness * 10000000000) / 10000000000;
const blackness = Math.round(hwb.blackness * 10000000000) / 10000000000;
const alpha = Math.round(hwb.alpha * 10000000000) / 10000000000;
return `hwb(${hue} ${whiteness}% ${blackness}%${isOpaque
? ''
: ` / ${alpha}%`})`;
}
function color2rgbString(color) {
const rgb = color2rgb(color);
const isOpaque = rgb.alpha === 100;
const red = Math.round(rgb.red * 10000000000) / 10000000000;
const green = Math.round(rgb.green * 10000000000) / 10000000000;
const blue = Math.round(rgb.blue * 10000000000) / 10000000000;
const alpha = Math.round(rgb.alpha * 10000000000) / 10000000000;
return `rgb(${red}% ${green}% ${blue}%${isOpaque
? ''
: ` / ${alpha}%`})`;
}
function color2legacyString(color) {
return color.colorspace === 'hsl'
? color2hslLegacyString(color)
: color2rgbLegacyString(color);
}
function color2rgbLegacyString(color) {
const rgb = color2rgb(color);
const isOpaque = rgb.alpha === 100;
const name = isOpaque ? 'rgb' : 'rgba';
const red = Math.round(rgb.red * 255 / 100);
const green = Math.round(rgb.green * 255 / 100);
const blue = Math.round(rgb.blue * 255 / 100);
const alpha = Math.round(rgb.alpha / 100 * 10000000000) / 10000000000;
return `${name}(${red}, ${green}, ${blue}${isOpaque
? ''
: `, ${alpha}`})`;
}
function color2hslLegacyString(color) {
const hsl = color2hsl(color);
const isOpaque = hsl.alpha === 100;
const name = isOpaque ? 'hsl' : 'hsla';
const hue = hsl.hue;
const saturation = Math.round(hsl.saturation * 10000000000) / 10000000000;
const lightness = Math.round(hsl.lightness * 10000000000) / 10000000000;
const alpha = Math.round(hsl.alpha / 100 * 10000000000) / 10000000000;
return `${name}(${hue}, ${saturation}%, ${lightness}%${isOpaque
? ''
: `, ${alpha}`})`;
}
function manageUnresolved(node, opts, word, message) {
if ('warn' === opts.unresolved) {
opts.decl.warn(opts.result, message, { word });
} else if ('ignore' !== opts.unresolved) {
throw opts.decl.error(message, { word });
}
}
// tooling
/* Transform AST
/* ========================================================================== */
function transformAST(node, opts) {
node.nodes.slice(0).forEach((child, index) => {
if (isColorModFunction(child)) {
// transform any variables within the color-mod() function
if (opts.transformVars) {
transformVariables(child, opts);
}
// transform any color-mod() functions
const color = transformColorModFunction(child, opts);
if (color) {
// update the color-mod() function with the transformed value
node.nodes.splice(index, 1, {
type: 'word',
value: opts.stringifier(color)
});
}
} else if (child.nodes && Object(child.nodes).length) {
transformAST(child, opts);
}
});
}
/* Transform <var> functions
/* ========================================================================== */
function transformVariables(node, opts) {
parser.walk(node.nodes, (child, index, nodes) => {
if (isVariable(child)) {
// get the custom property and fallback value from var()
const [prop, fallbackNode] = transformArgsByParams(child, [
// <value> , [ <fallback> ]?
[transformWord, isComma, transformNode]
]);
// if the custom property is known
if (prop in opts.customProperties) {
let customPropertyValue = opts.customProperties[prop];
// follow custom properties referencing custom properties
if (looseVarMatch.test(parser.stringify(customPropertyValue))) {
const rootChildAST = JSON.parse(JSON.stringify({ nodes: customPropertyValue.nodes }));
transformVariables(rootChildAST, opts);
customPropertyValue = rootChildAST;
}
// replace var() with the custom property value
if (customPropertyValue.nodes.length) {
nodes.splice(index, 0, ...JSON.parse(JSON.stringify(customPropertyValue.nodes)));
}
nodes.splice(nodes.indexOf(child), 1);
} else if (fallbackNode && fallbackNode.nodes.length === 1 && fallbackNode.nodes[0].nodes.length) {
// otherwise, replace var() with the fallback value
transformVariables(fallbackNode, opts);
nodes.splice(index, 1, ...fallbackNode.nodes[0].nodes[0]);
}
}
});
}
/* Transform <color> functions
/* ========================================================================== */
function transformColor(node, opts) {
if (isRGBFunction(node)) {
return transformRGBFunction(node, opts);
} else if (isHSLFunction(node)) {
return transformHSLFunction(node, opts);
} else if (isHWBFunction(node)) {
return transformHWBFunction(node, opts);
} else if (isColorModFunction(node)) {
return transformColorModFunction(node, opts);
} else if (isHexColor(node)) {
return transformHexColor(node, opts);
} else if (isNamedColor(node)) {
return transformNamedColor(node, opts);
} else {
return manageUnresolved(node, opts, node.value, `Expected a color`);
}
}
// return a transformed rgb/rgba color function
function transformRGBFunction(node, opts) {
const [red, green, blue, alpha = 100] = transformArgsByParams(node, [
// <percentage> <percentage> <percentage> [ , <alpha-value> ]?
[transformPercentage, transformPercentage, transformPercentage, isSlash, transformAlpha],
// <number> <number> <number> [ , <alpha-value> ]?
[transformRGBNumber, transformRGBNumber, transformRGBNumber, isSlash, transformAlpha],
// <percentage> , <percentage> , <percentage> [ , <alpha-value> ]?
[transformPercentage, isComma, transformPercentage, isComma, transformPercentage, isComma, transformAlpha],
// <number> , <number> , <number> [ , <alpha-value> ]?
[transformRGBNumber, isComma, transformRGBNumber, isComma, transformRGBNumber, isComma, transformAlpha]
]);
if (red !== undefined) {
const color = new Color({ red, green, blue, alpha, colorspace: 'rgb' });
return color;
} else {
return manageUnresolved(node, opts, node.value, `Expected a valid rgb() function`);
}
}
// return a transformed hsl/hsla color function
function transformHSLFunction(node, opts) {
const [hue, saturation, lightness, alpha = 100] = transformArgsByParams(node, [
// <hue> <percentage> <percentage> [ / <alpha-value> ]?
[transformHue, transformPercentage, transformPercentage, isSlash, transformAlpha],
// <hue> , <percentage> , <percentage> [ , <alpha-value> ]?
[transformHue, isComma, transformPercentage, isComma, transformPercentage, isComma, transformAlpha]
]);
if (lightness !== undefined) {
const color = new Color({ hue, saturation, lightness, alpha, colorspace: 'hsl' });
return color;
} else {
return manageUnresolved(node, opts, node.value, `Expected a valid hsl() function`);
}
}
// return a transformed hwb color function