-
Notifications
You must be signed in to change notification settings - Fork 359
/
color.dart
862 lines (745 loc) · 29.9 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
// 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 'package:collection/collection.dart';
import '../callable.dart';
import '../evaluation_context.dart';
import '../exception.dart';
import '../module/built_in.dart';
import '../util/number.dart';
import '../util/nullable.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*=');
/// The global definitions of Sass color functions.
final global = UnmodifiableListView([
// ### RGB
_red, _green, _blue, _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) {
var parsed = _parseChannels(
"rgb", [r"$red", r"$green", r"$blue"], arguments.first);
return parsed is SassString ? parsed : _rgb("rgb", parsed as List<Value>);
}
}),
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) {
var parsed = _parseChannels(
"rgba", [r"$red", r"$green", r"$blue"], arguments.first);
return parsed is SassString
? parsed
: _rgb("rgba", parsed as List<Value>);
}
}),
_function("invert", r"$color, $weight: 100%", (arguments) {
var weight = arguments[1].assertNumber("weight");
if (arguments[0] is SassNumber) {
if (weight.value != 100 || !weight.hasUnit("%")) {
throw "Only one argument may be passed to the plain-CSS invert() "
"function.";
}
return _functionString("invert", arguments.take(1));
}
var color = arguments[0].assertColor("color");
var inverse = color.changeRgb(
red: 255 - color.red, green: 255 - color.green, blue: 255 - color.blue);
return _mixColors(inverse, color, weight);
}),
// ### HSL
_hue, _saturation, _lightness, _complement,
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) {
var parsed = _parseChannels(
"hsl", [r"$hue", r"$saturation", r"$lightness"], arguments.first);
return parsed is SassString ? parsed : _hsl("hsl", parsed as List<Value>);
}
}),
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) {
var parsed = _parseChannels(
"hsla", [r"$hue", r"$saturation", r"$lightness"], arguments.first);
return parsed is SassString
? parsed
: _hsl("hsla", parsed as List<Value>);
}
}),
_function("grayscale", r"$color", (arguments) {
if (arguments[0] is SassNumber) {
return _functionString('grayscale', arguments);
}
var color = arguments[0].assertColor("color");
return color.changeHsl(saturation: 0);
}),
_function("adjust-hue", r"$color, $degrees", (arguments) {
var color = arguments[0].assertColor("color");
var degrees = arguments[1].assertNumber("degrees");
_checkAngle(degrees);
return color.changeHsl(hue: color.hue + degrees.value);
}),
_function("lighten", r"$color, $amount", (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
return color.changeHsl(
lightness: (color.lightness + amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
}),
_function("darken", r"$color, $amount", (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
return color.changeHsl(
lightness: (color.lightness - amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
}),
BuiltInCallable.overloadedFunction("saturate", {
r"$amount": (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");
return color.changeHsl(
saturation: (color.saturation + amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
}
}),
_function("desaturate", r"$color, $amount", (arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
return color.changeHsl(
saturation: (color.saturation - amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
}),
// ### Opacity
_function("opacify", r"$color, $amount", _opacify),
_function("fade-in", r"$color, $amount", _opacify),
_function("transparentize", r"$color, $amount", _transparentize),
_function("fade-out", r"$color, $amount", _transparentize),
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) {
return _functionString("opacity", arguments);
}
var color = arguments[0].assertColor("color");
return SassNumber(color.alpha);
}),
// ### Miscellaneous
_ieHexStr,
_adjust.withName("adjust-color"),
_scale.withName("scale-color"),
_change.withName("change-color")
]);
/// The Sass color module.
final module = BuiltInModule("color", functions: [
// ### RGB
_red, _green, _blue, _mix,
_function("invert", r"$color, $weight: 100%", (arguments) {
var weight = arguments[1].assertNumber("weight");
if (arguments[0] is SassNumber) {
if (weight.value != 100 || !weight.hasUnit("%")) {
throw "Only one argument may be passed to the plain-CSS invert() "
"function.";
}
var result = _functionString("invert", arguments.take(1));
warn(
"Passing a number (${arguments[0]}) to color.invert() is "
"deprecated.\n"
"\n"
"Recommendation: $result",
deprecation: true);
return result;
}
var color = arguments[0].assertColor("color");
var inverse = color.changeRgb(
red: 255 - color.red, green: 255 - color.green, blue: 255 - color.blue);
return _mixColors(inverse, color, weight);
}),
// ### HSL
_hue, _saturation, _lightness, _complement,
_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));
warn(
"Passing a number (${arguments[0]}) to color.grayscale() is "
"deprecated.\n"
"\n"
"Recommendation: $result",
deprecation: true);
return result;
}
var color = arguments[0].assertColor("color");
return color.changeHsl(saturation: 0);
}),
// ### HWB
BuiltInCallable.overloadedFunction("hwb", {
r"$hue, $whiteness, $blackness, $alpha: 1": (arguments) => _hwb(arguments),
r"$channels": (arguments) {
var parsed = _parseChannels(
"hwb", [r"$hue", r"$whiteness", r"$blackness"], arguments.first);
// `hwb()` doesn't (currently) support special number or variable strings.
if (parsed is SassString) {
throw SassScriptException('Expected numeric channels, got "$parsed".');
} else {
return _hwb(parsed as List<Value>);
}
}
}),
_function(
"whiteness",
r"$color",
(arguments) =>
SassNumber(arguments.first.assertColor("color").whiteness, "%")),
_function(
"blackness",
r"$color",
(arguments) =>
SassNumber(arguments.first.assertColor("color").blackness, "%")),
// ### 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);
warn(
"Using color.alpha() for a Microsoft filter is deprecated.\n"
"\n"
"Recommendation: $result",
deprecation: true);
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);
warn(
"Using color.alpha() for a Microsoft filter is deprecated.\n"
"\n"
"Recommendation: $result",
deprecation: true);
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);
warn(
"Passing a number (${arguments[0]} to color.opacity() is "
"deprecated.\n"
"\n"
"Recommendation: $result",
deprecation: true);
return result;
}
var color = arguments[0].assertColor("color");
return SassNumber(color.alpha);
}),
// Miscellaneous
_adjust, _scale, _change, _ieHexStr
]);
// ### RGB
final _red = _function("red", r"$color", (arguments) {
return SassNumber(arguments.first.assertColor("color").red);
});
final _green = _function("green", r"$color", (arguments) {
return SassNumber(arguments.first.assertColor("color").green);
});
final _blue = _function("blue", r"$color", (arguments) {
return SassNumber(arguments.first.assertColor("color").blue);
});
final _mix = _function("mix", r"$color1, $color2, $weight: 50%", (arguments) {
var color1 = arguments[0].assertColor("color1");
var color2 = arguments[1].assertColor("color2");
var weight = arguments[2].assertNumber("weight");
return _mixColors(color1, color2, weight);
});
// ### HSL
final _hue = _function("hue", r"$color",
(arguments) => SassNumber(arguments.first.assertColor("color").hue, "deg"));
final _saturation = _function(
"saturation",
r"$color",
(arguments) =>
SassNumber(arguments.first.assertColor("color").saturation, "%"));
final _lightness = _function(
"lightness",
r"$color",
(arguments) =>
SassNumber(arguments.first.assertColor("color").lightness, "%"));
final _complement = _function("complement", r"$color", (arguments) {
var color = arguments[0].assertColor("color");
return color.changeHsl(hue: color.hue + 180);
});
// 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");
String hexString(int component) =>
component.toRadixString(16).padLeft(2, '0').toUpperCase();
return SassString(
"#${hexString(fuzzyRound(color.alpha * 255))}${hexString(color.red)}"
"${hexString(color.green)}${hexString(color.blue)}",
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 color = arguments[0].assertColor("color");
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);
/// Gets and validates the parameter with [name] from keywords.
///
/// [max] should be 255 for RGB channels, 1 for the alpha channel, and 100
/// for saturation, lightness, whiteness, and blackness.
num? getParam(String name, num max,
{bool checkPercent = false, bool assertPercent = false}) {
var number = keywords.remove(name)?.assertNumber(name);
if (number == null) return null;
if (!scale && checkPercent) _checkPercent(number, name);
if (scale || assertPercent) number.assertUnit("%", name);
if (scale) max = 100;
return number.valueInRange(change ? 0 : -max, max, name);
}
var alpha = getParam("alpha", 1);
var red = getParam("red", 255);
var green = getParam("green", 255);
var blue = getParam("blue", 255);
var hueNumber = scale ? null : keywords.remove("hue")?.assertNumber("hue");
if (hueNumber != null) _checkAngle(hueNumber, "hue");
var hue = hueNumber?.value;
var saturation = getParam("saturation", 100, checkPercent: true);
var lightness = getParam("lightness", 100, checkPercent: true);
var whiteness = getParam("whiteness", 100, assertPercent: true);
var blackness = getParam("blackness", 100, assertPercent: true);
if (keywords.isNotEmpty) {
throw SassScriptException(
"No ${pluralize('argument', keywords.length)} named "
"${toSentence(keywords.keys.map((name) => '\$$name'), 'or')}.");
}
var hasRgb = red != null || green != null || blue != null;
var hasSL = saturation != null || lightness != null;
var hasWB = whiteness != null || blackness != null;
if (hasRgb && (hasSL || hasWB || hue != null)) {
throw SassScriptException("RGB parameters may not be passed along with "
"${hasWB ? 'HWB' : 'HSL'} parameters.");
}
if (hasSL && hasWB) {
throw SassScriptException(
"HSL parameters may not be passed along with HWB parameters.");
}
/// Updates [current] based on [param], clamped within [max].
num updateValue(num current, num? param, num max) {
if (param == null) return current;
if (change) return param;
if (adjust) return (current + param).clamp(0, max);
return current + (param > 0 ? max - current : current) * (param / 100);
}
int updateRgb(int current, num? param) =>
fuzzyRound(updateValue(current, param, 255));
if (hasRgb) {
return color.changeRgb(
red: updateRgb(color.red, red),
green: updateRgb(color.green, green),
blue: updateRgb(color.blue, blue),
alpha: updateValue(color.alpha, alpha, 1));
} else if (hasWB) {
return color.changeHwb(
hue: change ? hue : color.hue + (hue ?? 0),
whiteness: updateValue(color.whiteness, whiteness, 100),
blackness: updateValue(color.blackness, blackness, 100),
alpha: updateValue(color.alpha, alpha, 1));
} else if (hue != null || hasSL) {
return color.changeHsl(
hue: change ? hue : color.hue + (hue ?? 0),
saturation: updateValue(color.saturation, saturation, 100),
lightness: updateValue(color.lightness, lightness, 100),
alpha: updateValue(color.alpha, alpha, 1));
} else if (alpha != null) {
return color.changeAlpha(updateValue(color.alpha, alpha, 1));
} else {
return color;
}
}
/// 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");
});
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);
}
var red = arguments[0].assertNumber("red");
var green = arguments[1].assertNumber("green");
var blue = arguments[2].assertNumber("blue");
return SassColor.rgb(
fuzzyRound(_percentageOrUnitless(red, 255, "red")),
fuzzyRound(_percentageOrUnitless(green, 255, "green")),
fuzzyRound(_percentageOrUnitless(blue, 255, "blue")),
alpha.andThen((alpha) =>
_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha")));
}
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.
if (arguments[0].isVar) {
return _functionString(name, arguments);
} else if (arguments[1].isVar) {
var first = arguments[0];
if (first is SassColor) {
return SassString(
"$name(${first.red}, ${first.green}, ${first.blue}, "
"${arguments[1].toCssString()})",
quotes: false);
} else {
return _functionString(name, arguments);
}
} else if (arguments[1].isSpecialNumber) {
var color = arguments[0].assertColor("color");
return SassString(
"$name(${color.red}, ${color.green}, ${color.blue}, "
"${arguments[1].toCssString()})",
quotes: false);
}
var color = arguments[0].assertColor("color");
var alpha = arguments[1].assertNumber("alpha");
return color.changeAlpha(_percentageOrUnitless(alpha, 1, "alpha"));
}
Value _hsl(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);
}
var hue = arguments[0].assertNumber("hue");
var saturation = arguments[1].assertNumber("saturation");
var lightness = arguments[2].assertNumber("lightness");
_checkAngle(hue, "hue");
_checkPercent(saturation, "saturation");
_checkPercent(lightness, "lightness");
return SassColor.hsl(
hue.value,
saturation.value.clamp(0, 100),
lightness.value.clamp(0, 100),
alpha.andThen((alpha) =>
_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha")));
}
/// Prints a deprecation warning if [hue] has a unit other than `deg`.
void _checkAngle(SassNumber angle, [String? name]) {
if (!angle.hasUnits || angle.hasUnit('deg')) return;
var message = StringBuffer()
..writeln("\$$name: Passing a unit other than deg ($angle) is deprecated.")
..writeln();
if (angle.compatibleWithUnit('deg')) {
message
..writeln(
"You're passing $angle, which is currently (incorrectly) converted "
"to ${SassNumber(angle.value, 'deg')}.")
..writeln("Soon, it will instead be correctly converted to "
"${angle.coerce(['deg'], [])}.")
..writeln();
var actualUnit = angle.numeratorUnits.first;
message
..writeln("To preserve current behavior: \$$name * 1deg/1$actualUnit")
..writeln("To migrate to new behavior: 0deg + \$$name")
..writeln();
} else {
message
..writeln("To preserve current behavior: \$$name${_removeUnits(angle)}")
..writeln();
}
message.write("See https://sass-lang.com/d/color-units");
warn(message.toString(), deprecation: true);
}
/// Prints a deprecation warning if [number] doesn't have unit `%`.
void _checkPercent(SassNumber number, String name) {
if (number.hasUnit('%')) return;
warn(
"\$$name: Passing a number without unit % ($number) is deprecated.\n"
"\n"
"To preserve current behavior: \$$name${_removeUnits(number)} * 1%",
deprecation: true);
}
/// Returns the right-hand side of an expression that would remove all units
/// from `$number` but leaves the value the same.
///
/// Used for constructing deprecation messages.
String _removeUnits(SassNumber number) =>
number.denominatorUnits.map((unit) => " * 1$unit").join() +
number.numeratorUnits.map((unit) => " / 1$unit").join();
/// Create an HWB color from the given [arguments].
Value _hwb(List<Value> arguments) {
var alpha = arguments.length > 3 ? arguments[3] : null;
var hue = arguments[0].assertNumber("hue");
var whiteness = arguments[1].assertNumber("whiteness");
var blackness = arguments[2].assertNumber("blackness");
whiteness.assertUnit("%", "whiteness");
blackness.assertUnit("%", "blackness");
return SassColor.hwb(
hue.value,
whiteness.valueInRange(0, 100, "whiteness"),
blackness.valueInRange(0, 100, "blackness"),
alpha.andThen((alpha) =>
_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha")));
}
Object /* SassString | List<Value> */ _parseChannels(
String name, List<String> argumentNames, Value channels) {
if (channels.isVar) return _functionString(name, [channels]);
var originalChannels = channels;
Value? alphaFromSlashList;
if (channels.separator == ListSeparator.slash) {
var list = channels.asList;
if (list.length != 2) {
throw SassScriptException(
"Only 2 slash-separated elements allowed, but ${list.length} "
"${pluralize('was', list.length, plural: 'were')} passed.");
}
channels = list[0];
alphaFromSlashList = list[1];
if (!alphaFromSlashList.isSpecialNumber) {
alphaFromSlashList.assertNumber("alpha");
}
if (list[0].isVar) return _functionString(name, [originalChannels]);
}
var isCommaSeparated = channels.separator == ListSeparator.comma;
var isBracketed = channels.hasBrackets;
if (isCommaSeparated || isBracketed) {
var buffer = StringBuffer(r"$channels must be");
if (isBracketed) buffer.write(" an unbracketed");
if (isCommaSeparated) {
buffer.write(isBracketed ? "," : " a");
buffer.write(" space-separated");
}
buffer.write(" list.");
throw SassScriptException(buffer.toString());
}
var list = channels.asList;
if (list.length > 3) {
throw SassScriptException("Only 3 elements allowed, but ${list.length} "
"were passed.");
} else if (list.length < 3) {
if (list.any((value) => value.isVar) ||
(list.isNotEmpty && _isVarSlash(list.last))) {
return _functionString(name, [originalChannels]);
} else {
var argument = argumentNames[list.length];
throw SassScriptException("Missing element $argument.");
}
}
if (alphaFromSlashList != null) return [...list, alphaFromSlashList];
var maybeSlashSeparated = list[2];
if (maybeSlashSeparated is SassNumber) {
var slash = maybeSlashSeparated.asSlash;
if (slash == null) return list;
return [list[0], list[1], slash.item1, slash.item2];
} else if (maybeSlashSeparated is SassString &&
!maybeSlashSeparated.hasQuotes &&
maybeSlashSeparated.text.contains("/")) {
return _functionString(name, [channels]);
} else {
return list;
}
}
/// Returns whether [value] is an unquoted string that start with `var(` and
/// contains `/`.
bool _isVarSlash(Value value) =>
value is SassString &&
value.hasQuotes &&
startsWithIgnoreCase(value.text, "var(") &&
value.text.contains("/");
/// Asserts that [number] is a percentage or has no units, and normalizes the
/// value.
///
/// If [number] has no units, its value is clamped to be greater than `0` or
/// less than [max] and returned. If [number] is a percentage, it's scaled to be
/// within `0` and [max]. Otherwise, this throws a [SassScriptException].
///
/// [name] is used to identify the argument in the error message.
num _percentageOrUnitless(SassNumber number, num max, String name) {
num value;
if (!number.hasUnits) {
value = number.value;
} else if (number.hasUnit("%")) {
value = max * number.value / 100;
} else {
throw SassScriptException(
'\$$name: Expected $number to have no units or "%".');
}
return value.clamp(0, max);
}
/// Returns [color1] and [color2], mixed together and weighted by [weight].
SassColor _mixColors(SassColor color1, SassColor color2, SassNumber weight) {
// This algorithm factors in both the user-provided weight (w) and the
// difference between the alpha values of the two colors (a) to decide how
// to perform the weighted average of the two RGB values.
//
// It works by first normalizing both parameters to be within [-1, 1], where
// 1 indicates "only use color1", -1 indicates "only use color2", and all
// values in between indicated a proportionately weighted average.
//
// Once we have the normalized variables w and a, we apply the formula
// (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1. This
// formula has two especially nice properties:
//
// * When either w or a are -1 or 1, the combined weight is also that
// number (cases where w * a == -1 are undefined, and handled as a
// special case).
//
// * When a is 0, the combined weight is w, and vice versa.
//
// Finally, the weight of color1 is renormalized to be within [0, 1] and the
// weight of color2 is given by 1 minus the weight of color1.
var weightScale = weight.valueInRange(0, 100, "weight") / 100;
var normalizedWeight = weightScale * 2 - 1;
var alphaDistance = color1.alpha - color2.alpha;
var combinedWeight1 = normalizedWeight * alphaDistance == -1
? normalizedWeight
: (normalizedWeight + alphaDistance) /
(1 + normalizedWeight * alphaDistance);
var weight1 = (combinedWeight1 + 1) / 2;
var weight2 = 1 - weight1;
return SassColor.rgb(
fuzzyRound(color1.red * weight1 + color2.red * weight2),
fuzzyRound(color1.green * weight1 + color2.green * weight2),
fuzzyRound(color1.blue * weight1 + color2.blue * weight2),
color1.alpha * weightScale + color2.alpha * (1 - weightScale));
}
/// The definition of the `opacify()` and `fade-in()` functions.
SassColor _opacify(List<Value> arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
return color.changeAlpha(
(color.alpha + amount.valueInRange(0, 1, "amount")).clamp(0, 1));
}
/// The definition of the `transparentize()` and `fade-out()` functions.
SassColor _transparentize(List<Value> arguments) {
var color = arguments[0].assertColor("color");
var amount = arguments[1].assertNumber("amount");
return color.changeAlpha(
(color.alpha - amount.valueInRange(0, 1, "amount")).clamp(0, 1));
}
/// Like [new BuiltInCallable.function], but always sets the URL to
/// `sass:color`.
BuiltInCallable _function(
String name, String arguments, Value callback(List<Value> arguments)) =>
BuiltInCallable.function(name, arguments, callback, url: "sass:color");