/
color.dart
1526 lines (1348 loc) · 55.4 KB
/
color.dart
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
// Copyright 2019 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'dart:collection';
import 'dart:math' as math;
import 'package:collection/collection.dart';
import '../callable.dart';
import '../deprecation.dart';
import '../evaluation_context.dart';
import '../exception.dart';
import '../module/built_in.dart';
import '../parse/scss.dart';
import '../util/map.dart';
import '../util/nullable.dart';
import '../util/number.dart';
import '../utils.dart';
import '../value.dart';
/// A regular expression matching the beginning of a proprietary Microsoft
/// filter declaration.
final _microsoftFilterStart = RegExp(r'^[a-zA-Z]+\s*=');
/// If a special number string is detected in these color spaces, even if they
/// were using the one-argument function syntax, we convert it to the three- or
/// four- argument comma-separated syntax for broader browser compatibility.
const _specialCommaSpaces = {ColorSpace.rgb, ColorSpace.hsl};
/// The global definitions of Sass color functions.
final global = UnmodifiableListView([
// ### RGB
_channelFunction("red", (color) => color.red, global: true),
_channelFunction("green", (color) => color.green, global: true),
_channelFunction("blue", (color) => color.blue, global: true),
_mix,
BuiltInCallable.overloadedFunction("rgb", {
r"$red, $green, $blue, $alpha": (arguments) => _rgb("rgb", arguments),
r"$red, $green, $blue": (arguments) => _rgb("rgb", arguments),
r"$color, $alpha": (arguments) => _rgbTwoArg("rgb", arguments),
r"$channels": (arguments) => _parseChannels("rgb", arguments[0],
space: ColorSpace.rgb, name: 'channels')
}),
BuiltInCallable.overloadedFunction("rgba", {
r"$red, $green, $blue, $alpha": (arguments) => _rgb("rgba", arguments),
r"$red, $green, $blue": (arguments) => _rgb("rgba", arguments),
r"$color, $alpha": (arguments) => _rgbTwoArg("rgba", arguments),
r"$channels": (arguments) => _parseChannels('rgba', arguments[0],
space: ColorSpace.rgb, name: 'channels')
}),
_function("invert", r"$color, $weight: 100%, $space: null",
(arguments) => _invert(arguments, global: true)),
// ### HSL
_channelFunction("hue", (color) => color.hue, unit: 'deg', global: true),
_channelFunction("saturation", (color) => color.saturation,
unit: '%', global: true),
_channelFunction("lightness", (color) => color.lightness,
unit: '%', global: true),
BuiltInCallable.overloadedFunction("hsl", {
r"$hue, $saturation, $lightness, $alpha": (arguments) =>
_hsl("hsl", arguments),
r"$hue, $saturation, $lightness": (arguments) => _hsl("hsl", arguments),
r"$hue, $saturation": (arguments) {
// hsl(123, var(--foo)) is valid CSS because --foo might be `10%, 20%` and
// functions are parsed after variable substitution.
if (arguments[0].isVar || arguments[1].isVar) {
return _functionString('hsl', arguments);
} else {
throw SassScriptException(r"Missing argument $lightness.");
}
},
r"$channels": (arguments) => _parseChannels('hsl', arguments[0],
space: ColorSpace.hsl, name: 'channels')
}),
BuiltInCallable.overloadedFunction("hsla", {
r"$hue, $saturation, $lightness, $alpha": (arguments) =>
_hsl("hsla", arguments),
r"$hue, $saturation, $lightness": (arguments) => _hsl("hsla", arguments),
r"$hue, $saturation": (arguments) {
if (arguments[0].isVar || arguments[1].isVar) {
return _functionString('hsla', arguments);
} else {
throw SassScriptException(r"Missing argument $lightness.");
}
},
r"$channels": (arguments) => _parseChannels('hsla', arguments[0],
space: ColorSpace.hsl, name: 'channels')
}),
_function(
"grayscale",
r"$color",
(arguments) => arguments[0] is SassNumber || arguments[0].isSpecialNumber
// Use the native CSS `grayscale` filter function.
? _functionString('grayscale', arguments)
: _grayscale(arguments[0])),
_function("adjust-hue", r"$color, $degrees", (arguments) {
var color = arguments[0].assertColor("color");
var degrees = _angleValue(arguments[1], "degrees");
var suggestedValue = SassNumber(degrees, 'deg');
warnForDeprecation(
"adjust-hue() is deprecated. Suggestion:\n"
"\n"
"color.adjust(\$color, \$hue: $suggestedValue)\n"
"\n"
"More info: https://sass-lang.com/d/color-functions",
Deprecation.colorFunctions);
return color.changeHsl(hue: color.hue + degrees);
}),
_function("lighten", r"$color, $amount", (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
var result = color.changeHsl(
lightness: (color.lightness + amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
warnForDeprecation(
"lighten() is deprecated. "
"${_suggestScaleAndAdjust(color, amount.value, 'lightness')}\n"
"\n"
"More info: https://sass-lang.com/d/color-functions",
Deprecation.colorFunctions);
return result;
}),
_function("darken", r"$color, $amount", (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
var result = color.changeHsl(
lightness: (color.lightness - amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
warnForDeprecation(
"darken() is deprecated. "
"${_suggestScaleAndAdjust(color, -amount.value, 'lightness')}\n"
"\n"
"More info: https://sass-lang.com/d/color-functions",
Deprecation.colorFunctions);
return result;
}),
BuiltInCallable.overloadedFunction("saturate", {
r"$amount": (arguments) {
if (arguments[0] is SassNumber || arguments[0].isSpecialNumber) {
// Use the native CSS `saturate` filter function.
return _functionString("saturate", arguments);
}
var number = arguments[0].assertNumber("amount");
return SassString("saturate(${number.toCssString()})", quotes: false);
},
r"$color, $amount": (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
var result = color.changeHsl(
saturation: (color.saturation + amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
warnForDeprecation(
"saturate() is deprecated. "
"${_suggestScaleAndAdjust(color, amount.value, 'saturation')}\n"
"\n"
"More info: https://sass-lang.com/d/color-functions",
Deprecation.colorFunctions);
return result;
}
}),
_function("desaturate", r"$color, $amount", (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
var result = color.changeHsl(
saturation: (color.saturation - amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
warnForDeprecation(
"desaturate() is deprecated. "
"${_suggestScaleAndAdjust(color, -amount.value, 'saturation')}\n"
"\n"
"More info: https://sass-lang.com/d/color-functions",
Deprecation.colorFunctions);
return result;
}),
// ### Opacity
_function("opacify", r"$color, $amount",
(arguments) => _opacify("opacify", arguments)),
_function("fade-in", r"$color, $amount",
(arguments) => _opacify("fade-in", arguments)),
_function("transparentize", r"$color, $amount",
(arguments) => _transparentize("transparentize", arguments)),
_function("fade-out", r"$color, $amount",
(arguments) => _transparentize("fade-out", arguments)),
BuiltInCallable.overloadedFunction("alpha", {
r"$color": (arguments) {
var argument = arguments[0];
if (argument is SassString &&
!argument.hasQuotes &&
argument.text.contains(_microsoftFilterStart)) {
// Support the proprietary Microsoft alpha() function.
return _functionString("alpha", arguments);
}
var color = argument.assertColor("color");
return SassNumber(color.alpha);
},
r"$args...": (arguments) {
var argList = arguments[0].asList;
if (argList.isNotEmpty &&
argList.every((argument) =>
argument is SassString &&
!argument.hasQuotes &&
argument.text.contains(_microsoftFilterStart))) {
// Support the proprietary Microsoft alpha() function.
return _functionString("alpha", arguments);
}
assert(argList.length != 1);
if (argList.isEmpty) {
throw SassScriptException("Missing argument \$color.");
} else {
throw SassScriptException(
"Only 1 argument allowed, but ${argList.length} were passed.");
}
}
}),
_function("opacity", r"$color", (arguments) {
if (arguments[0] is SassNumber || arguments[0].isSpecialNumber) {
// Use the native CSS `opacity` filter function.
return _functionString("opacity", arguments);
}
var color = arguments[0].assertColor("color");
return SassNumber(color.alpha);
}),
// ### Color Spaces
_function(
"color",
r"$description",
(arguments) =>
_parseChannels("color", arguments[0], name: 'description')),
_function(
"hwb",
r"$channels",
(arguments) => _parseChannels("hwb", arguments[0],
space: ColorSpace.hwb, name: 'channels')),
_function(
"lab",
r"$channels",
(arguments) => _parseChannels("lab", arguments[0],
space: ColorSpace.lab, name: 'channels')),
_function(
"lch",
r"$channels",
(arguments) => _parseChannels("lch", arguments[0],
space: ColorSpace.lch, name: 'channels')),
_function(
"oklab",
r"$channels",
(arguments) => _parseChannels("oklab", arguments[0],
space: ColorSpace.oklab, name: 'channels')),
_function(
"oklch",
r"$channels",
(arguments) => _parseChannels("oklch", arguments[0],
space: ColorSpace.oklch, name: 'channels')),
_complement,
// ### Miscellaneous
_ieHexStr,
_adjust.withName("adjust-color"),
_scale.withName("scale-color"),
_change.withName("change-color")
]);
/// The Sass color module.
final module = BuiltInModule("color", functions: <Callable>[
// ### RGB
_channelFunction("red", (color) => color.red),
_channelFunction("green", (color) => color.green),
_channelFunction("blue", (color) => color.blue),
_mix,
_function("invert", r"$color, $weight: 100%, $space: null", (arguments) {
var result = _invert(arguments);
if (result is SassString) {
warnForDeprecation(
"Passing a number (${arguments[0]}) to color.invert() is "
"deprecated.\n"
"\n"
"Recommendation: $result",
Deprecation.colorModuleCompat);
}
return result;
}),
// ### HSL
_channelFunction("hue", (color) => color.hue, unit: 'deg'),
_channelFunction("saturation", (color) => color.saturation, unit: '%'),
_channelFunction("lightness", (color) => color.lightness, unit: '%'),
_removedColorFunction("adjust-hue", "hue"),
_removedColorFunction("lighten", "lightness"),
_removedColorFunction("darken", "lightness", negative: true),
_removedColorFunction("saturate", "saturation"),
_removedColorFunction("desaturate", "saturation", negative: true),
_function("grayscale", r"$color", (arguments) {
if (arguments[0] is SassNumber) {
var result = _functionString("grayscale", arguments.take(1));
warnForDeprecation(
"Passing a number (${arguments[0]}) to color.grayscale() is "
"deprecated.\n"
"\n"
"Recommendation: $result",
Deprecation.colorModuleCompat);
return result;
}
return _grayscale(arguments[0]);
}),
// ### HWB
BuiltInCallable.overloadedFunction("hwb", {
r"$hue, $whiteness, $blackness, $alpha: 1": (arguments) => _parseChannels(
'hwb',
SassList([
SassList(
[arguments[0], arguments[1], arguments[2]], ListSeparator.space),
arguments[3]
], ListSeparator.slash),
space: ColorSpace.hwb),
r"$channels": (arguments) => _parseChannels('hwb', arguments[0],
space: ColorSpace.hwb, name: 'channels')
}),
_channelFunction("whiteness", (color) => color.whiteness, unit: '%'),
_channelFunction("blackness", (color) => color.blackness, unit: '%'),
// ### Opacity
_removedColorFunction("opacify", "alpha"),
_removedColorFunction("fade-in", "alpha"),
_removedColorFunction("transparentize", "alpha", negative: true),
_removedColorFunction("fade-out", "alpha", negative: true),
BuiltInCallable.overloadedFunction("alpha", {
r"$color": (arguments) {
var argument = arguments[0];
if (argument is SassString &&
!argument.hasQuotes &&
argument.text.contains(_microsoftFilterStart)) {
var result = _functionString("alpha", arguments);
warnForDeprecation(
"Using color.alpha() for a Microsoft filter is deprecated.\n"
"\n"
"Recommendation: $result",
Deprecation.colorModuleCompat);
return result;
}
var color = argument.assertColor("color");
return SassNumber(color.alpha);
},
r"$args...": (arguments) {
if (arguments[0].asList.every((argument) =>
argument is SassString &&
!argument.hasQuotes &&
argument.text.contains(_microsoftFilterStart))) {
// Support the proprietary Microsoft alpha() function.
var result = _functionString("alpha", arguments);
warnForDeprecation(
"Using color.alpha() for a Microsoft filter is deprecated.\n"
"\n"
"Recommendation: $result",
Deprecation.colorModuleCompat);
return result;
}
assert(arguments.length != 1);
throw SassScriptException(
"Only 1 argument allowed, but ${arguments.length} were passed.");
}
}),
_function("opacity", r"$color", (arguments) {
if (arguments[0] is SassNumber) {
var result = _functionString("opacity", arguments);
warnForDeprecation(
"Passing a number (${arguments[0]} to color.opacity() is "
"deprecated.\n"
"\n"
"Recommendation: $result",
Deprecation.colorModuleCompat);
return result;
}
var color = arguments[0].assertColor("color");
return SassNumber(color.alpha);
}),
// ### Color Spaces
_function(
"space",
r"$color",
(arguments) => SassString(arguments.first.assertColor("color").space.name,
quotes: false)),
_function("to-space", r"$color, $space", (arguments) {
var converted = _colorInSpace(arguments[0], arguments[1]);
// `color.to-space()` never returns missing channels for legacy color
// spaces because they're less compatible and users are probably using a
// legacy space because they want a highly compatible color.
return converted.isLegacy &&
(converted.isChannel0Missing ||
converted.isChannel1Missing ||
converted.isChannel2Missing ||
converted.isAlphaMissing) &&
converted.space != (arguments[0] as SassColor).space
? SassColor.forSpaceInternal(converted.space, converted.channel0,
converted.channel1, converted.channel2, converted.alpha)
: converted;
}),
_function("is-legacy", r"$color",
(arguments) => SassBoolean(arguments[0].assertColor("color").isLegacy)),
_function(
"is-missing",
r"$color, $channel",
(arguments) => SassBoolean(arguments[0]
.assertColor("color")
.isChannelMissing(_channelName(arguments[1]),
colorName: "color", channelName: "channel"))),
_function(
"is-in-gamut",
r"$color, $space: null",
(arguments) =>
SassBoolean(_colorInSpace(arguments[0], arguments[1]).isInGamut)),
_function("to-gamut", r"$color, $space: null, $method: null", (arguments) {
var color = arguments[0].assertColor("color");
var space = _spaceOrDefault(color, arguments[1], "space");
if (arguments[2] == sassNull) {
throw SassScriptException(
"color.to-gamut() requires a \$method argument for forwards-"
"compatibility with changes in the CSS spec. Suggestion:\n"
"\n"
"\$method: local-minde",
"method");
}
// Assign this before checking [space.isBounded] so that invalid method
// names consistently produce errors.
var method = GamutMapMethod.fromName(
(arguments[2].assertString("method")..assertUnquoted("method")).text);
if (!space.isBounded) return color;
return color.toSpace(space).toGamut(method).toSpace(color.space);
}),
_function("channel", r"$color, $channel, $space: null", (arguments) {
var color = _colorInSpace(arguments[0], arguments[2]);
var channelName = _channelName(arguments[1]);
if (channelName == "alpha") return SassNumber(color.alpha);
var channelIndex = color.space.channels
.indexWhere((channel) => channel.name == channelName);
if (channelIndex == -1) {
throw SassScriptException(
"Color $color has no channel named $channelName.", "channel");
}
var channelInfo = color.space.channels[channelIndex];
var channelValue = color.channels[channelIndex];
var unit = channelInfo.associatedUnit;
if (unit == '%') {
channelValue = channelValue * 100 / (channelInfo as LinearChannel).max;
}
return SassNumber(channelValue, unit);
}),
_function("same", r"$color1, $color2", (arguments) {
var color1 = arguments[0].assertColor('color1');
var color2 = arguments[1].assertColor('color2');
// Convert both colors into the same space to compare them. Usually we
// just use color1's space, but since HSL and HWB can't represent
// out-of-gamut colors we use RGB for all legacy color spaces.
var targetSpace = color1.isLegacy ? ColorSpace.rgb : color1.space;
return SassBoolean(
color1.toSpace(targetSpace) == color2.toSpace(targetSpace));
}),
_function(
"is-powerless",
r"$color, $channel, $space: null",
(arguments) => SassBoolean(_colorInSpace(arguments[0], arguments[2])
.isChannelPowerless(_channelName(arguments[1]),
colorName: "color", channelName: "channel"))),
_complement,
// Miscellaneous
_adjust, _scale, _change, _ieHexStr
]);
// ### RGB
final _mix = _function("mix", r"$color1, $color2, $weight: 50%, $method: null",
(arguments) {
var color1 = arguments[0].assertColor("color1");
var color2 = arguments[1].assertColor("color2");
var weight = arguments[2].assertNumber("weight");
if (arguments[3] != sassNull) {
return color1.interpolate(
color2, InterpolationMethod.fromValue(arguments[3], "method"),
weight: weight.valueInRangeWithUnit(0, 100, "weight", "%") / 100);
}
_checkPercent(weight, "weight");
if (!color1.isLegacy) {
throw SassScriptException(
"To use color.mix() with non-legacy color $color1, you must provide a "
"\$method.",
"color1");
} else if (!color2.isLegacy) {
throw SassScriptException(
"To use color.mix() with non-legacy color $color2, you must provide a "
"\$method.",
"color2");
}
return _mixLegacy(color1, color2, weight);
});
// ### Color Spaces
final _complement =
_function("complement", r"$color, $space: null", (arguments) {
var color = arguments[0].assertColor("color");
var space = color.isLegacy && arguments[1] == sassNull
? ColorSpace.hsl
: ColorSpace.fromName(
(arguments[1].assertString("space")..assertUnquoted("space")).text,
"space");
if (!space.isPolar) {
throw SassScriptException(
"Color space $space doesn't have a hue channel.", 'space');
}
var inSpace = color.toSpace(space);
return inSpace.changeChannels({'hue': inSpace.channel('hue') + 180}).toSpace(
color.space);
});
/// The implementation of the `invert()` function.
///
/// If [global] is true, that indicates that this is being called from the
/// global `invert()` function.
Value _invert(List<Value> arguments, {bool global = false}) {
var weightNumber = arguments[1].assertNumber("weight");
if (arguments[0] is SassNumber || (global && arguments[0].isSpecialNumber)) {
if (weightNumber.value != 100 || !weightNumber.hasUnit("%")) {
throw "Only one argument may be passed to the plain-CSS invert() "
"function.";
}
// Use the native CSS `invert` filter function.
return _functionString("invert", arguments.take(1));
}
var color = arguments[0].assertColor("color");
if (arguments[2] == sassNull) {
if (!color.isLegacy) {
throw SassScriptException(
"To use color.invert() with non-legacy color $color, you must provide "
"a \$space.",
"color");
}
_checkPercent(weightNumber, "weight");
var rgb = color.toSpace(ColorSpace.rgb);
return _mixLegacy(
SassColor.rgb(255.0 - rgb.channel0, 255.0 - rgb.channel1,
255.0 - rgb.channel2, color.alphaOrNull),
color,
weightNumber);
}
var space = ColorSpace.fromName(
(arguments[2].assertString('space')..assertUnquoted('space')).text,
'space');
var weight = weightNumber.valueInRangeWithUnit(0, 100, 'weight', '%') / 100;
if (fuzzyEquals(weight, 0)) return color;
var inSpace = color.toSpace(space);
var inverted = switch (space) {
ColorSpace.hwb => SassColor.hwb((inSpace.channel0 + 180) % 360,
inSpace.channel2, inSpace.channel1, inSpace.alpha),
ColorSpace.hsl => SassColor.hsl((inSpace.channel0 + 180) % 360,
inSpace.channel1, 100 - inSpace.channel2, inSpace.alpha),
ColorSpace.lch => SassColor.lch(100 - inSpace.channel0, inSpace.channel1,
(inSpace.channel2 + 180) % 360, inSpace.alpha),
ColorSpace.oklch => SassColor.oklch(1 - inSpace.channel0, inSpace.channel1,
(inSpace.channel2 + 180) % 360, inSpace.alpha),
ColorSpace(
channels: [
LinearChannel channel0,
LinearChannel channel1,
LinearChannel channel2
]
) =>
SassColor.forSpaceInternal(
space,
_invertChannel(channel0, inSpace.channel0),
_invertChannel(channel1, inSpace.channel1),
_invertChannel(channel2, inSpace.channel2),
inSpace.alpha),
_ => throw UnsupportedError("Unknown color space $space.")
};
if (fuzzyEquals(weight, 1)) return inverted;
return color.interpolate(inverted, InterpolationMethod(space),
weight: 1 - weight);
}
/// Returns the inverse of the given [value] in a linear color channel.
double _invertChannel(LinearChannel channel, double value) =>
channel.min < 0 ? -value : channel.max - value;
/// The implementation of the `grayscale()` function, without any logic for the
/// plain-CSS `grayscale()` syntax.
Value _grayscale(Value colorArg) {
var color = colorArg.assertColor("color");
if (color.isLegacy) {
var hsl = color.toSpace(ColorSpace.hsl);
return SassColor.hsl(hsl.channel0, 0, hsl.channel2, hsl.alpha)
.toSpace(color.space);
} else {
var oklch = color.toSpace(ColorSpace.oklch);
return SassColor.oklch(oklch.channel0, 0, oklch.channel2, oklch.alpha)
.toSpace(color.space);
}
}
// Miscellaneous
final _adjust = _function("adjust", r"$color, $kwargs...",
(arguments) => _updateComponents(arguments, adjust: true));
final _scale = _function("scale", r"$color, $kwargs...",
(arguments) => _updateComponents(arguments, scale: true));
final _change = _function("change", r"$color, $kwargs...",
(arguments) => _updateComponents(arguments, change: true));
final _ieHexStr = _function("ie-hex-str", r"$color", (arguments) {
var color = arguments[0]
.assertColor("color")
.toSpace(ColorSpace.rgb)
.toGamut(GamutMapMethod.localMinde);
String hexString(double component) =>
fuzzyRound(component).toRadixString(16).padLeft(2, '0').toUpperCase();
return SassString(
"#${hexString(color.alpha * 255)}${hexString(color.channel0)}"
"${hexString(color.channel1)}${hexString(color.channel2)}",
quotes: false);
});
/// Implementation for `color.change`, `color.adjust`, and `color.scale`.
///
/// Exactly one of [change], [adjust], and [scale] must be true to determine
/// which function should be executed.
SassColor _updateComponents(List<Value> arguments,
{bool change = false, bool adjust = false, bool scale = false}) {
assert([change, adjust, scale].where((x) => x).length == 1);
var argumentList = arguments[1] as SassArgumentList;
if (argumentList.asList.isNotEmpty) {
throw SassScriptException(
"Only one positional argument is allowed. All other arguments must "
"be passed by name.");
}
var keywords = Map.of(argumentList.keywords);
var originalColor = arguments[0].assertColor("color");
var spaceKeyword = keywords.remove("space")?.assertString("space")
?..assertUnquoted("space");
var alphaArg = keywords.remove('alpha')?.assertNumber('alpha');
// For backwards-compatibility, we allow legacy colors to modify channels in
// any legacy color space.
var color =
spaceKeyword == null && originalColor.isLegacy && keywords.isNotEmpty
? _sniffLegacyColorSpace(keywords).andThen(originalColor.toSpace) ??
originalColor
: _colorInSpace(originalColor, spaceKeyword ?? sassNull);
var oldChannels = color.channels;
var channelArgs = List<Value?>.filled(oldChannels.length, null);
var channelInfo = color.space.channels;
for (var (name, value) in keywords.pairs) {
var channelIndex = channelInfo.indexWhere((info) => name == info.name);
if (channelIndex == -1) {
throw SassScriptException(
"Color space ${color.space} doesn't have a channel with this name.",
name);
}
channelArgs[channelIndex] = value;
}
SassColor result;
if (change) {
result = _changeColor(color, channelArgs, alphaArg);
} else {
var channelNumbers = [
for (var i = 0; i < channelInfo.length; i++)
channelArgs[i]?.assertNumber(channelInfo[i].name)
];
result = scale
? _scaleColor(color, channelNumbers, alphaArg)
: _adjustColor(color, channelNumbers, alphaArg);
}
return result.toSpace(originalColor.space);
}
/// Returns a copy of [color] with its channel values replaced by those in
/// [channelArgs] and [alphaArg], if specified.
SassColor _changeColor(
SassColor color, List<Value?> channelArgs, SassNumber? alphaArg) =>
_colorFromChannels(
color.space,
_channelForChange(channelArgs[0], color, 0),
_channelForChange(channelArgs[1], color, 1),
_channelForChange(channelArgs[2], color, 2),
alphaArg.andThen((alphaArg) {
if (!alphaArg.hasUnits) {
return alphaArg.value;
} else if (alphaArg.hasUnit('%')) {
return alphaArg.value / 100;
} else {
warnForDeprecation(
"\$alpha: Passing a unit other than % ($alphaArg) is "
"deprecated.\n"
"\n"
"To preserve current behavior: "
"${alphaArg.unitSuggestion('alpha')}\n"
"\n"
"See https://sass-lang.com/d/function-units",
Deprecation.functionUnits);
return alphaArg.value;
}
}) ??
color.alpha,
clamp: false);
/// Returns the value for a single channel in `color.change()`.
///
/// The [channelArg] is the argument passed in by the user, if one exists. If no
/// argument is passed, the channel at [index] in [color] is used instead.
SassNumber? _channelForChange(Value? channelArg, SassColor color, int channel) {
if (channelArg == null) {
return switch (color.channelsOrNull[channel]) {
var value? => SassNumber(
value,
(color.space == ColorSpace.hsl || color.space == ColorSpace.hwb) &&
channel > 0
? '%'
: null),
_ => null
};
}
if (_isNone(channelArg)) return null;
if (channelArg is SassNumber) return channelArg;
throw SassScriptException('$channelArg is not a number or unquoted "none".',
color.space.channels[channel].name);
}
/// Returns a copy of [color] with its channel values scaled by the values in
/// [channelArgs] and [alphaArg], if specified.
SassColor _scaleColor(
SassColor color, List<SassNumber?> channelArgs, SassNumber? alphaArg) =>
SassColor.forSpaceInternal(
color.space,
_scaleChannel(color.space.channels[0], color.channel0, channelArgs[0]),
_scaleChannel(color.space.channels[1], color.channel1, channelArgs[1]),
_scaleChannel(color.space.channels[2], color.channel2, channelArgs[2]),
_scaleChannel(ColorChannel.alpha, color.alpha, alphaArg));
/// Returns [oldValue] scaled by [factorArg] according to the definition in
/// [channel].
double _scaleChannel(
ColorChannel channel, double oldValue, SassNumber? factorArg) {
if (factorArg == null) return oldValue;
if (channel is! LinearChannel) {
throw SassScriptException("Channel isn't scalable.", channel.name);
}
var factor = (factorArg..assertUnit('%', channel.name))
.valueInRangeWithUnit(-100, 100, channel.name, '%') /
100;
return switch (factor) {
0 => oldValue,
> 0 => oldValue >= channel.max
? oldValue
: oldValue + (channel.max - oldValue) * factor,
_ => oldValue <= channel.min
? oldValue
: oldValue + (oldValue - channel.min) * factor
};
}
/// Returns a copy of [color] with its channel values adjusted by the values in
/// [channelArgs] and [alphaArg], if specified.
SassColor _adjustColor(
SassColor color, List<SassNumber?> channelArgs, SassNumber? alphaArg) =>
SassColor.forSpaceInternal(
color.space,
_adjustChannel(color.space, color.space.channels[0], color.channel0,
channelArgs[0]),
_adjustChannel(color.space, color.space.channels[1], color.channel1,
channelArgs[1]),
_adjustChannel(color.space, color.space.channels[2], color.channel2,
channelArgs[2]),
// The color space doesn't matter for alpha, as long as it's not
// strictly bounded.
_adjustChannel(
ColorSpace.lab, ColorChannel.alpha, color.alpha, alphaArg)
.clamp(0, 1));
/// Returns [oldValue] adjusted by [adjustmentArg] according to the definition
/// in [space]'s [channel].
double _adjustChannel(ColorSpace space, ColorChannel channel, double oldValue,
SassNumber? adjustmentArg) {
if (adjustmentArg == null) return oldValue;
switch ((space, channel)) {
case (ColorSpace.hsl || ColorSpace.hwb, _) when channel is! LinearChannel:
// `_channelFromValue` expects all hue values to be compatible with `deg`,
// but we're still in the deprecation period where we allow non-`deg`
// values for HSL and HWB so we have to handle that ahead-of-time.
adjustmentArg = SassNumber(_angleValue(adjustmentArg, 'hue'));
case (ColorSpace.hsl, LinearChannel()):
// `_channelFromValue` expects lightness/saturation to be `%`, but we're
// still in the deprecation period where we allow non-`%` values so we
// have to handle that ahead-of-time.
_checkPercent(adjustmentArg, channel.name);
adjustmentArg = SassNumber(adjustmentArg.value, '%');
case (_, ColorChannel.alpha) when adjustmentArg.hasUnits:
// `_channelFromValue` expects alpha to be unitless or `%`, but we're
// still in the deprecation period where we allow other values (and
// interpret `%` as unitless) so we have to handle that ahead-of-time.
warnForDeprecation(
"\$alpha: Passing a number with unit ${adjustmentArg.unitString} is "
"deprecated.\n"
"\n"
"To preserve current behavior: "
"${adjustmentArg.unitSuggestion('alpha')}\n"
"\n"
"More info: https://sass-lang.com/d/function-units",
Deprecation.functionUnits);
adjustmentArg = SassNumber(adjustmentArg.value);
}
var result =
oldValue + _channelFromValue(channel, adjustmentArg, clamp: false)!;
return switch (channel) {
LinearChannel(lowerClamped: true, :var min) when result < min =>
oldValue < min ? math.max(oldValue, result) : min,
LinearChannel(upperClamped: true, :var max) when result > max =>
oldValue > max ? math.min(oldValue, result) : max,
_ => result
};
}
/// Given a map of arguments passed to [_updateComponents] for a legacy color,
/// determines whether it's updating the color as RGB, HSL, or HWB.
///
/// Returns `null` if [keywords] contains no keywords for any of the legacy
/// color spaces.
ColorSpace? _sniffLegacyColorSpace(Map<String, Value> keywords) {
for (var key in keywords.keys) {
switch (key) {
case "red" || "green" || "blue":
return ColorSpace.rgb;
case "saturation" || "lightness":
return ColorSpace.hsl;
case "whiteness" || "blackness":
return ColorSpace.hwb;
}
}
return keywords.containsKey("hue") ? ColorSpace.hsl : null;
}
/// Returns a string representation of [name] called with [arguments], as though
/// it were a plain CSS function.
SassString _functionString(String name, Iterable<Value> arguments) =>
SassString(
"$name(" +
arguments.map((argument) => argument.toCssString()).join(', ') +
")",
quotes: false);
/// Returns a [_function] that throws an error indicating that
/// `color.adjust()` should be used instead.
///
/// This prints a suggested `color.adjust()` call that passes the adjustment
/// value to [argument], with a leading minus sign if [negative] is `true`.
BuiltInCallable _removedColorFunction(String name, String argument,
{bool negative = false}) =>
_function(name, r"$color, $amount", (arguments) {
throw SassScriptException(
"The function $name() isn't in the sass:color module.\n"
"\n"
"Recommendation: color.adjust(${arguments[0]}, \$$argument: "
"${negative ? '-' : ''}${arguments[1]})\n"
"\n"
"More info: https://sass-lang.com/documentation/functions/color#$name");
});
/// The implementation of the three- and four-argument `rgb()` and `rgba()`
/// functions.
Value _rgb(String name, List<Value> arguments) {
var alpha = arguments.length > 3 ? arguments[3] : null;
if (arguments[0].isSpecialNumber ||
arguments[1].isSpecialNumber ||
arguments[2].isSpecialNumber ||
(alpha?.isSpecialNumber ?? false)) {
return _functionString(name, arguments);
}
return _colorFromChannels(
ColorSpace.rgb,
arguments[0].assertNumber("red"),
arguments[1].assertNumber("green"),
arguments[2].assertNumber("blue"),
alpha.andThen((alpha) =>
_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha")
.clamp(0, 1)) ??
1,
fromRgbFunction: true);
}
/// The implementation of the two-argument `rgb()` and `rgba()` functions.
Value _rgbTwoArg(String name, List<Value> arguments) {
// rgba(var(--foo), 0.5) is valid CSS because --foo might be `123, 456, 789`
// and functions are parsed after variable substitution.
var first = arguments[0];
var second = arguments[1];
if (first.isVar || (first is! SassColor && second.isVar)) {
return _functionString(name, arguments);
}
var color = first.assertColor("color");
color.assertLegacy("color");
color = color.toSpace(ColorSpace.rgb);
if (second.isSpecialNumber) {
return _functionString(name, [
SassNumber(color.channel('red')),
SassNumber(color.channel('green')),
SassNumber(color.channel('blue')),
arguments[1]
]);
}
var alpha = arguments[1].assertNumber("alpha");
return color
.changeAlpha(_percentageOrUnitless(alpha, 1, "alpha").clamp(0, 1));