-
Notifications
You must be signed in to change notification settings - Fork 358
/
serialize.dart
1877 lines (1626 loc) · 60 KB
/
serialize.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 2016 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:math' as math;
import 'dart:typed_data';
import 'package:charcode/charcode.dart';
import 'package:collection/collection.dart';
import 'package:source_maps/source_maps.dart';
import 'package:string_scanner/string_scanner.dart';
import '../ast/css.dart';
import '../ast/node.dart';
import '../ast/selector.dart';
import '../color_names.dart';
import '../deprecation.dart';
import '../exception.dart';
import '../logger.dart';
import '../parse/parser.dart';
import '../utils.dart';
import '../util/character.dart';
import '../util/multi_span.dart';
import '../util/no_source_map_buffer.dart';
import '../util/nullable.dart';
import '../util/number.dart';
import '../util/source_map_buffer.dart';
import '../util/span.dart';
import '../value.dart';
import 'interface/css.dart';
import 'interface/selector.dart';
import 'interface/value.dart';
/// Converts [node] to a CSS string.
///
/// If [style] is passed, it controls the style of the resulting CSS. It
/// defaults to [OutputStyle.expanded].
///
/// If [inspect] is `true`, this will emit an unambiguous representation of the
/// source structure. Note however that, although this will be valid SCSS, it
/// may not be valid CSS. If [inspect] is `false` and [node] contains any values
/// that can't be represented in plain CSS, throws a [SassException].
///
/// If [sourceMap] is `true`, the returned [SerializeResult] will contain a
/// source map indicating how the original Sass files map to the compiled CSS.
///
/// If [charset] is `true`, this will include a `@charset` declaration or a BOM
/// if the stylesheet contains any non-ASCII characters.
SerializeResult serialize(CssNode node,
{OutputStyle? style,
bool inspect = false,
bool useSpaces = true,
int? indentWidth,
LineFeed? lineFeed,
Logger? logger,
bool sourceMap = false,
bool charset = true}) {
indentWidth ??= 2;
var visitor = _SerializeVisitor(
style: style,
inspect: inspect,
useSpaces: useSpaces,
indentWidth: indentWidth,
lineFeed: lineFeed,
logger: logger,
sourceMap: sourceMap);
node.accept(visitor);
var css = visitor._buffer.toString();
String prefix;
if (charset && css.codeUnits.any((codeUnit) => codeUnit > 0x7F)) {
prefix = style == OutputStyle.compressed ? '\uFEFF' : '@charset "UTF-8";\n';
} else {
prefix = '';
}
return (
prefix + css,
sourceMap: sourceMap ? visitor._buffer.buildSourceMap(prefix: prefix) : null
);
}
/// Converts [value] to a CSS string.
///
/// If [inspect] is `true`, this will emit an unambiguous representation of the
/// source structure. Note however that, although this will be valid SCSS, it
/// may not be valid CSS. If [inspect] is `false` and [value] can't be
/// represented in plain CSS, throws a [SassScriptException].
///
/// If [quote] is `false`, quoted strings are emitted without quotes.
String serializeValue(Value value, {bool inspect = false, bool quote = true}) {
var visitor =
_SerializeVisitor(inspect: inspect, quote: quote, sourceMap: false);
value.accept(visitor);
return visitor._buffer.toString();
}
/// Converts [selector] to a CSS string.
///
/// If [inspect] is `true`, this will emit an unambiguous representation of the
/// source structure. Note however that, although this will be valid SCSS, it
/// may not be valid CSS. If [inspect] is `false` and [selector] can't be
/// represented in plain CSS, throws a [SassScriptException].
String serializeSelector(Selector selector, {bool inspect = false}) {
var visitor = _SerializeVisitor(inspect: inspect, sourceMap: false);
selector.accept(visitor);
return visitor._buffer.toString();
}
/// A visitor that converts CSS syntax trees to plain strings.
final class _SerializeVisitor
implements CssVisitor<void>, ValueVisitor<void>, SelectorVisitor<void> {
/// A buffer that contains the CSS produced so far.
final SourceMapBuffer _buffer;
/// The current indentation of the CSS output.
var _indentation = 0;
/// The style of CSS to generate.
final OutputStyle _style;
/// Whether we're emitting an unambiguous representation of the source
/// structure, as opposed to valid CSS.
final bool _inspect;
/// Whether quoted strings should be emitted with quotes.
final bool _quote;
/// The character to use for indentation; either space or tab.
final int _indentCharacter;
/// The number of spaces or tabs to be used for indentation.
final int _indentWidth;
/// The characters to use for a line feed.
final LineFeed _lineFeed;
/// The logger to use to print warnings.
///
/// This should only be used for statement-level serialization. It's not
/// guaranteed to be the main user-provided logger for expressions.
final Logger _logger;
/// Whether we're emitting compressed output.
bool get _isCompressed => _style == OutputStyle.compressed;
_SerializeVisitor(
{OutputStyle? style,
bool inspect = false,
bool quote = true,
bool useSpaces = true,
int? indentWidth,
LineFeed? lineFeed,
Logger? logger,
bool sourceMap = true})
: _buffer = sourceMap ? SourceMapBuffer() : NoSourceMapBuffer(),
_style = style ?? OutputStyle.expanded,
_inspect = inspect,
_quote = quote,
_indentCharacter = useSpaces ? $space : $tab,
_indentWidth = indentWidth ?? 2,
_lineFeed = lineFeed ?? LineFeed.lf,
_logger = logger ?? const Logger.stderr() {
RangeError.checkValueInInterval(_indentWidth, 0, 10, "indentWidth");
}
void visitCssStylesheet(CssStylesheet node) {
CssNode? previous;
for (var child in node.children) {
if (_isInvisible(child)) continue;
if (previous != null) {
if (_requiresSemicolon(previous)) _buffer.writeCharCode($semicolon);
if (_isTrailingComment(child, previous)) {
_writeOptionalSpace();
} else {
_writeLineFeed();
if (previous.isGroupEnd) _writeLineFeed();
}
}
previous = child;
child.accept(this);
}
if (previous != null && _requiresSemicolon(previous) && !_isCompressed) {
_buffer.writeCharCode($semicolon);
}
}
void visitCssComment(CssComment node) {
_for(node, () {
// Preserve comments that start with `/*!`.
if (_isCompressed && !node.isPreserved) return;
// Ignore sourceMappingURL and sourceURL comments.
if (node.text.startsWith(RegExp(r"/\*# source(Mapping)?URL="))) return;
if (_minimumIndentation(node.text) case var minimumIndentation?) {
assert(minimumIndentation != -1);
minimumIndentation =
math.min(minimumIndentation, node.span.start.column);
_writeIndentation();
_writeWithIndent(node.text, minimumIndentation);
} else {
_writeIndentation();
_buffer.write(node.text);
}
});
}
void visitCssAtRule(CssAtRule node) {
_writeIndentation();
_for(node, () {
_buffer.writeCharCode($at);
_write(node.name);
if (node.value case var value?) {
_buffer.writeCharCode($space);
_write(value);
}
});
if (!node.isChildless) {
_writeOptionalSpace();
_visitChildren(node);
}
}
void visitCssMediaRule(CssMediaRule node) {
_writeIndentation();
_for(node, () {
_buffer.write("@media");
var firstQuery = node.queries.first;
if (!_isCompressed ||
firstQuery.modifier != null ||
firstQuery.type != null ||
(firstQuery.conditions.length == 1 &&
firstQuery.conditions.first.startsWith("(not "))) {
_buffer.writeCharCode($space);
}
_writeBetween(node.queries, _commaSeparator, _visitMediaQuery);
});
_writeOptionalSpace();
_visitChildren(node);
}
void visitCssImport(CssImport node) {
_writeIndentation();
_for(node, () {
_buffer.write("@import");
_writeOptionalSpace();
_for(node.url, () => _writeImportUrl(node.url.value));
if (node.modifiers case var modifiers?) {
_writeOptionalSpace();
_buffer.write(modifiers);
}
});
}
/// Writes [url], which is an import's URL, to the buffer.
void _writeImportUrl(String url) {
if (!_isCompressed || url.codeUnitAt(0) != $u) {
_buffer.write(url);
return;
}
// If this is url(...), remove the surrounding function. This is terser and
// it allows us to remove whitespace between `@import` and the URL.
var urlContents = url.substring(4, url.length - 1);
var maybeQuote = urlContents.codeUnitAt(0);
if (maybeQuote == $single_quote || maybeQuote == $double_quote) {
_buffer.write(urlContents);
} else {
// If the URL didn't contain quotes, write them manually.
_visitQuotedString(urlContents);
}
}
void visitCssKeyframeBlock(CssKeyframeBlock node) {
_writeIndentation();
_for(
node.selector,
() =>
_writeBetween(node.selector.value, _commaSeparator, _buffer.write));
_writeOptionalSpace();
_visitChildren(node);
}
void _visitMediaQuery(CssMediaQuery query) {
if (query.modifier case var modifier?) {
_buffer.write(modifier);
_buffer.writeCharCode($space);
}
if (query.type case var type?) {
_buffer.write(type);
if (query.conditions.isNotEmpty) _buffer.write(" and ");
}
if (query.conditions case [var first] when first.startsWith("(not ")) {
_buffer.write("not ");
var condition = query.conditions.first;
_buffer.write(condition.substring("(not ".length, condition.length - 1));
} else {
var operator = query.conjunction ? "and" : "or";
_writeBetween(query.conditions,
_isCompressed ? "$operator " : " $operator ", _buffer.write);
}
}
void visitCssStyleRule(CssStyleRule node) {
_writeIndentation();
_for(node.selector, () => node.selector.accept(this));
_writeOptionalSpace();
_visitChildren(node);
}
void visitCssSupportsRule(CssSupportsRule node) {
_writeIndentation();
_for(node, () {
_buffer.write("@supports");
if (!(_isCompressed && node.condition.value.codeUnitAt(0) == $lparen)) {
_buffer.writeCharCode($space);
}
_write(node.condition);
});
_writeOptionalSpace();
_visitChildren(node);
}
void visitCssDeclaration(CssDeclaration node) {
if (node.interleavedRules.isNotEmpty) {
var declSpecificities = _specificities(node.parent!);
for (var rule in node.interleavedRules) {
var ruleSpecificities = _specificities(rule);
// If the declaration can never match with the same specificity as one
// of its sibling rules, then ordering will never matter and there's no
// need to warn about the declaration being re-ordered.
if (!declSpecificities.any(ruleSpecificities.contains)) continue;
_logger.warnForDeprecation(
Deprecation.mixedDecls,
"Sass's behavior for declarations that appear after nested\n"
"rules will be changing to match the behavior specified by CSS in an "
"upcoming\n"
"version. To keep the existing behavior, move the declaration above "
"the nested\n"
"rule. To opt into the new behavior, wrap the declaration in `& "
"{}`.\n"
"\n"
"More info: https://sass-lang.com/d/mixed-decls",
span:
MultiSpan(node.span, 'declaration', {rule.span: 'nested rule'}),
trace: node.trace);
}
}
_writeIndentation();
_write(node.name);
_buffer.writeCharCode($colon);
// If `node` is a custom property that was parsed as a normal Sass-syntax
// property (such as `#{--foo}: ...`), we serialize its value using the
// normal Sass property logic as well.
if (node.isCustomProperty && node.parsedAsCustomProperty) {
_for(node.value, () {
if (_isCompressed) {
_writeFoldedValue(node);
} else {
_writeReindentedValue(node);
}
});
} else {
_writeOptionalSpace();
try {
_buffer.forSpan(
node.valueSpanForMap, () => node.value.value.accept(this));
} on MultiSpanSassScriptException catch (error, stackTrace) {
throwWithTrace(
MultiSpanSassException(error.message, node.value.span,
error.primaryLabel, error.secondarySpans),
error,
stackTrace);
} on SassScriptException catch (error, stackTrace) {
throwWithTrace(
SassException(error.message, node.value.span), error, stackTrace);
}
}
}
/// Returns the set of possible specificities which which [node] might match.
Set<int> _specificities(CssParentNode node) {
if (node case CssStyleRule rule) {
// Plain CSS style rule nesting implicitly wraps parent selectors in
// `:is()`, so they all match with the highest specificity among any of
// them.
var parent = node.parent.andThen(_specificities)?.max ?? 0;
return {
for (var selector in rule.selector.components)
parent + selector.specificity
};
} else {
return node.parent.andThen(_specificities) ?? const {0};
}
}
/// Emits the value of [node], with all newlines followed by whitespace
void _writeFoldedValue(CssDeclaration node) {
var scanner = StringScanner((node.value.value as SassString).text);
while (!scanner.isDone) {
var next = scanner.readChar();
if (next != $lf) {
_buffer.writeCharCode(next);
continue;
}
_buffer.writeCharCode($space);
while (scanner.peekChar().isWhitespace) {
scanner.readChar();
}
}
}
/// Emits the value of [node], re-indented relative to the current indentation.
void _writeReindentedValue(CssDeclaration node) {
var value = (node.value.value as SassString).text;
switch (_minimumIndentation(value)) {
case null:
_buffer.write(value);
case -1:
_buffer.write(trimAsciiRight(value, excludeEscape: true));
_buffer.writeCharCode($space);
case var minimumIndentation:
_writeWithIndent(
value, math.min(minimumIndentation, node.name.span.start.column));
}
}
/// Returns the indentation level of the least-indented non-empty line in
/// [text] after the first.
///
/// Returns `null` if [text] contains no newlines, and -1 if it contains
/// newlines but no lines are indented.
int? _minimumIndentation(String text) {
var scanner = LineScanner(text);
while (!scanner.isDone && scanner.readChar() != $lf) {}
if (scanner.isDone) return scanner.peekChar(-1) == $lf ? -1 : null;
int? min;
while (!scanner.isDone) {
while (!scanner.isDone) {
var next = scanner.peekChar();
if (next != $space && next != $tab) break;
scanner.readChar();
}
if (scanner.isDone || scanner.scanChar($lf)) continue;
min = min == null ? scanner.column : math.min(min, scanner.column);
while (!scanner.isDone && scanner.readChar() != $lf) {}
}
return min ?? -1;
}
/// Writes [text] to [_buffer], replacing [minimumIndentation] with
/// [_indentation] for each non-empty line after the first.
///
/// Compresses trailing empty lines of [text] into a single trailing space.
void _writeWithIndent(String text, int minimumIndentation) {
var scanner = LineScanner(text);
// Write the first line as-is.
while (!scanner.isDone) {
var next = scanner.readChar();
if (next == $lf) break;
_buffer.writeCharCode(next);
}
while (true) {
assert(scanner.peekChar(-1).isWhitespace);
// Scan forward until we hit non-whitespace or the end of [text].
var lineStart = scanner.position;
var newlines = 1;
inner:
while (true) {
// If we hit the end of [text], we still need to preserve the fact that
// whitespace exists because it could matter for custom properties.
if (scanner.isDone) {
_buffer.writeCharCode($space);
return;
}
switch (scanner.readChar()) {
case $space || $tab:
continue inner;
case $lf:
lineStart = scanner.position;
newlines++;
case _:
break inner;
}
}
_writeTimes($lf, newlines);
_writeIndentation();
_buffer.write(scanner.substring(lineStart + minimumIndentation));
// Scan and write until we hit a newline or the end of [text].
while (true) {
if (scanner.isDone) return;
var next = scanner.readChar();
if (next == $lf) break;
_buffer.writeCharCode(next);
}
}
}
// ## Values
void visitBoolean(SassBoolean value) => _buffer.write(value.value.toString());
void visitCalculation(SassCalculation value) {
_buffer.write(value.name);
_buffer.writeCharCode($lparen);
_writeBetween(value.arguments, _commaSeparator, _writeCalculationValue);
_buffer.writeCharCode($rparen);
}
void _writeCalculationValue(Object value) {
switch (value) {
case SassNumber(hasComplexUnits: true) when !_inspect:
throw SassScriptException("$value isn't a valid CSS value.");
case SassNumber(value: double(isFinite: false)):
switch (value.value) {
case double.infinity:
_buffer.write('infinity');
case double.negativeInfinity:
_buffer.write('-infinity');
case double(isNaN: true):
_buffer.write('NaN');
}
_writeCalculationUnits(value.numeratorUnits, value.denominatorUnits);
case SassNumber(hasComplexUnits: true):
_writeNumber(value.value);
if (value.numeratorUnits case [var first, ...var rest]) {
_buffer.write(first);
_writeCalculationUnits(rest, value.denominatorUnits);
} else {
_writeCalculationUnits([], value.denominatorUnits);
}
case Value():
value.accept(this);
case CalculationOperation(:var operator, :var left, :var right):
var parenthesizeLeft = left is CalculationOperation &&
left.operator.precedence < operator.precedence;
if (parenthesizeLeft) _buffer.writeCharCode($lparen);
_writeCalculationValue(left);
if (parenthesizeLeft) _buffer.writeCharCode($rparen);
var operatorWhitespace = !_isCompressed || operator.precedence == 1;
if (operatorWhitespace) _buffer.writeCharCode($space);
_buffer.write(operator.operator);
if (operatorWhitespace) _buffer.writeCharCode($space);
var parenthesizeRight = (right is CalculationOperation &&
_parenthesizeCalculationRhs(operator, right.operator)) ||
(operator == CalculationOperator.dividedBy &&
right is SassNumber &&
(right.value.isFinite
? right.hasComplexUnits
: right.hasUnits));
if (parenthesizeRight) _buffer.writeCharCode($lparen);
_writeCalculationValue(right);
if (parenthesizeRight) _buffer.writeCharCode($rparen);
}
}
/// Writes the complex numerator and denominator units beyond the first
/// numerator unit for a number as they appear in a calculation.
void _writeCalculationUnits(
List<String> numeratorUnits, List<String> denominatorUnits) {
for (var unit in numeratorUnits) {
_writeOptionalSpace();
_buffer.writeCharCode($asterisk);
_writeOptionalSpace();
_buffer.writeCharCode($1);
_buffer.write(unit);
}
for (var unit in denominatorUnits) {
_writeOptionalSpace();
_buffer.writeCharCode($slash);
_writeOptionalSpace();
_buffer.writeCharCode($1);
_buffer.write(unit);
}
}
/// Returns whether the right-hand operation of a calculation should be
/// parenthesized.
///
/// In `a ? (b # c)`, `outer` is `?` and `right` is `#`.
bool _parenthesizeCalculationRhs(
CalculationOperator outer, CalculationOperator right) =>
switch (outer) {
CalculationOperator.dividedBy => true,
CalculationOperator.plus => false,
_ => right == CalculationOperator.plus ||
right == CalculationOperator.minus
};
void visitColor(SassColor value) {
switch (value.space) {
case ColorSpace.rgb || ColorSpace.hsl || ColorSpace.hwb
when !value.isChannel0Missing &&
!value.isChannel1Missing &&
!value.isChannel2Missing &&
!value.isAlphaMissing:
_writeLegacyColor(value);
case ColorSpace.rgb:
_buffer.write('rgb(');
_writeChannel(value.channel0OrNull);
_buffer.writeCharCode($space);
_writeChannel(value.channel1OrNull);
_buffer.writeCharCode($space);
_writeChannel(value.channel2OrNull);
_maybeWriteSlashAlpha(value);
_buffer.writeCharCode($rparen);
case ColorSpace.hsl || ColorSpace.hwb:
_buffer
..write(value.space)
..writeCharCode($lparen);
_writeChannel(value.channel0OrNull, _isCompressed ? null : 'deg');
_buffer.writeCharCode($space);
_writeChannel(value.channel1OrNull, '%');
_buffer.writeCharCode($space);
_writeChannel(value.channel2OrNull, '%');
_maybeWriteSlashAlpha(value);
_buffer.writeCharCode($rparen);
case ColorSpace.lab || ColorSpace.lch
when !_inspect &&
!fuzzyInRange(value.channel0, 0, 100) &&
!value.isChannel1Missing &&
!value.isChannel2Missing:
case ColorSpace.oklab || ColorSpace.oklch
when !_inspect &&
!fuzzyInRange(value.channel0, 0, 1) &&
!value.isChannel1Missing &&
!value.isChannel2Missing:
case ColorSpace.lch || ColorSpace.oklch
when !_inspect &&
fuzzyLessThan(value.channel1, 0) &&
!value.isChannel0Missing &&
!value.isChannel1Missing:
// color-mix() is currently more widely supported than relative color
// syntax, so we use it to serialize out-of-gamut colors in a way that
// maintains the color space defined in Sass while (per spec) not
// clamping their values. In practice, all browsers clamp out-of-gamut
// values, but there's not much we can do about that at time of writing.
_buffer.write('color-mix(in ');
_buffer.write(value.space);
_buffer.write(_commaSeparator);
// The XYZ space has no gamut restrictions, so we use it to represent
// the out-of-gamut color before converting into the target space.
_writeColorFunction(value.toSpace(ColorSpace.xyzD65));
_writeOptionalSpace();
_buffer.write('100%');
_buffer.write(_commaSeparator);
_buffer.write(_isCompressed ? 'red' : 'black');
_buffer.writeCharCode($rparen);
case ColorSpace.lab ||
ColorSpace.oklab ||
ColorSpace.lch ||
ColorSpace.oklch:
_buffer
..write(value.space)
..writeCharCode($lparen);
// color-mix() can't represent out-of-bounds colors with missing
// channels, so in this case we use the less-supported but
// more-expressive relative color syntax instead. Relative color syntax
// never clamps channels.
var polar = value.space.channels[2].isPolarAngle;
if (!_inspect &&
(!fuzzyInRange(value.channel0, 0, 100) ||
(polar && fuzzyLessThan(value.channel1, 0)))) {
_buffer
..write('from ')
..write(_isCompressed ? 'red' : 'black')
..writeCharCode($space);
}
if (!_isCompressed && !value.isChannel0Missing) {
var max = (value.space.channels[0] as LinearChannel).max;
_writeNumber(value.channel0 * 100 / max);
_buffer.writeCharCode($percent);
} else {
_writeChannel(value.channel0OrNull);
}
_buffer.writeCharCode($space);
_writeChannel(value.channel1OrNull);
_buffer.writeCharCode($space);
_writeChannel(
value.channel2OrNull, polar && !_isCompressed ? 'deg' : null);
_maybeWriteSlashAlpha(value);
_buffer.writeCharCode($rparen);
case _:
_writeColorFunction(value);
}
}
/// Writes a [channel] which may be missing.
void _writeChannel(double? channel, [String? unit]) {
if (channel == null) {
_buffer.write('none');
} else if (channel.isFinite) {
_writeNumber(channel);
if (unit != null) _buffer.write(unit);
} else {
visitNumber(SassNumber(channel, unit));
}
}
/// Writes a legacy color to the stylesheet.
///
/// Unlike newer color spaces, the three legacy color spaces are
/// interchangeable with one another. We choose the shortest representation
/// that's still compatible with all the browsers we support.
void _writeLegacyColor(SassColor color) {
var opaque = fuzzyEquals(color.alpha, 1);
// Out-of-gamut colors can _only_ be represented accurately as HSL, because
// only HSL isn't clamped at parse time (except negative saturation which
// isn't necessary anyway).
if (!color.isInGamut && !_inspect) {
_writeHsl(color);
return;
}
// In compressed mode, emit colors in the shortest representation possible.
if (_isCompressed) {
var rgb = color.toSpace(ColorSpace.rgb);
if (opaque && _tryIntegerRgb(rgb)) return;
var red = _writeNumberToString(rgb.channel0);
var green = _writeNumberToString(rgb.channel1);
var blue = _writeNumberToString(rgb.channel2);
var hsl = color.toSpace(ColorSpace.hsl);
var hue = _writeNumberToString(hsl.channel0);
var saturation = _writeNumberToString(hsl.channel1);
var lightness = _writeNumberToString(hsl.channel2);
// Add two characters for HSL for the %s on saturation and lightness.
if (red.length + green.length + blue.length <=
hue.length + saturation.length + lightness.length + 2) {
_buffer
..write(opaque ? 'rgb(' : 'rgba(')
..write(red)
..writeCharCode($comma)
..write(green)
..writeCharCode($comma)
..write(blue);
} else {
_buffer
..write(opaque ? 'hsl(' : 'hsla(')
..write(hue)
..writeCharCode($comma)
..write(saturation)
..write('%,')
..write(lightness)
..writeCharCode($percent);
}
if (!opaque) {
_buffer.writeCharCode($comma);
_writeNumber(color.alpha);
}
_buffer.writeCharCode($rparen);
return;
}
if (color.space == ColorSpace.hsl) {
_writeHsl(color);
return;
} else if (_inspect && color.space == ColorSpace.hwb) {
_writeHwb(color);
return;
}
switch (color.format) {
case ColorFormat.rgbFunction:
_writeRgb(color);
return;
case SpanColorFormat format:
_buffer.write(format.original);
return;
}
// Always emit generated transparent colors in rgba format. This works
// around an IE bug. See sass/sass#1782.
if (opaque) {
var rgb = color.toSpace(ColorSpace.rgb);
if (namesByColor[rgb] case var name?) {
_buffer.write(name);
return;
}
if (_canUseHex(rgb)) {
_buffer.writeCharCode($hash);
_writeHexComponent(rgb.channel0.round());
_writeHexComponent(rgb.channel1.round());
_writeHexComponent(rgb.channel2.round());
return;
}
}
// If an HWB color can't be represented as a hex color, write is as HSL
// rather than RGB since that more clearly captures the author's intent.
if (color.space == ColorSpace.hwb) {
_writeHsl(color);
} else {
_writeRgb(color);
}
}
/// If [value] can be written as a hex code or a color name, writes it in the
/// shortest format possible and returns `true.`
///
/// Otherwise, writes nothing and returns `false`. Assumes [value] is in the
/// RGB space.
bool _tryIntegerRgb(SassColor rgb) {
assert(rgb.space == ColorSpace.rgb);
if (!_canUseHex(rgb)) return false;
var redInt = rgb.channel0.round();
var greenInt = rgb.channel1.round();
var blueInt = rgb.channel2.round();
var shortHex = _canUseShortHex(redInt, greenInt, blueInt);
if (namesByColor[rgb] case var name?
when name.length <= (shortHex ? 4 : 7)) {
_buffer.write(name);
} else if (shortHex) {
_buffer.writeCharCode($hash);
_buffer.writeCharCode(hexCharFor(redInt & 0xF));
_buffer.writeCharCode(hexCharFor(greenInt & 0xF));
_buffer.writeCharCode(hexCharFor(blueInt & 0xF));
} else {
_buffer.writeCharCode($hash);
_writeHexComponent(redInt);
_writeHexComponent(greenInt);
_writeHexComponent(blueInt);
}
return true;
}
/// Whether [rgb] can be represented as a hexadecimal color.
bool _canUseHex(SassColor rgb) {
assert(rgb.space == ColorSpace.rgb);
return _canUseHexForChannel(rgb.channel0) &&
_canUseHexForChannel(rgb.channel1) &&
_canUseHexForChannel(rgb.channel2);
}
/// Whether [channel]'s value can be represented as a two-character
/// hexadecimal value.
bool _canUseHexForChannel(double channel) =>
fuzzyIsInt(channel) &&
fuzzyGreaterThanOrEquals(channel, 0) &&
fuzzyLessThan(channel, 256);
/// Writes [value] as an `rgb()` or `rgba()` function.
void _writeRgb(SassColor color) {
var opaque = fuzzyEquals(color.alpha, 1);
var rgb = color.toSpace(ColorSpace.rgb);
_buffer.write(opaque ? "rgb(" : "rgba(");
_writeNumber(rgb.channel('red'));
_buffer.write(_commaSeparator);
_writeNumber(rgb.channel('green'));
_buffer.write(_commaSeparator);
_writeNumber(rgb.channel('blue'));
if (!opaque) {
_buffer.write(_commaSeparator);
_writeNumber(color.alpha);
}
_buffer.writeCharCode($rparen);
}
/// Writes [value] as an `hsl()` or `hsla()` function.
void _writeHsl(SassColor color) {
var opaque = fuzzyEquals(color.alpha, 1);
var hsl = color.toSpace(ColorSpace.hsl);
_buffer.write(opaque ? "hsl(" : "hsla(");
_writeChannel(hsl.channel('hue'));
_buffer.write(_commaSeparator);
_writeChannel(hsl.channel('saturation'), '%');
_buffer.write(_commaSeparator);
_writeChannel(hsl.channel('lightness'), '%');
if (!opaque) {
_buffer.write(_commaSeparator);
_writeNumber(color.alpha);
}
_buffer.writeCharCode($rparen);
}
/// Writes [value] as an `hwb()` function.
///
/// This is only used in inspect mode, and so only supports the new color syntax.
void _writeHwb(SassColor color) {
_buffer.write("hwb(");
var hwb = color.toSpace(ColorSpace.hwb);
_writeNumber(hwb.channel('hue'));
_buffer.writeCharCode($space);
_writeNumber(hwb.channel('whiteness'));
_buffer.writeCharCode($percent);
_buffer.writeCharCode($space);
_writeNumber(hwb.channel('blackness'));
_buffer.writeCharCode($percent);
if (!fuzzyEquals(color.alpha, 1)) {
_buffer.write(' / ');
_writeNumber(color.alpha);
}
_buffer.writeCharCode($rparen);
}
/// Writes [color] using the `color()` function syntax.
void _writeColorFunction(SassColor color) {
assert(!{
ColorSpace.rgb,
ColorSpace.hsl,
ColorSpace.hwb,
ColorSpace.lab,
ColorSpace.oklab,
ColorSpace.lch,
ColorSpace.oklch
}.contains(color.space));
_buffer
..write('color(')
..write(color.space)
..writeCharCode($space);
_writeBetween(color.channelsOrNull, ' ', _writeChannel);
_maybeWriteSlashAlpha(color);
_buffer.writeCharCode($rparen);
}
/// Returns whether [color]'s hex pair representation is symmetrical (e.g.
/// `FF`).
bool _isSymmetricalHex(int color) => color & 0xF == color >> 4;
/// Returns whether [color] can be represented as a short hexadecimal color
/// (e.g. `#fff`).
bool _canUseShortHex(int red, int green, int blue) =>
_isSymmetricalHex(red) &&
_isSymmetricalHex(green) &&
_isSymmetricalHex(blue);
/// Emits [color] as a hex character pair.
void _writeHexComponent(int color) {
assert(color < 0x100);
_buffer.writeCharCode(hexCharFor(color >> 4));
_buffer.writeCharCode(hexCharFor(color & 0xF));
}
/// Writes the alpha component of [color] if it isn't 1.
void _maybeWriteSlashAlpha(SassColor color) {
if (fuzzyEquals(color.alpha, 1)) return;