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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const {
angleUtils,
} = require("resource://devtools/client/shared/css-angle.js");
const { colorUtils } = require("resource://devtools/shared/css/color.js");
const { getCSSLexer } = require("resource://devtools/shared/css/lexer.js");
const {
appendText,
} = require("resource://devtools/client/inspector/shared/utils.js");
const STYLE_INSPECTOR_PROPERTIES =
"devtools/shared/locales/styleinspector.properties";
const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
const STYLE_INSPECTOR_L10N = new LocalizationHelper(STYLE_INSPECTOR_PROPERTIES);
// Functions that accept an angle argument.
const ANGLE_TAKING_FUNCTIONS = [
"linear-gradient",
"-moz-linear-gradient",
"repeating-linear-gradient",
"-moz-repeating-linear-gradient",
"conic-gradient",
"repeating-conic-gradient",
"rotate",
"rotateX",
"rotateY",
"rotateZ",
"rotate3d",
"skew",
"skewX",
"skewY",
"hue-rotate",
];
// All cubic-bezier CSS timing-function names.
const BEZIER_KEYWORDS = [
"linear",
"ease-in-out",
"ease-in",
"ease-out",
"ease",
];
// Functions that accept a color argument.
const COLOR_TAKING_FUNCTIONS = [
"linear-gradient",
"-moz-linear-gradient",
"repeating-linear-gradient",
"-moz-repeating-linear-gradient",
"radial-gradient",
"-moz-radial-gradient",
"repeating-radial-gradient",
"-moz-repeating-radial-gradient",
"conic-gradient",
"repeating-conic-gradient",
"drop-shadow",
"color-mix",
];
// Functions that accept a shape argument.
const BASIC_SHAPE_FUNCTIONS = ["polygon", "circle", "ellipse", "inset"];
const BACKDROP_FILTER_ENABLED = Services.prefs.getBoolPref(
"layout.css.backdrop-filter.enabled"
);
const HTML_NS = "http://www.w3.org/1999/xhtml";
// Very long text properties should be truncated using CSS to avoid creating
// extremely tall propertyvalue containers. 5000 characters is an arbitrary
// limit. Assuming an average ruleview can hold 50 characters per line, this
// should start truncating properties which would otherwise be 100 lines long.
const TRUNCATE_LENGTH_THRESHOLD = 5000;
const TRUNCATE_NODE_CLASSNAME = "propertyvalue-long-text";
/**
* This module is used to process CSS text declarations and output DOM fragments (to be
* appended to panels in DevTools) for CSS values decorated with additional UI and
* functionality.
*
* For example:
* - attaching swatches for values instrumented with specialized tools: colors, timing
* functions (cubic-bezier), filters, shapes, display values (flex/grid), etc.
* - adding previews where possible (images, fonts, CSS transforms).
* - converting between color types on Shift+click on their swatches.
*
* Usage:
* const OutputParser = require("devtools/client/shared/output-parser");
* const parser = new OutputParser(document, cssProperties);
* parser.parseCssProperty("color", "red"); // Returns document fragment.
*
*/
class OutputParser {
/**
* @param {Document} document
* Used to create DOM nodes.
* @param {CssProperties} cssProperties
* Instance of CssProperties, an object which provides an interface for
* working with the database of supported CSS properties and values.
*/
constructor(document, cssProperties) {
this.#doc = document;
this.#cssProperties = cssProperties;
}
#angleSwatches = new WeakMap();
#colorSwatches = new WeakMap();
#cssProperties;
#doc;
#parsed = [];
/**
* Parse a CSS property value given a property name.
*
* @param {String} name
* CSS Property Name
* @param {String} value
* CSS Property value
* @param {Object} [options]
* Options object. For valid options and default values see
* #mergeOptions().
* @return {DocumentFragment}
* A document fragment containing color swatches etc.
*/
parseCssProperty(name, value, options = {}) {
options = this.#mergeOptions(options);
options.expectCubicBezier = this.#cssProperties.supportsType(
name,
"timing-function"
);
options.expectLinearEasing = this.#cssProperties.supportsType(
name,
"timing-function"
);
options.expectDisplay = name === "display";
options.expectFilter =
name === "filter" ||
(BACKDROP_FILTER_ENABLED && name === "backdrop-filter");
options.expectShape =
name === "clip-path" ||
name === "shape-outside" ||
name === "offset-path";
options.expectFont = name === "font-family";
options.supportsColor =
this.#cssProperties.supportsType(name, "color") ||
this.#cssProperties.supportsType(name, "gradient") ||
(name.startsWith("--") && InspectorUtils.isValidCSSColor(value));
// The filter property is special in that we want to show the
// swatch even if the value is invalid, because this way the user
// can easily use the editor to fix it.
if (options.expectFilter || this.#cssPropertySupportsValue(name, value)) {
return this.#parse(value, options);
}
this.#appendTextNode(value);
return this.#toDOM();
}
/**
* Read tokens from |tokenStream| and collect all the (non-comment)
* text. Return the collected texts and variable data (if any).
* Stop when an unmatched closing paren is seen.
* If |stopAtComma| is true, then also stop when a top-level
* (unparenthesized) comma is seen.
*
* @param {String} text
* The original source text.
* @param {CSSLexer} tokenStream
* The token stream from which to read.
* @param {Object} options
* The options object in use; @see #mergeOptions.
* @param {Boolean} stopAtComma
* If true, stop at a comma.
* @return {Object}
* An object of the form {tokens, functionData, sawComma, sawVariable}.
* |tokens| is a list of the non-comment, non-whitespace tokens
* that were seen. The stopping token (paren or comma) will not
* be included.
* |functionData| is a list of parsed strings and nodes that contain the
* data between the matching parenthesis. The stopping token's text will
* not be included.
* |sawComma| is true if the stop was due to a comma, or false otherwise.
* |sawVariable| is true if a variable was seen while parsing the text.
*/
#parseMatchingParens(text, tokenStream, options, stopAtComma) {
let depth = 1;
const functionData = [];
const tokens = [];
let sawVariable = false;
while (depth > 0) {
const token = tokenStream.nextToken();
if (!token) {
break;
}
if (token.tokenType === "comment") {
continue;
}
if (token.tokenType === "symbol") {
if (stopAtComma && depth === 1 && token.text === ",") {
return { tokens, functionData, sawComma: true, sawVariable };
} else if (token.text === "(") {
++depth;
} else if (token.text === ")") {
--depth;
if (depth === 0) {
break;
}
}
} else if (
token.tokenType === "function" &&
token.text === "var" &&
options.getVariableValue
) {
sawVariable = true;
const { node } = this.#parseVariable(token, text, tokenStream, options);
functionData.push(node);
} else if (token.tokenType === "function") {
++depth;
}
if (
token.tokenType !== "function" ||
token.text !== "var" ||
!options.getVariableValue
) {
functionData.push(text.substring(token.startOffset, token.endOffset));
}
if (token.tokenType !== "whitespace") {
tokens.push(token);
}
}
return { tokens, functionData, sawComma: false, sawVariable };
}
/**
* Parse var() use and return a variable node to be added to the output state.
* This will read tokens up to and including the ")" that closes the "var("
* invocation.
*
* @param {CSSToken} initialToken
* The "var(" token that was already seen.
* @param {String} text
* The original input text.
* @param {CSSLexer} tokenStream
* The token stream from which to read.
* @param {Object} options
* The options object in use; @see #mergeOptions.
* @return {Object}
* - node: A node for the variable, with the appropriate text and
* title. Eg. a span with "var(--var1)" as the textContent
* and a title for --var1 like "--var1 = 10" or
* "--var1 is not set".
* - value: The value for the variable.
*/
#parseVariable(initialToken, text, tokenStream, options) {
// Handle the "var(".
const varText = text.substring(
initialToken.startOffset,
initialToken.endOffset
);
const variableNode = this.#createNode("span", {}, varText);
// Parse the first variable name within the parens of var().
const { tokens, functionData, sawComma, sawVariable } =
this.#parseMatchingParens(text, tokenStream, options, true);
const result = sawVariable ? "" : functionData.join("");
// Display options for the first and second argument in the var().
const firstOpts = {};
const secondOpts = {};
let varValue;
// Get the variable value if it is in use.
if (tokens && tokens.length === 1) {
varValue = options.getVariableValue(tokens[0].text);
}
// Get the variable name.
const varName = text.substring(tokens[0].startOffset, tokens[0].endOffset);
if (typeof varValue === "string") {
// The variable value is valid, set the variable name's title of the first argument
// in var() to display the variable name and value.
firstOpts["data-variable"] = STYLE_INSPECTOR_L10N.getFormatStr(
"rule.variableValue",
varName,
varValue
);
firstOpts.class = options.matchedVariableClass;
secondOpts.class = options.unmatchedVariableClass;
} else {
// The variable name is not valid, mark it unmatched.
firstOpts.class = options.unmatchedVariableClass;
firstOpts["data-variable"] = STYLE_INSPECTOR_L10N.getFormatStr(
"rule.variableUnset",
varName
);
}
variableNode.appendChild(this.#createNode("span", firstOpts, result));
// If we saw a ",", then append it and show the remainder using
// the correct highlighting.
if (sawComma) {
variableNode.appendChild(this.#doc.createTextNode(","));
// Parse the text up until the close paren, being sure to
// disable the special case for filter.
const subOptions = Object.assign({}, options);
subOptions.expectFilter = false;
const saveParsed = this.#parsed;
this.#parsed = [];
const rest = this.#doParse(text, subOptions, tokenStream, true);
this.#parsed = saveParsed;
const span = this.#createNode("span", secondOpts);
span.appendChild(rest);
variableNode.appendChild(span);
}
variableNode.appendChild(this.#doc.createTextNode(")"));
return { node: variableNode, value: varValue };
}
/**
* The workhorse for @see #parse. This parses some CSS text,
* stopping at EOF; or optionally when an umatched close paren is
* seen.
*
* @param {String} text
* The original input text.
* @param {Object} options
* The options object in use; @see #mergeOptions.
* @param {CSSLexer} tokenStream
* The token stream from which to read
* @param {Boolean} stopAtCloseParen
* If true, stop at an umatched close paren.
* @return {DocumentFragment}
* A document fragment.
*/
// eslint-disable-next-line complexity
#doParse(text, options, tokenStream, stopAtCloseParen) {
let parenDepth = stopAtCloseParen ? 1 : 0;
let outerMostFunctionTakesColor = false;
const colorFunctions = [];
let fontFamilyNameParts = [];
let previousWasBang = false;
const colorOK = function () {
return (
options.supportsColor ||
(options.expectFilter &&
parenDepth === 1 &&
outerMostFunctionTakesColor)
);
};
const angleOK = function (angle) {
return new angleUtils.CssAngle(angle).valid;
};
let spaceNeeded = false;
let done = false;
while (!done) {
const token = tokenStream.nextToken();
if (!token) {
break;
}
const lowerCaseTokenText = token.text?.toLowerCase();
if (token.tokenType === "comment") {
// This doesn't change spaceNeeded, because we didn't emit
// anything to the output.
continue;
}
switch (token.tokenType) {
case "function": {
const isColorTakingFunction =
COLOR_TAKING_FUNCTIONS.includes(lowerCaseTokenText);
if (
isColorTakingFunction ||
ANGLE_TAKING_FUNCTIONS.includes(lowerCaseTokenText)
) {
// The function can accept a color or an angle argument, and we know
// it isn't special in some other way. So, we let it
// through to the ordinary parsing loop so that the value
// can be handled in a single place.
this.#appendTextNode(
text.substring(token.startOffset, token.endOffset)
);
if (parenDepth === 0) {
outerMostFunctionTakesColor = isColorTakingFunction;
}
if (isColorTakingFunction) {
colorFunctions.push({ parenDepth, functionName: token.text });
}
++parenDepth;
} else if (lowerCaseTokenText === "var" && options.getVariableValue) {
const { node: variableNode, value } = this.#parseVariable(
token,
text,
tokenStream,
options
);
if (value && colorOK() && InspectorUtils.isValidCSSColor(value)) {
this.#appendColor(value, {
...options,
variableContainer: variableNode,
colorFunction: colorFunctions.at(-1)?.functionName,
});
} else {
this.#parsed.push(variableNode);
}
} else {
const { functionData, sawVariable } = this.#parseMatchingParens(
text,
tokenStream,
options
);
const functionName = text.substring(
token.startOffset,
token.endOffset
);
if (sawVariable) {
// If function contains variable, we need to add both strings
// and nodes.
this.#appendTextNode(functionName);
for (const data of functionData) {
if (typeof data === "string") {
this.#appendTextNode(data);
} else if (data) {
this.#parsed.push(data);
}
}
this.#appendTextNode(")");
} else {
// If no variable in function, join the text together and add
// to DOM accordingly.
const functionText = functionName + functionData.join("") + ")";
if (
options.expectCubicBezier &&
lowerCaseTokenText === "cubic-bezier"
) {
this.#appendCubicBezier(functionText, options);
} else if (
options.expectLinearEasing &&
lowerCaseTokenText === "linear"
) {
this.#appendLinear(functionText, options);
} else if (
colorOK() &&
InspectorUtils.isValidCSSColor(functionText)
) {
this.#appendColor(functionText, {
...options,
colorFunction: colorFunctions.at(-1)?.functionName,
});
} else if (
options.expectShape &&
BASIC_SHAPE_FUNCTIONS.includes(lowerCaseTokenText)
) {
this.#appendShape(functionText, options);
} else {
this.#appendTextNode(functionText);
}
}
}
break;
}
case "ident":
if (
options.expectCubicBezier &&
BEZIER_KEYWORDS.includes(lowerCaseTokenText)
) {
this.#appendCubicBezier(token.text, options);
} else if (
options.expectLinearEasing &&
lowerCaseTokenText == "linear"
) {
this.#appendLinear(token.text, options);
} else if (this.#isDisplayFlex(text, token, options)) {
this.#appendHighlighterToggle(token.text, options.flexClass);
} else if (this.#isDisplayGrid(text, token, options)) {
this.#appendHighlighterToggle(token.text, options.gridClass);
} else if (colorOK() && InspectorUtils.isValidCSSColor(token.text)) {
this.#appendColor(token.text, {
...options,
colorFunction: colorFunctions.at(-1)?.functionName,
});
} else if (angleOK(token.text)) {
this.#appendAngle(token.text, options);
} else if (options.expectFont && !previousWasBang) {
// We don't append the identifier if the previous token
// was equal to '!', since in that case we expect the
// identifier to be equal to 'important'.
fontFamilyNameParts.push(token.text);
} else {
this.#appendTextNode(
text.substring(token.startOffset, token.endOffset)
);
}
break;
case "id":
case "hash": {
const original = text.substring(token.startOffset, token.endOffset);
if (colorOK() && InspectorUtils.isValidCSSColor(original)) {
if (spaceNeeded) {
// Insert a space to prevent token pasting when a #xxx
// color is changed to something like rgb(...).
this.#appendTextNode(" ");
}
this.#appendColor(original, {
...options,
colorFunction: colorFunctions.at(-1)?.functionName,
});
} else {
this.#appendTextNode(original);
}
break;
}
case "dimension":
const value = text.substring(token.startOffset, token.endOffset);
if (angleOK(value)) {
this.#appendAngle(value, options);
} else {
this.#appendTextNode(value);
}
break;
case "url":
case "bad_url":
this.#appendURL(
text.substring(token.startOffset, token.endOffset),
token.text,
options
);
break;
case "string":
if (options.expectFont) {
fontFamilyNameParts.push(
text.substring(token.startOffset, token.endOffset)
);
} else {
this.#appendTextNode(
text.substring(token.startOffset, token.endOffset)
);
}
break;
case "whitespace":
if (options.expectFont) {
fontFamilyNameParts.push(" ");
} else {
this.#appendTextNode(
text.substring(token.startOffset, token.endOffset)
);
}
break;
case "symbol":
if (token.text === "(") {
++parenDepth;
} else if (token.text === ")") {
--parenDepth;
if (colorFunctions.at(-1)?.parenDepth == parenDepth) {
colorFunctions.pop();
}
if (stopAtCloseParen && parenDepth === 0) {
done = true;
break;
}
if (parenDepth === 0) {
outerMostFunctionTakesColor = false;
}
} else if (
(token.text === "," || token.text === "!") &&
options.expectFont &&
fontFamilyNameParts.length !== 0
) {
this.#appendFontFamily(fontFamilyNameParts.join(""), options);
fontFamilyNameParts = [];
}
// falls through
default:
this.#appendTextNode(
text.substring(token.startOffset, token.endOffset)
);
break;
}
// If this token might possibly introduce token pasting when
// color-cycling, require a space.
spaceNeeded =
token.tokenType === "ident" ||
token.tokenType === "at" ||
token.tokenType === "id" ||
token.tokenType === "hash" ||
token.tokenType === "number" ||
token.tokenType === "dimension" ||
token.tokenType === "percentage" ||
token.tokenType === "dimension";
previousWasBang = token.tokenType === "symbol" && token.text === "!";
}
if (options.expectFont && fontFamilyNameParts.length !== 0) {
this.#appendFontFamily(fontFamilyNameParts.join(""), options);
}
let result = this.#toDOM();
if (options.expectFilter && !options.filterSwatch) {
result = this.#wrapFilter(text, options, result);
}
return result;
}
/**
* Parse a string.
*
* @param {String} text
* Text to parse.
* @param {Object} [options]
* Options object. For valid options and default values see
* #mergeOptions().
* @return {DocumentFragment}
* A document fragment.
*/
#parse(text, options = {}) {
text = text.trim();
this.#parsed.length = 0;
const tokenStream = getCSSLexer(text);
return this.#doParse(text, options, tokenStream, false);
}
/**
* Returns true if it's a "display: [inline-]flex" token.
*
* @param {String} text
* The parsed text.
* @param {Object} token
* The parsed token.
* @param {Object} options
* The options given to #parse.
*/
#isDisplayFlex(text, token, options) {
return (
options.expectDisplay &&
(token.text === "flex" || token.text === "inline-flex")
);
}
/**
* Returns true if it's a "display: [inline-]grid" token.
*
* @param {String} text
* The parsed text.
* @param {Object} token
* The parsed token.
* @param {Object} options
* The options given to #parse.
*/
#isDisplayGrid(text, token, options) {
return (
options.expectDisplay &&
(token.text === "grid" || token.text === "inline-grid")
);
}
/**
* Append a cubic-bezier timing function value to the output
*
* @param {String} bezier
* The cubic-bezier timing function
* @param {Object} options
* Options object. For valid options and default values see
* #mergeOptions()
*/
#appendCubicBezier(bezier, options) {
const container = this.#createNode("span", {
"data-bezier": bezier,
});
if (options.bezierSwatchClass) {
const swatch = this.#createNode("span", {
class: options.bezierSwatchClass,
tabindex: "0",
role: "button",
});
container.appendChild(swatch);
}
const value = this.#createNode(
"span",
{
class: options.bezierClass,
},
bezier
);
container.appendChild(value);
this.#parsed.push(container);
}
#appendLinear(text, options) {
const container = this.#createNode("span", {
"data-linear": text,
});
if (options.linearEasingSwatchClass) {
const swatch = this.#createNode("span", {
class: options.linearEasingSwatchClass,
tabindex: "0",
role: "button",
"data-linear": text,
});
container.appendChild(swatch);
}
const value = this.#createNode(
"span",
{
class: options.linearEasingClass,
},
text
);
container.appendChild(value);
this.#parsed.push(container);
}
/**
* Append a Flexbox|Grid highlighter toggle icon next to the value in a
* "display: [inline-]flex" or "display: [inline-]grid" declaration.
*
* @param {String} text
* The text value to append
* @param {String} className
* The class name for the toggle span
*/
#appendHighlighterToggle(text, className) {
const container = this.#createNode("span", {});
const toggle = this.#createNode("span", {
class: className,
});
const value = this.#createNode("span", {});
value.textContent = text;
container.appendChild(toggle);
container.appendChild(value);
this.#parsed.push(container);
}
/**
* Append a CSS shapes highlighter toggle next to the value, and parse the value
* into spans, each containing a point that can be hovered over.
*
* @param {String} shape
* The shape text value to append
* @param {Object} options
* Options object. For valid options and default values see
* #mergeOptions()
*/
#appendShape(shape, options) {
const shapeTypes = [
{
prefix: "polygon(",
coordParser: this.#addPolygonPointNodes.bind(this),
},
{
prefix: "circle(",
coordParser: this.#addCirclePointNodes.bind(this),
},
{
prefix: "ellipse(",
coordParser: this.#addEllipsePointNodes.bind(this),
},
{
prefix: "inset(",
coordParser: this.#addInsetPointNodes.bind(this),
},
];
const container = this.#createNode("span", {});
const toggle = this.#createNode("span", {
class: options.shapeSwatchClass,
tabindex: "0",
role: "button",
});
const lowerCaseShape = shape.toLowerCase();
for (const { prefix, coordParser } of shapeTypes) {
if (lowerCaseShape.includes(prefix)) {
const coordsBegin = prefix.length;
const coordsEnd = shape.lastIndexOf(")");
let valContainer = this.#createNode("span", {
class: options.shapeClass,
});
container.appendChild(toggle);
appendText(valContainer, shape.substring(0, coordsBegin));
const coordsString = shape.substring(coordsBegin, coordsEnd);
valContainer = coordParser(coordsString, valContainer);
appendText(valContainer, shape.substring(coordsEnd));
container.appendChild(valContainer);
}
}
this.#parsed.push(container);
}
/**
* Parse the given polygon coordinates and create a span for each coordinate pair,
* adding it to the given container node.
*
* @param {String} coords
* The string of coordinate pairs.
* @param {Node} container
* The node to which spans containing points are added.
* @returns {Node} The container to which spans have been added.
*/
// eslint-disable-next-line complexity
#addPolygonPointNodes(coords, container) {
const tokenStream = getCSSLexer(coords);
let token = tokenStream.nextToken();
let coord = "";
let i = 0;
let depth = 0;
let isXCoord = true;
let fillRule = false;
let coordNode = this.#createNode("span", {
class: "ruleview-shape-point",
"data-point": `${i}`,
});
while (token) {
if (token.tokenType === "symbol" && token.text === ",") {
// Comma separating coordinate pairs; add coordNode to container and reset vars
if (!isXCoord) {
// Y coord not added to coordNode yet
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": `${i}`,
"data-pair": isXCoord ? "x" : "y",
},
coord
);
coordNode.appendChild(node);
coord = "";
isXCoord = !isXCoord;
}
if (fillRule) {
// If the last text added was a fill-rule, do not increment i.
fillRule = false;
} else {
container.appendChild(coordNode);
i++;
}
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
coord = "";
depth = 0;
isXCoord = true;
coordNode = this.#createNode("span", {
class: "ruleview-shape-point",
"data-point": `${i}`,
});
} else if (token.tokenType === "symbol" && token.text === "(") {
depth++;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "symbol" && token.text === ")") {
depth--;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "whitespace" && coord === "") {
// Whitespace at beginning of coord; add to container
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
} else if (token.tokenType === "whitespace" && depth === 0) {
// Whitespace signifying end of coord
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": `${i}`,
"data-pair": isXCoord ? "x" : "y",
},
coord
);
coordNode.appendChild(node);
appendText(
coordNode,
coords.substring(token.startOffset, token.endOffset)
);
coord = "";
isXCoord = !isXCoord;
} else if (
token.tokenType === "number" ||
token.tokenType === "dimension" ||
token.tokenType === "percentage" ||
token.tokenType === "function"
) {
if (isXCoord && coord && depth === 0) {
// Whitespace is not necessary between x/y coords.
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": `${i}`,
"data-pair": "x",
},
coord
);
coordNode.appendChild(node);
isXCoord = false;
coord = "";
}
coord += coords.substring(token.startOffset, token.endOffset);
if (token.tokenType === "function") {
depth++;
}
} else if (
token.tokenType === "ident" &&
(token.text === "nonzero" || token.text === "evenodd")
) {
// A fill-rule (nonzero or evenodd).
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
fillRule = true;
} else {
coord += coords.substring(token.startOffset, token.endOffset);
}
token = tokenStream.nextToken();
}
// Add coords if any are left over
if (coord) {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": `${i}`,
"data-pair": isXCoord ? "x" : "y",
},
coord
);
coordNode.appendChild(node);
container.appendChild(coordNode);
}
return container;
}
/**
* Parse the given circle coordinates and populate the given container appropriately
* with a separate span for the center point.
*
* @param {String} coords
* The circle definition.
* @param {Node} container
* The node to which the definition is added.
* @returns {Node} The container to which the definition has been added.
*/
// eslint-disable-next-line complexity
#addCirclePointNodes(coords, container) {
const tokenStream = getCSSLexer(coords);
let token = tokenStream.nextToken();
let depth = 0;
let coord = "";
let point = "radius";
const centerNode = this.#createNode("span", {
class: "ruleview-shape-point",
"data-point": "center",
});
while (token) {
if (token.tokenType === "symbol" && token.text === "(") {
depth++;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "symbol" && token.text === ")") {
depth--;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "whitespace" && coord === "") {
// Whitespace at beginning of coord; add to container
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
} else if (
token.tokenType === "whitespace" &&
point === "radius" &&
depth === 0
) {
// Whitespace signifying end of radius
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "radius",
},
coord
);
container.appendChild(node);
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
point = "cx";
coord = "";
depth = 0;
} else if (token.tokenType === "whitespace" && depth === 0) {
// Whitespace signifying end of cx/cy
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "center",
"data-pair": point === "cx" ? "x" : "y",
},
coord
);
centerNode.appendChild(node);
appendText(
centerNode,
coords.substring(token.startOffset, token.endOffset)
);
point = point === "cx" ? "cy" : "cx";
coord = "";
depth = 0;
} else if (token.tokenType === "ident" && token.text === "at") {
// "at"; Add radius to container if not already done so
if (point === "radius" && coord) {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "radius",
},
coord
);
container.appendChild(node);
}
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
point = "cx";
coord = "";
depth = 0;
} else if (
token.tokenType === "number" ||
token.tokenType === "dimension" ||
token.tokenType === "percentage" ||
token.tokenType === "function"
) {
if (point === "cx" && coord && depth === 0) {
// Center coords don't require whitespace between x/y. So if current point is
// cx, we have the cx coord, and depth is 0, then this token is actually cy.
// Add cx to centerNode and set point to cy.
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "center",
"data-pair": "x",
},
coord
);
centerNode.appendChild(node);
point = "cy";
coord = "";
}
coord += coords.substring(token.startOffset, token.endOffset);
if (token.tokenType === "function") {
depth++;
}
} else {
coord += coords.substring(token.startOffset, token.endOffset);
}
token = tokenStream.nextToken();
}
// Add coords if any are left over.
if (coord) {
if (point === "radius") {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "radius",
},
coord
);
container.appendChild(node);
} else {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "center",
"data-pair": point === "cx" ? "x" : "y",
},
coord
);
centerNode.appendChild(node);
}
}
if (centerNode.textContent) {
container.appendChild(centerNode);
}
return container;
}
/**
* Parse the given ellipse coordinates and populate the given container appropriately
* with a separate span for each point
*
* @param {String} coords
* The ellipse definition.
* @param {Node} container
* The node to which the definition is added.
* @returns {Node} The container to which the definition has been added.
*/
// eslint-disable-next-line complexity
#addEllipsePointNodes(coords, container) {
const tokenStream = getCSSLexer(coords);
let token = tokenStream.nextToken();
let depth = 0;
let coord = "";
let point = "rx";
const centerNode = this.#createNode("span", {
class: "ruleview-shape-point",
"data-point": "center",
});
while (token) {
if (token.tokenType === "symbol" && token.text === "(") {
depth++;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "symbol" && token.text === ")") {
depth--;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "whitespace" && coord === "") {
// Whitespace at beginning of coord; add to container
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
} else if (token.tokenType === "whitespace" && depth === 0) {
if (point === "rx" || point === "ry") {
// Whitespace signifying end of rx/ry
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": point,
},
coord
);
container.appendChild(node);
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
point = point === "rx" ? "ry" : "cx";
coord = "";
depth = 0;
} else {
// Whitespace signifying end of cx/cy
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "center",
"data-pair": point === "cx" ? "x" : "y",
},
coord
);
centerNode.appendChild(node);
appendText(
centerNode,
coords.substring(token.startOffset, token.endOffset)
);
point = point === "cx" ? "cy" : "cx";
coord = "";
depth = 0;
}
} else if (token.tokenType === "ident" && token.text === "at") {
// "at"; Add radius to container if not already done so
if (point === "ry" && coord) {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "ry",
},
coord
);
container.appendChild(node);
}
appendText(
container,
coords.substring(token.startOffset, token.endOffset)
);
point = "cx";
coord = "";
depth = 0;
} else if (
token.tokenType === "number" ||
token.tokenType === "dimension" ||
token.tokenType === "percentage" ||
token.tokenType === "function"
) {
if (point === "rx" && coord && depth === 0) {
// Radius coords don't require whitespace between x/y.
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "rx",
},
coord
);
container.appendChild(node);
point = "ry";
coord = "";
}
if (point === "cx" && coord && depth === 0) {
// Center coords don't require whitespace between x/y.
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "center",
"data-pair": "x",
},
coord
);
centerNode.appendChild(node);
point = "cy";
coord = "";
}
coord += coords.substring(token.startOffset, token.endOffset);
if (token.tokenType === "function") {
depth++;
}
} else {
coord += coords.substring(token.startOffset, token.endOffset);
}
token = tokenStream.nextToken();
}
// Add coords if any are left over.
if (coord) {
if (point === "rx" || point === "ry") {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": point,
},
coord
);
container.appendChild(node);
} else {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
"data-point": "center",
"data-pair": point === "cx" ? "x" : "y",
},
coord
);
centerNode.appendChild(node);
}
}
if (centerNode.textContent) {
container.appendChild(centerNode);
}
return container;
}
/**
* Parse the given inset coordinates and populate the given container appropriately.
*
* @param {String} coords
* The inset definition.
* @param {Node} container
* The node to which the definition is added.
* @returns {Node} The container to which the definition has been added.
*/
// eslint-disable-next-line complexity
#addInsetPointNodes(coords, container) {
const insetPoints = ["top", "right", "bottom", "left"];
const tokenStream = getCSSLexer(coords);
let token = tokenStream.nextToken();
let depth = 0;
let coord = "";
let i = 0;
let round = false;
// nodes is an array containing all the coordinate spans. otherText is an array of
// arrays, each containing the text that should be inserted into container before
// the node with the same index. i.e. all elements of otherText[i] is inserted
// into container before nodes[i].
const nodes = [];
const otherText = [[]];
while (token) {
if (round) {
// Everything that comes after "round" should just be plain text
otherText[i].push(coords.substring(token.startOffset, token.endOffset));
} else if (token.tokenType === "symbol" && token.text === "(") {
depth++;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "symbol" && token.text === ")") {
depth--;
coord += coords.substring(token.startOffset, token.endOffset);
} else if (token.tokenType === "whitespace" && coord === "") {
// Whitespace at beginning of coord; add to container
otherText[i].push(coords.substring(token.startOffset, token.endOffset));
} else if (token.tokenType === "whitespace" && depth === 0) {
// Whitespace signifying end of coord; create node and push to nodes
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
},
coord
);
nodes.push(node);
i++;
coord = "";
otherText[i] = [coords.substring(token.startOffset, token.endOffset)];
depth = 0;
} else if (
token.tokenType === "number" ||
token.tokenType === "dimension" ||
token.tokenType === "percentage" ||
token.tokenType === "function"
) {
if (coord && depth === 0) {
// Inset coords don't require whitespace between each coord.
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
},
coord
);
nodes.push(node);
i++;
coord = "";
otherText[i] = [];
}
coord += coords.substring(token.startOffset, token.endOffset);
if (token.tokenType === "function") {
depth++;
}
} else if (token.tokenType === "ident" && token.text === "round") {
if (coord && depth === 0) {
// Whitespace is not necessary before "round"; create a new node for the coord
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
},
coord
);
nodes.push(node);
i++;
coord = "";
otherText[i] = [];
}
round = true;
otherText[i].push(coords.substring(token.startOffset, token.endOffset));
} else {
coord += coords.substring(token.startOffset, token.endOffset);
}
token = tokenStream.nextToken();
}
// Take care of any leftover text
if (coord) {
if (round) {
otherText[i].push(coord);
} else {
const node = this.#createNode(
"span",
{
class: "ruleview-shape-point",
},
coord
);
nodes.push(node);
}
}
// insetPoints contains the 4 different possible inset points in the order they are
// defined. By taking the modulo of the index in insetPoints with the number of nodes,
// we can get which node represents each point (e.g. if there is only 1 node, it
// represents all 4 points). The exception is "left" when there are 3 nodes. In that
// case, it is nodes[1] that represents the left point rather than nodes[0].
for (let j = 0; j < 4; j++) {
const point = insetPoints[j];
const nodeIndex =
point === "left" && nodes.length === 3 ? 1 : j % nodes.length;
nodes[nodeIndex].classList.add(point);
}
nodes.forEach((node, j, array) => {
for (const text of otherText[j]) {
appendText(container, text);
}
container.appendChild(node);
});
// Add text that comes after the last node, if any exists
if (otherText[nodes.length]) {
for (const text of otherText[nodes.length]) {
appendText(container, text);
}
}
return container;
}
/**
* Append a angle value to the output
*
* @param {String} angle
* angle to append
* @param {Object} options
* Options object. For valid options and default values see
* #mergeOptions()
*/
#appendAngle(angle, options) {
const angleObj = new angleUtils.CssAngle(angle);
const container = this.#createNode("span", {
"data-angle": angle,
});
if (options.angleSwatchClass) {
const swatch = this.#createNode("span", {
class: options.angleSwatchClass,
tabindex: "0",
role: "button",
});
this.#angleSwatches.set(swatch, angleObj);
swatch.addEventListener("mousedown", this.#onAngleSwatchMouseDown);
// Add click listener to stop event propagation when shift key is pressed
// in order to prevent the value input to be focused.
// Bug 711942 will add a tooltip to edit angle values and we should
// be able to move this listener to Tooltip.js when it'll be implemented.
swatch.addEventListener("click", function (event) {
if (event.shiftKey) {
event.stopPropagation();
}
});
container.appendChild(swatch);
}
const value = this.#createNode(
"span",
{
class: options.angleClass,
},
angle
);
container.appendChild(value);
this.#parsed.push(container);
}
/**
* Check if a CSS property supports a specific value.
*
* @param {String} name
* CSS Property name to check
* @param {String} value
* CSS Property value to check
*/
#cssPropertySupportsValue(name, value) {
// Checking pair as a CSS declaration string to account for "!important" in value.
const declaration = `${name}:${value}`;
return this.#doc.defaultView.CSS.supports(declaration);
}
/**
* Tests if a given colorObject output by CssColor is valid for parsing.
* Valid means it's really a color, not any of the CssColor SPECIAL_VALUES
* except transparent
*/
#isValidColor(colorObj) {
return (
colorObj.valid &&
(!colorObj.specialValue || colorObj.specialValue === "transparent")
);
}
/**
* Append a color to the output.
*
* @param {String} color
* Color to append
* @param {Object} [options]
* Options object. For valid options and default values see
* #mergeOptions().
*/
#appendColor(color, options = {}) {
const colorObj = new colorUtils.CssColor(color);
if (this.#isValidColor(colorObj)) {
const container = this.#createNode("span", {
"data-color": color,
});
if (options.colorSwatchClass) {
let attributes = {
class: options.colorSwatchClass,
style: "background-color:" + color,
};
// Color swatches next to values trigger the color editor everywhere aside from
// the Computed panel where values are read-only.
if (!options.colorSwatchClass.startsWith("computed-")) {
attributes = { ...attributes, tabindex: "0", role: "button" };
}
// The swatch is a <span> instead of a <button> intentionally. See Bug 1597125.
// It is made keyboard accessible via `tabindex` and has keydown handlers
// attached for pressing SPACE and RETURN in SwatchBasedEditorTooltip.js
const swatch = this.#createNode("span", attributes);
this.#colorSwatches.set(swatch, colorObj);
if (options.colorFunction) {
swatch.dataset.colorFunction = options.colorFunction;
}
swatch.addEventListener("mousedown", this.#onColorSwatchMouseDown);
container.appendChild(swatch);
}
let colorUnit = options.defaultColorUnit;
if (!options.useDefaultColorUnit) {
// If we're not being asked to convert the color to the default color type
// specified by the user, then force the CssColor instance to be set to the type
// of the current color.
// Not having a type means that the default color type will be automatically used.
colorUnit = colorUtils.classifyColor(color);
}
color = colorObj.toString(colorUnit);
container.dataset.color = color;
// Next we create the markup to show the value of the property.
if (options.variableContainer) {
// If we are creating a color swatch for a CSS variable we simply reuse
// the markup created for the variableContainer.
if (options.colorClass) {
options.variableContainer.classList.add(options.colorClass);
}
container.appendChild(options.variableContainer);
} else {
// Otherwise we create a new element with the `color` as textContent.
const value = this.#createNode(
"span",
{
class: options.colorClass,
},
color
);
container.appendChild(value);
}
this.#parsed.push(container);
} else {
this.#appendTextNode(color);
}
}
/**
* Wrap some existing nodes in a filter editor.
*
* @param {String} filters
* The full text of the "filter" property.
* @param {object} options
* The options object passed to parseCssProperty().
* @param {object} nodes
* Nodes created by #toDOM().
*
* @returns {object}
* A new node that supplies a filter swatch and that wraps |nodes|.
*/
#wrapFilter(filters, options, nodes) {
const container = this.#createNode("span", {
"data-filters": filters,
});
if (options.filterSwatchClass) {
const swatch = this.#createNode("span", {
class: options.filterSwatchClass,
tabindex: "0",
role: "button",
});
container.appendChild(swatch);
}
const value = this.#createNode("span", {
class: options.filterClass,
});
value.appendChild(nodes);
container.appendChild(value);
return container;
}
#onColorSwatchMouseDown = event => {
if (!event.shiftKey) {
return;
}
// Prevent click event to be fired to not show the tooltip
event.stopPropagation();
const swatch = event.target;
const color = this.#colorSwatches.get(swatch);
const val = color.nextColorUnit();
swatch.nextElementSibling.textContent = val;
swatch.parentNode.dataset.color = val;
const unitChangeEvent = new swatch.ownerGlobal.CustomEvent("unit-change");
swatch.dispatchEvent(unitChangeEvent);
};
#onAngleSwatchMouseDown = event => {
if (!event.shiftKey) {
return;
}
event.stopPropagation();
const swatch = event.target;
const angle = this.#angleSwatches.get(swatch);
const val = angle.nextAngleUnit();
swatch.nextElementSibling.textContent = val;
const unitChangeEvent = new swatch.ownerGlobal.CustomEvent("unit-change");
swatch.dispatchEvent(unitChangeEvent);
};
/**
* A helper function that sanitizes a possibly-unterminated URL.
*/
#sanitizeURL(url) {
// Re-lex the URL and add any needed termination characters.
const urlTokenizer = getCSSLexer(url);
// Just read until EOF; there will only be a single token.
while (urlTokenizer.nextToken()) {
// Nothing.
}
return urlTokenizer.performEOFFixup(url, true);
}
/**
* Append a URL to the output.
*
* @param {String} match
* Complete match that may include "url(xxx)"
* @param {String} url
* Actual URL
* @param {Object} [options]
* Options object. For valid options and default values see
* #mergeOptions().
*/
#appendURL(match, url, options) {
if (options.urlClass) {
// Sanitize the URL. Note that if we modify the URL, we just
// leave the termination characters. This isn't strictly
// "as-authored", but it makes a bit more sense.
match = this.#sanitizeURL(match);
// This regexp matches a URL token. It puts the "url(", any
// leading whitespace, and any opening quote into |leader|; the
// URL text itself into |body|, and any trailing quote, trailing
// whitespace, and the ")" into |trailer|. We considered adding
// functionality for this to CSSLexer, in some way, but this
// seemed simpler on the whole.
const urlParts =
/^(url\([ \t\r\n\f]*(["']?))(.*?)(\2[ \t\r\n\f]*\))$/i.exec(match);
// Bail out if that didn't match anything.
if (!urlParts) {
this.#appendTextNode(match);
return;
}
const [, leader, , body, trailer] = urlParts;
this.#appendTextNode(leader);
let href = url;
if (options.baseURI) {
try {
href = new URL(url, options.baseURI).href;
} catch (e) {
// Ignore.
}
}
this.#appendNode(
"a",
{
target: "_blank",
class: options.urlClass,
href,
},
body
);
this.#appendTextNode(trailer);
} else {
this.#appendTextNode(match);
}
}
/**
* Append a font family to the output.
*
* @param {String} fontFamily
* Font family to append
* @param {Object} options
* Options object. For valid options and default values see
* #mergeOptions().
*/
#appendFontFamily(fontFamily, options) {
let spanContents = fontFamily;
let quoteChar = null;
let trailingWhitespace = false;
// Before appending the actual font-family span, we need to trim
// down the actual contents by removing any whitespace before and
// after, and any quotation characters in the passed string. Any
// such characters are preserved in the actual output, but just
// not inside the span element.
if (spanContents[0] === " ") {
this.#appendTextNode(" ");
spanContents = spanContents.slice(1);
}
if (spanContents[spanContents.length - 1] === " ") {
spanContents = spanContents.slice(0, -1);
trailingWhitespace = true;
}
if (spanContents[0] === "'" || spanContents[0] === '"') {
quoteChar = spanContents[0];
}
if (quoteChar) {
this.#appendTextNode(quoteChar);
spanContents = spanContents.slice(1, -1);
}
this.#appendNode(
"span",
{
class: options.fontFamilyClass,
},
spanContents
);
if (quoteChar) {
this.#appendTextNode(quoteChar);
}
if (trailingWhitespace) {
this.#appendTextNode(" ");
}
}
/**
* Create a node.
*
* @param {String} tagName
* Tag type e.g. "div"
* @param {Object} attributes
* e.g. {class: "someClass", style: "cursor:pointer"};
* @param {String} [value]
* If a value is included it will be appended as a text node inside
* the tag. This is useful e.g. for span tags.
* @return {Node} Newly created Node.
*/
#createNode(tagName, attributes, value = "") {
const node = this.#doc.createElementNS(HTML_NS, tagName);
const attrs = Object.getOwnPropertyNames(attributes);
for (const attr of attrs) {
if (attributes[attr]) {
node.setAttribute(attr, attributes[attr]);
}
}
if (value) {
const textNode = this.#doc.createTextNode(value);
node.appendChild(textNode);
}
return node;
}
/**
* Append a node to the output.
*
* @param {String} tagName
* Tag type e.g. "div"
* @param {Object} attributes
* e.g. {class: "someClass", style: "cursor:pointer"};
* @param {String} [value]
* If a value is included it will be appended as a text node inside
* the tag. This is useful e.g. for span tags.
*/
#appendNode(tagName, attributes, value = "") {
const node = this.#createNode(tagName, attributes, value);
if (value.length > TRUNCATE_LENGTH_THRESHOLD) {
node.classList.add(TRUNCATE_NODE_CLASSNAME);
}
this.#parsed.push(node);
}
/**
* Append a text node to the output. If the previously output item was a text
* node then we append the text to that node.
*
* @param {String} text
* Text to append
*/
#appendTextNode(text) {
const lastItem = this.#parsed[this.#parsed.length - 1];
if (text.length > TRUNCATE_LENGTH_THRESHOLD) {
// If the text is too long, force creating a node, which will add the
// necessary classname to truncate the property correctly.
this.#appendNode("span", {}, text);
} else if (typeof lastItem === "string") {
this.#parsed[this.#parsed.length - 1] = lastItem + text;
} else {
this.#parsed.push(text);
}
}
/**
* Take all output and append it into a single DocumentFragment.
*
* @return {DocumentFragment}
* Document Fragment
*/
#toDOM() {
const frag = this.#doc.createDocumentFragment();
for (const item of this.#parsed) {
if (typeof item === "string") {
frag.appendChild(this.#doc.createTextNode(item));
} else {
frag.appendChild(item);
}
}
this.#parsed.length = 0;
return frag;
}
/**
* Merges options objects. Default values are set here.
*
* @param {Object} overrides
* The option values to override e.g. #mergeOptions({colors: false})
* @param {Boolean} overrides.useDefaultColorUnit: Convert colors to the default type
* selected in the options panel.
* @param {String} overrides.angleClass: The class to use for the angle value that follows
* the swatch.
* @param {String} overrides.angleSwatchClass: The class to use for angle swatches.
* @param {} overrides.bezierClass: "" // The class to use for the bezier value
* // that follows the swatch.
* @param {} overrides.bezierSwatchClass: "" // The class to use for bezier swatches.
* @param {} overrides.colorClass: "" // The class to use for the color value
* // that follows the swatch.
* @param {} overrides.colorSwatchClass: "" // The class to use for color swatches.
* @param {} overrides.filterSwatch: false // A special case for parsing a
* // "filter" property, causing the
* // parser to skip the call to
* // #wrapFilter. Used only for
* // previewing with the filter swatch.
* @param {} overrides.flexClass: "" // The class to use for the flex icon.
* @param {} overrides.gridClass: "" // The class to use for the grid icon.
* @param {} overrides.shapeClass: "" // The class to use for the shape value
* // that follows the swatch.
* @param {} overrides.shapeSwatchClass: "" // The class to use for the shape swatch.
* @param {} overrides.supportsColor: false // Does the CSS property support colors?
* @param {} overrides.urlClass: "" // The class to be used for url() links.
* @param {} overrides.fontFamilyClass: "" // The class to be used for font families.
* @param {} overrides.baseURI: undefined // A string used to resolve
* // relative links.
* @param {} overrides.getVariableValue // A function taking a single
* // argument, the name of a variable.
* // This should return the variable's
* // value, if it is in use; or null.
* - unmatchedVariableClass: ""
* // The class to use for a component
* // of a "var(...)" that is not in
* // use.
* @return {Object}
* Overridden options object
*/
#mergeOptions(overrides) {
const defaults = {
useDefaultColorUnit: true,
defaultColorUnit: "authored",
angleClass: "",
angleSwatchClass: "",
bezierClass: "",
bezierSwatchClass: "",
colorClass: "",
colorSwatchClass: "",
filterSwatch: false,
flexClass: "",
gridClass: "",
shapeClass: "",
shapeSwatchClass: "",
supportsColor: false,
urlClass: "",
fontFamilyClass: "",
baseURI: undefined,
getVariableValue: null,
unmatchedVariableClass: null,
};
for (const item in overrides) {
defaults[item] = overrides[item];
}
return defaults;
}
}
module.exports = OutputParser;
|