diff options
Diffstat (limited to 'devtools/shared/css')
-rw-r--r-- | devtools/shared/css/color-db.js | 323 | ||||
-rw-r--r-- | devtools/shared/css/color.js | 766 | ||||
-rw-r--r-- | devtools/shared/css/constants.js | 38 | ||||
-rw-r--r-- | devtools/shared/css/lexer.js | 1522 | ||||
-rw-r--r-- | devtools/shared/css/moz.build | 13 | ||||
-rw-r--r-- | devtools/shared/css/parsing-utils.js | 783 |
6 files changed, 3445 insertions, 0 deletions
diff --git a/devtools/shared/css/color-db.js b/devtools/shared/css/color-db.js new file mode 100644 index 0000000000..fbac9d9d4b --- /dev/null +++ b/devtools/shared/css/color-db.js @@ -0,0 +1,323 @@ +/* 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"; + +// /!\ Auto-generated from nsColorNameList.h. +// This should be kept in sync with that list. +// test_cssColorDatabase.js tries to enforce this. + +const cssColors = { + aliceblue: [240, 248, 255, 1], + antiquewhite: [250, 235, 215, 1], + aqua: [0, 255, 255, 1], + aquamarine: [127, 255, 212, 1], + azure: [240, 255, 255, 1], + beige: [245, 245, 220, 1], + bisque: [255, 228, 196, 1], + black: [0, 0, 0, 1], + blanchedalmond: [255, 235, 205, 1], + blue: [0, 0, 255, 1], + blueviolet: [138, 43, 226, 1], + brown: [165, 42, 42, 1], + burlywood: [222, 184, 135, 1], + cadetblue: [95, 158, 160, 1], + chartreuse: [127, 255, 0, 1], + chocolate: [210, 105, 30, 1], + coral: [255, 127, 80, 1], + cornflowerblue: [100, 149, 237, 1], + cornsilk: [255, 248, 220, 1], + crimson: [220, 20, 60, 1], + cyan: [0, 255, 255, 1], + darkblue: [0, 0, 139, 1], + darkcyan: [0, 139, 139, 1], + darkgoldenrod: [184, 134, 11, 1], + darkgray: [169, 169, 169, 1], + darkgreen: [0, 100, 0, 1], + darkgrey: [169, 169, 169, 1], + darkkhaki: [189, 183, 107, 1], + darkmagenta: [139, 0, 139, 1], + darkolivegreen: [85, 107, 47, 1], + darkorange: [255, 140, 0, 1], + darkorchid: [153, 50, 204, 1], + darkred: [139, 0, 0, 1], + darksalmon: [233, 150, 122, 1], + darkseagreen: [143, 188, 143, 1], + darkslateblue: [72, 61, 139, 1], + darkslategray: [47, 79, 79, 1], + darkslategrey: [47, 79, 79, 1], + darkturquoise: [0, 206, 209, 1], + darkviolet: [148, 0, 211, 1], + deeppink: [255, 20, 147, 1], + deepskyblue: [0, 191, 255, 1], + dimgray: [105, 105, 105, 1], + dimgrey: [105, 105, 105, 1], + dodgerblue: [30, 144, 255, 1], + firebrick: [178, 34, 34, 1], + floralwhite: [255, 250, 240, 1], + forestgreen: [34, 139, 34, 1], + fuchsia: [255, 0, 255, 1], + gainsboro: [220, 220, 220, 1], + ghostwhite: [248, 248, 255, 1], + gold: [255, 215, 0, 1], + goldenrod: [218, 165, 32, 1], + gray: [128, 128, 128, 1], + grey: [128, 128, 128, 1], + green: [0, 128, 0, 1], + greenyellow: [173, 255, 47, 1], + honeydew: [240, 255, 240, 1], + hotpink: [255, 105, 180, 1], + indianred: [205, 92, 92, 1], + indigo: [75, 0, 130, 1], + ivory: [255, 255, 240, 1], + khaki: [240, 230, 140, 1], + lavender: [230, 230, 250, 1], + lavenderblush: [255, 240, 245, 1], + lawngreen: [124, 252, 0, 1], + lemonchiffon: [255, 250, 205, 1], + lightblue: [173, 216, 230, 1], + lightcoral: [240, 128, 128, 1], + lightcyan: [224, 255, 255, 1], + lightgoldenrodyellow: [250, 250, 210, 1], + lightgray: [211, 211, 211, 1], + lightgreen: [144, 238, 144, 1], + lightgrey: [211, 211, 211, 1], + lightpink: [255, 182, 193, 1], + lightsalmon: [255, 160, 122, 1], + lightseagreen: [32, 178, 170, 1], + lightskyblue: [135, 206, 250, 1], + lightslategray: [119, 136, 153, 1], + lightslategrey: [119, 136, 153, 1], + lightsteelblue: [176, 196, 222, 1], + lightyellow: [255, 255, 224, 1], + lime: [0, 255, 0, 1], + limegreen: [50, 205, 50, 1], + linen: [250, 240, 230, 1], + magenta: [255, 0, 255, 1], + maroon: [128, 0, 0, 1], + mediumaquamarine: [102, 205, 170, 1], + mediumblue: [0, 0, 205, 1], + mediumorchid: [186, 85, 211, 1], + mediumpurple: [147, 112, 219, 1], + mediumseagreen: [60, 179, 113, 1], + mediumslateblue: [123, 104, 238, 1], + mediumspringgreen: [0, 250, 154, 1], + mediumturquoise: [72, 209, 204, 1], + mediumvioletred: [199, 21, 133, 1], + midnightblue: [25, 25, 112, 1], + mintcream: [245, 255, 250, 1], + mistyrose: [255, 228, 225, 1], + moccasin: [255, 228, 181, 1], + navajowhite: [255, 222, 173, 1], + navy: [0, 0, 128, 1], + oldlace: [253, 245, 230, 1], + olive: [128, 128, 0, 1], + olivedrab: [107, 142, 35, 1], + orange: [255, 165, 0, 1], + orangered: [255, 69, 0, 1], + orchid: [218, 112, 214, 1], + palegoldenrod: [238, 232, 170, 1], + palegreen: [152, 251, 152, 1], + paleturquoise: [175, 238, 238, 1], + palevioletred: [219, 112, 147, 1], + papayawhip: [255, 239, 213, 1], + peachpuff: [255, 218, 185, 1], + peru: [205, 133, 63, 1], + pink: [255, 192, 203, 1], + plum: [221, 160, 221, 1], + powderblue: [176, 224, 230, 1], + purple: [128, 0, 128, 1], + rebeccapurple: [102, 51, 153, 1], + red: [255, 0, 0, 1], + rosybrown: [188, 143, 143, 1], + royalblue: [65, 105, 225, 1], + saddlebrown: [139, 69, 19, 1], + salmon: [250, 128, 114, 1], + sandybrown: [244, 164, 96, 1], + seagreen: [46, 139, 87, 1], + seashell: [255, 245, 238, 1], + sienna: [160, 82, 45, 1], + silver: [192, 192, 192, 1], + skyblue: [135, 206, 235, 1], + slateblue: [106, 90, 205, 1], + slategray: [112, 128, 144, 1], + slategrey: [112, 128, 144, 1], + snow: [255, 250, 250, 1], + springgreen: [0, 255, 127, 1], + steelblue: [70, 130, 180, 1], + tan: [210, 180, 140, 1], + teal: [0, 128, 128, 1], + thistle: [216, 191, 216, 1], + tomato: [255, 99, 71, 1], + turquoise: [64, 224, 208, 1], + violet: [238, 130, 238, 1], + wheat: [245, 222, 179, 1], + white: [255, 255, 255, 1], + whitesmoke: [245, 245, 245, 1], + yellow: [255, 255, 0, 1], + yellowgreen: [154, 205, 50, 1], +}; + +// Lab values generated using formula from http://www.easyrgb.com/en/math.php. +// X_10, Y_10, Z_10 (CIE 1964) reference values for D65 illuminant +// (Daylight, sRGB, Adobe-RGB) were used. +const labColors = { + aliceblue: [97.17890760827636, -0.9397756746095665, -5.246475627032843], + antiquewhite: [93.73077088204487, 2.236373679139203, 10.649604819299775], + aqua: [91.11652110946342, -47.73670577664391, -15.108617112376965], + aquamarine: [92.03615371984776, -45.172410289053445, 8.849868350925295], + azure: [98.93278063011066, -4.468521315692032, -2.6738855376031267], + beige: [95.9488798865349, -3.7925176714859177, 11.156542330042662], + bisque: [92.0124490871158, 4.82408891282099, 18.18700912515505], + black: [0, 0, 0], + blanchedalmond: [93.91948969581235, 2.528359387620638, 16.175210959201024], + blue: [32.302586667249486, 79.43492388715862, -108.79669359538693], + blueviolet: [42.18810476642369, 70.12395877232036, -75.62885995423268], + brown: [37.521829744034335, 49.932241625757406, 30.23890786161597], + burlywood: [77.01689872654846, 7.390609044482909, 29.376190715516536], + cadetblue: [61.15461539950293, -19.415767005661277, -8.112231649104906], + chartreuse: [89.87420853068858, -67.74722658691745, 85.31006761317337], + chocolate: [55.98605299432204, 37.34619405020917, 56.41475927486582], + coral: [67.29048083264607, 45.696749904176436, 47.02073461855407], + cornflowerblue: [61.92818670495679, 9.628987440020332, -50.20264083555141], + cornsilk: [97.45526614880224, -1.8103271448461355, 13.39924085969022], + crimson: [47.02980511087301, 71.21981659922766, 33.22842672949625], + cyan: [91.11652110946342, -47.73670577664391, -15.108617112376965], + darkblue: [14.757156815274186, 50.58098497783475, -69.27738650827831], + darkcyan: [52.207519815998296, -30.3968264791159, -9.620563573304297], + darkgoldenrod: [59.2185428516686, 10.142719410772493, 62.4074048759456], + darkgray: [69.23779560557699, 0.30845909288851336, -0.725035226776094], + darkgreen: [36.20351872497333, -43.22004822584333, 41.62418791981264], + darkgrey: [69.23779560557699, 0.30845909288851336, -0.725035226776094], + darkkhaki: [73.38127833356914, -8.475096082350364, 38.72716132653318], + darkmagenta: [32.59748369188066, 62.78988696261057, -39.34048012552456], + darkolivegreen: [42.2340254244788, -18.63594475603103, 30.256085481863913], + darkorange: [69.48104411888188, 37.16688167941806, 75.14386507030734], + darkorchid: [43.37926695780136, 65.43267508264566, -60.90252187934995], + darkred: [28.084732284208997, 51.2102293904998, 41.189776600752445], + darksalmon: [69.85346453844176, 28.509213259811705, 27.1173578088314], + darkseagreen: [72.08740631745533, -23.522932623842696, 17.379064372791554], + darkslateblue: [30.829287209616794, 26.247343305352388, -42.688380574102695], + darkslategray: [31.25607829935253, -11.558209436609623, -4.143133638795559], + darkslategrey: [31.25607829935253, -11.558209436609623, -4.143133638795559], + darkturquoise: [75.29307531314078, -39.74330458218445, -14.353628151972542], + darkviolet: [39.57886745488795, 76.59826422688023, -71.18960396554851], + deeppink: [55.95428053659428, 84.8834888580915, -6.348160442712891], + deepskyblue: [72.54923231908798, -17.34624248545108, -43.501223759829614], + dimgray: [44.41356014781601, 0.21862498706087807, -0.513879541005613], + dimgrey: [44.41356014781601, 0.21862498706087807, -0.513879541005613], + dodgerblue: [59.381725677880596, 10.24722110279519, -64.33873493803226], + firebrick: [39.11257274771978, 56.17110340915579, 37.36856201227712], + floralwhite: [98.40143252802201, 0.37693631302881947, 4.4296183363891295], + forestgreen: [50.59443111773345, -49.389501730047996, 44.675247183324544], + fuchsia: [60.319933664076004, 98.60839787805526, -61.78226947982015], + gainsboro: [87.76088811005116, 0.3754905813360132, -0.8825932030137817], + ghostwhite: [97.7572735023453, 1.6602117625886814, -4.329673676949475], + gold: [86.9285847161576, -1.5580031594539245, 86.69625851871493], + goldenrod: [70.81571317667877, 8.842268163696321, 68.36969220318736], + gray: [53.585013452169036, 0.2518147023348183, -0.5918921958278478], + grey: [53.585013452169036, 0.2518147023348183, -0.5918921958278478], + green: [46.22881784262658, -51.520138371609654, 49.61780491379323], + greenyellow: [91.95763180408608, -52.141510237787294, 81.35705222692138], + honeydew: [98.56580137512647, -7.15743440652189, 4.528336799358468], + hotpink: [65.48186958181394, 64.59515848582348, -11.397593830097975], + indianred: [53.3911485087161, 45.12118404819798, 21.633935524110235], + indigo: [20.46961954096429, 51.86802044661362, -53.88700686969674], + ivory: [99.63977381109996, -2.1358046127358254, 6.214520241062194], + khaki: [90.32729582034386, -8.636557330944761, 44.29884008040395], + lavender: [91.82769059829121, 4.102249854337825, -10.62634890559453], + lavenderblush: [96.06837944039779, 6.29813340018881, -1.5503003307978824], + lawngreen: [88.87798766318886, -67.54051106102659, 84.48686421833247], + lemonchiffon: [97.6476983766357, -5.022220605824412, 21.377483194761602], + lightblue: [83.81410256512628, -10.538570949192195, -12.381398199756767], + lightcoral: [66.15316216626996, 43.146382854120255, 18.95210780303691], + lightcyan: [97.86814756512815, -9.540634546450377, -4.3595592568243635], + lightgoldenrodyellow: [ + 97.36879732328356, -6.078213524913445, 18.368452638973686, + ], + lightgray: [84.5561167363605, 0.36389313370355225, -0.8553333223096704], + lightgreen: [86.54957590580997, -45.99957827642365, 36.262226875570526], + lightgrey: [84.5561167363605, 0.36389313370355225, -0.8553333223096704], + lightpink: [81.05253594361857, 28.338879720153866, 4.233248736979411], + lightsalmon: [74.70287844017, 31.832905786707443, 33.947175894873574], + lightseagreen: [65.78768757989991, -37.24749389368925, -7.0553625579029555], + lightskyblue: [79.72503275959482, -10.490259345458607, -29.455091101479304], + lightslategray: [ + 55.917349372007195, -1.9881568917105574, -11.774175139854615, + ], + lightslategrey: [ + 55.917349372007195, -1.9881568917105574, -11.774175139854615, + ], + lightsteelblue: [78.45233742822654, -0.9392458669100212, -16.08913657631925], + lightyellow: [99.28483637693047, -4.695918870143368, 13.930783736002962], + lime: [87.73703347354422, -85.88539046866318, 82.71415186197115], + limegreen: [72.60854102811317, -66.86592102874306, 60.99160141799125], + linen: [95.31120096478845, 2.0811899572744097, 5.104906068897774], + magenta: [60.319933664076004, 98.60839787805526, -61.78226947982015], + maroon: [25.530784572416174, 48.24348236957932, 37.97194526317749], + mediumaquamarine: [75.6931293906138, -38.036553589818666, 7.571354765719218], + mediumblue: [24.97615723043893, 67.38641044652589, -92.29465191227868], + mediumorchid: [53.64213313573549, 59.370412003217574, -48.23242669563843], + mediumpurple: [54.97523587308039, 37.09186250486124, -50.94130373794006], + mediumseagreen: [65.27341001550978, -47.96643007935963, 23.721501577817094], + mediumslateblue: [52.15750471109439, 41.35727328020744, -66.29828530971085], + mediumspringgreen: [87.3411479783456, -70.37364235921007, 31.74790377903216], + mediumturquoise: [76.8834686242291, -37.053452849746925, -9.183510559800713], + mediumvioletred: [44.76162545138306, 71.28274660137451, -15.767834030225348], + midnightblue: [15.859552026439893, 31.860128204191234, -50.08845915164022], + mintcream: [99.15659662605985, -3.7499332041522893, 0.27328356915989893], + mistyrose: [92.65558901260384, 9.147609792762356, 3.9347415624175097], + moccasin: [91.72208952705464, 2.8291906794328248, 25.573953055107125], + navajowhite: [90.10007935356519, 4.895862633988224, 27.509525419099212], + navy: [12.975311577716514, 47.65069178672376, -65.26396023609063], + oldlace: [96.77967120416257, 0.5784959274544033, 7.247216630469544], + olive: [51.86833136334822, -12.698958090622824, 56.38276716821539], + olivedrab: [54.650773976467136, -27.99433891007591, 49.33893945670905], + orange: [74.93219484533535, 24.28083176103374, 78.57643571179258], + orangered: [57.57499421872107, 68.11461778155586, 68.68889341848478], + orchid: [62.8009876658991, 55.621167174625064, -35.24868649820956], + palegoldenrod: [91.14038954621267, -6.970467434592564, 30.213907174487264], + palegreen: [90.75103714758299, -47.95503269332063, 37.81303534889619], + paleturquoise: [90.06142407788806, -19.270453187271997, -7.332269935129032], + palevioletred: [60.564787867661266, 45.838854731426515, -0.25065577032372666], + papayawhip: [95.07544110280504, 1.6725420650229306, 13.652324626448543], + peachpuff: [89.34875285782702, 8.471965039192453, 20.229897875280955], + peru: [61.751663684265665, 21.6941378210313, 47.496113355477334], + pink: [83.58479885775868, 24.525540181552508, 2.4934778968259685], + plum: [73.37274280928348, 32.885443900333215, -22.856650741159747], + powderblue: [86.13359115282357, -13.734412712450183, -8.914802708654769], + purple: [29.782100092098077, 59.15229907621816, -37.06137976602428], + rebeccapurple: [32.90243720302775, 43.10251060523782, -47.79866704780537], + red: [53.23288178584245, 80.42312097443104, 66.96552840294578], + osybrown: [63.6060381979233, 17.31557480446677, 5.964013673186241], + royalblue: [47.83284750656463, 26.523923842683427, -66.12638984604963], + saddlebrown: [37.46692024400534, 26.659518429642898, 40.73548402580912], + salmon: [67.25995258561211, 45.569072753010865, 28.527978009408052], + sandybrown: [73.95154071958171, 23.37100127546693, 46.25858205082345], + seagreen: [51.53535112854968, -39.50584886698982, 19.578964107165852], + seashell: [97.12111642889012, 2.5730542225586572, 3.614216901880374], + sienna: [43.796139581025685, 29.564844221078523, 35.307185975723435], + silver: [77.7043635899527, 0.339097964550894, -0.7970521060836511], + skyblue: [79.20897459092869, -14.504258485788124, -22.18979862749155], + slateblue: [45.33730589003685, 36.29854743329886, -58.578448229379696], + slategray: [52.83625796271889, -1.894387969799849, -11.208348578862527], + slategrey: [52.83625796271889, -1.894387969799849, -11.208348578862527], + snow: [98.64376394836441, 2.073027231003055, -0.3849225040892579], + springgreen: [88.47265520282772, -76.59140183507563, 46.37560569696295], + steelblue: [52.46747241512048, -3.828873386915843, -32.93153861676517], + tan: [74.97454643298407, 5.353040309039603, 23.775061853275446], + teal: [48.25607381337552, -28.635856151982775, -9.063218319038114], + thistle: [80.07734471203901, 13.57781031097305, -10.092571203748268], + tomato: [62.20136881808274, 58.18874059980511, 45.985101486056514], + turquoise: [81.26705459794431, -43.765218870671475, -4.872758326234994], + violet: [69.69362286537107, 56.72140058020769, -37.7245806568902], + wheat: [89.35068099788126, 1.8921211283112749, 23.23051272657026], + white: [100, 0.41978155958710683, -0.9866994530830286], + whitesmoke: [96.53748961423615, 0.40725140432995577, -0.9572472366698781], + yellow: [97.13824698129729, -21.169488449187533, 93.99151723968109], + yellowgreen: [76.5351984302265, -37.69097531845872, 66.13250570541341], +}; + +exports.cssColors = cssColors; +exports.labColors = labColors; diff --git a/devtools/shared/css/color.js b/devtools/shared/css/color.js new file mode 100644 index 0000000000..16ea58bc08 --- /dev/null +++ b/devtools/shared/css/color.js @@ -0,0 +1,766 @@ +/* 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 COLOR_UNIT_PREF = "devtools.defaultColorUnit"; +const SPECIALVALUES = new Set([ + "currentcolor", + "initial", + "inherit", + "transparent", + "unset", +]); + +/** + * This module is used to convert between various color types. + * + * Usage: + * let {colorUtils} = require("devtools/shared/css/color"); + * let color = new colorUtils.CssColor("red"); + * // In order to support css-color-4 color function, pass true to the + * // second argument. + * // e.g. + * // let color = new colorUtils.CssColor("red", true); + * + * color.authored === "red" + * color.hasAlpha === false + * color.valid === true + * color.transparent === false // transparent has a special status. + * color.name === "red" // returns hex when no name available. + * color.hex === "#f00" // returns shortHex when available else returns + * longHex. If alpha channel is present then we + * return this.alphaHex if available, + * or this.longAlphaHex if not. + * color.alphaHex === "#f00f" // returns short alpha hex when available + * else returns longAlphaHex. + * color.longHex === "#ff0000" // If alpha channel is present then we return + * this.longAlphaHex. + * color.longAlphaHex === "#ff0000ff" + * color.rgb === "rgb(255, 0, 0)" // If alpha channel is present + * // then we return this.rgba. + * color.rgba === "rgba(255, 0, 0, 1)" + * color.hsl === "hsl(0, 100%, 50%)" + * color.hsla === "hsla(0, 100%, 50%, 1)" // If alpha channel is present + * then we return this.rgba. + * color.hwb === "hwb(0, 0%, 0%)" + * + * color.toString() === "#f00"; // Outputs the color type determined in the + * COLOR_UNIT_PREF constant (above). + * + * Valid values for COLOR_UNIT_PREF are contained in CssColor.COLORUNIT. + */ +class CssColor { + /** + * @param {String} colorValue: Any valid color string + */ + constructor(colorValue) { + // Store a lower-cased version of the color to help with format + // testing. The original text is kept as well so it can be + // returned when needed. + this.#lowerCased = colorValue.toLowerCase(); + this.#authored = colorValue; + } + + /** + * Values used in COLOR_UNIT_PREF + */ + static COLORUNIT = { + authored: "authored", + hex: "hex", + name: "name", + rgb: "rgb", + hsl: "hsl", + hwb: "hwb", + }; + + // The value as-authored. + #authored = null; + #currentFormat; + // A lower-cased copy of |authored|. + #lowerCased = null; + + get hasAlpha() { + if (!this.valid) { + return false; + } + return this.getRGBATuple().a !== 1; + } + + /** + * Return true if the color is a valid color and we can get rgba tuples from it. + */ + get valid() { + // We can't use InspectorUtils.isValidCSSColor as colors can be valid but we can't have + // their rgba tuples (e.g. currentColor, accentColor, … whose actual values depends on + // additional context we don't have here). + return InspectorUtils.colorToRGBA(this.#authored) !== null; + } + + /** + * Not a real color type but used to preserve accuracy when converting between + * e.g. 8 character hex -> rgba -> 8 character hex (hex alpha values are + * 0 - 255 but rgba alpha values are only 0.0 to 1.0). + */ + get highResTuple() { + const type = classifyColor(this.#authored); + + if (type === CssColor.COLORUNIT.hex) { + return hexToRGBA(this.#authored.substring(1), true); + } + + // If we reach this point then the alpha value must be in the range + // 0.0 - 1.0 so we need to multiply it by 255. + const tuple = InspectorUtils.colorToRGBA(this.#authored); + tuple.a *= 255; + return tuple; + } + + /** + * Return true for all transparent values e.g. rgba(0, 0, 0, 0). + */ + get transparent() { + try { + const tuple = this.getRGBATuple(); + return !(tuple.r || tuple.g || tuple.b || tuple.a); + } catch (e) { + return false; + } + } + + get specialValue() { + return SPECIALVALUES.has(this.#lowerCased) ? this.#authored : null; + } + + get name() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + + const tuple = this.getRGBATuple(); + + if (tuple.a !== 1) { + return this.hex; + } + const { r, g, b } = tuple; + return InspectorUtils.rgbToColorName(r, g, b) || this.hex; + } + + get hex() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (this.hasAlpha) { + return this.alphaHex; + } + + let hex = this.longHex; + if ( + hex.charAt(1) == hex.charAt(2) && + hex.charAt(3) == hex.charAt(4) && + hex.charAt(5) == hex.charAt(6) + ) { + hex = "#" + hex.charAt(1) + hex.charAt(3) + hex.charAt(5); + } + return hex; + } + + get alphaHex() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + + let alphaHex = this.longAlphaHex; + if ( + alphaHex.charAt(1) == alphaHex.charAt(2) && + alphaHex.charAt(3) == alphaHex.charAt(4) && + alphaHex.charAt(5) == alphaHex.charAt(6) && + alphaHex.charAt(7) == alphaHex.charAt(8) + ) { + alphaHex = + "#" + + alphaHex.charAt(1) + + alphaHex.charAt(3) + + alphaHex.charAt(5) + + alphaHex.charAt(7); + } + return alphaHex; + } + + get longHex() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (this.hasAlpha) { + return this.longAlphaHex; + } + + const tuple = this.getRGBATuple(); + return ( + "#" + + ((1 << 24) + (tuple.r << 16) + (tuple.g << 8) + (tuple.b << 0)) + .toString(16) + .substr(-6) + ); + } + + get longAlphaHex() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + + const tuple = this.highResTuple; + + return ( + "#" + + ((1 << 24) + (tuple.r << 16) + (tuple.g << 8) + (tuple.b << 0)) + .toString(16) + .substr(-6) + + Math.round(tuple.a).toString(16).padStart(2, "0") + ); + } + + get rgb() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (!this.hasAlpha) { + if (this.#lowerCased.startsWith("rgb(")) { + // The color is valid and begins with rgb(. + return this.#authored; + } + const tuple = this.getRGBATuple(); + return "rgb(" + tuple.r + ", " + tuple.g + ", " + tuple.b + ")"; + } + return this.rgba; + } + + get rgba() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (this.#lowerCased.startsWith("rgba(")) { + // The color is valid and begins with rgba(. + return this.#authored; + } + const components = this.getRGBATuple(); + return ( + "rgba(" + + components.r + + ", " + + components.g + + ", " + + components.b + + ", " + + components.a + + ")" + ); + } + + get hsl() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (this.#lowerCased.startsWith("hsl(")) { + // The color is valid and begins with hsl(. + return this.#authored; + } + if (this.hasAlpha) { + return this.hsla; + } + return this.#hsl(); + } + + get hsla() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (this.#lowerCased.startsWith("hsla(")) { + // The color is valid and begins with hsla(. + return this.#authored; + } + if (this.hasAlpha) { + const a = this.getRGBATuple().a; + return this.#hsl(a); + } + return this.#hsl(1); + } + + get hwb() { + const invalidOrSpecialValue = this.#getInvalidOrSpecialValue(); + if (invalidOrSpecialValue !== false) { + return invalidOrSpecialValue; + } + if (this.#lowerCased.startsWith("hwb(")) { + // The color is valid and begins with hwb(. + return this.#authored; + } + if (this.hasAlpha) { + const a = this.getRGBATuple().a; + return this.#hwb(a); + } + return this.#hwb(); + } + + /** + * Check whether the current color value is in the special list e.g. + * transparent or invalid. + * + * @return {String|Boolean} + * - If the current color is a special value e.g. "transparent" then + * return the color. + * - If the current color is a system value e.g. "accentcolor" then + * return the color. + * - If the color is invalid or that we can't get rgba components from it + * (e.g. "accentcolor"), return an empty string. + * - If the color is a regular color e.g. #F06 so we return false + * to indicate that the color is neither invalid or special. + */ + #getInvalidOrSpecialValue() { + if (this.specialValue) { + return this.specialValue; + } + if (!this.valid) { + return ""; + } + return false; + } + + nextColorUnit() { + // Reorder the formats array to have the current format at the + // front so we can cycle through. + // Put "name" at the end as that provides a hex value if there's + // no name for the color. + let formats = ["hex", "hsl", "rgb", "hwb", "name"]; + + let currentFormat = this.#currentFormat; + // If we don't have determined the current format yet + if (!currentFormat) { + // If the pref value is COLORUNIT.authored, get the actual unit from the authored color, + // otherwise use the pref value. + const defaultFormat = Services.prefs.getCharPref(COLOR_UNIT_PREF); + currentFormat = + defaultFormat === CssColor.COLORUNIT.authored + ? classifyColor(this.#authored) + : defaultFormat; + } + const putOnEnd = formats.splice(0, formats.indexOf(currentFormat)); + formats = [...formats, ...putOnEnd]; + + const currentDisplayedColor = this[formats[0]]; + + let colorUnit; + for (const format of formats) { + if (this[format].toLowerCase() !== currentDisplayedColor.toLowerCase()) { + colorUnit = CssColor.COLORUNIT[format]; + break; + } + } + + this.#currentFormat = colorUnit; + return this.toString(colorUnit); + } + + /** + * Return a string representing a color of type defined in COLOR_UNIT_PREF. + */ + toString(colorUnit, forceUppercase) { + let color; + + switch (colorUnit) { + case CssColor.COLORUNIT.authored: + color = this.#authored; + break; + case CssColor.COLORUNIT.hex: + color = this.hex; + break; + case CssColor.COLORUNIT.hsl: + color = this.hsl; + break; + case CssColor.COLORUNIT.name: + color = this.name; + break; + case CssColor.COLORUNIT.rgb: + color = this.rgb; + break; + case CssColor.COLORUNIT.hwb: + color = this.hwb; + break; + default: + color = this.rgb; + } + + if ( + forceUppercase || + (colorUnit != CssColor.COLORUNIT.authored && + colorIsUppercase(this.#authored)) + ) { + color = color.toUpperCase(); + } + + return color; + } + + /** + * Returns a RGBA 4-Tuple representation of a color or transparent as + * appropriate. + */ + getRGBATuple() { + const tuple = InspectorUtils.colorToRGBA(this.#authored); + + tuple.a = parseFloat(tuple.a.toFixed(2)); + + return tuple; + } + + #hsl(maybeAlpha) { + if (this.#lowerCased.startsWith("hsl(") && maybeAlpha === undefined) { + // We can use it as-is. + return this.#authored; + } + + const { r, g, b } = this.getRGBATuple(); + const [h, s, l] = rgbToHsl([r, g, b]); + if (maybeAlpha !== undefined) { + return "hsla(" + h + ", " + s + "%, " + l + "%, " + maybeAlpha + ")"; + } + return "hsl(" + h + ", " + s + "%, " + l + "%)"; + } + + #hwb(maybeAlpha) { + if (this.#lowerCased.startsWith("hwb(") && maybeAlpha === undefined) { + // We can use it as-is. + return this.#authored; + } + + const { r, g, b } = this.getRGBATuple(); + const [hue, white, black] = rgbToHwb([r, g, b]); + return `hwb(${hue} ${white}% ${black}%${ + maybeAlpha !== undefined ? " / " + maybeAlpha : "" + })`; + } + + /** + * This method allows comparison of CssColor objects using ===. + */ + valueOf() { + return this.rgba; + } + + /** + * Check whether the color is fully transparent (alpha === 0). + * + * @return {Boolean} True if the color is transparent and valid. + */ + isTransparent() { + return this.getRGBATuple().a === 0; + } +} + +/** + * Convert rgb value to hsl + * + * @param {array} rgb + * Array of rgb values + * @return {array} + * Array of hsl values. + */ +function rgbToHsl([r, g, b]) { + r = r / 255; + g = g / 255; + b = b / 255; + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let h; + let s; + const l = (max + min) / 2; + + if (max == min) { + h = s = 0; + } else { + const d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: + h = ((g - b) / d) % 6; + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h *= 60; + if (h < 0) { + h += 360; + } + } + + return [roundTo(h, 1), roundTo(s * 100, 1), roundTo(l * 100, 1)]; +} + +/** + * Convert RGB value to HWB + * + * @param {array} rgb + * Array of RGB values + * @return {array} + * Array of HWB values. + */ +function rgbToHwb([r, g, b]) { + const hsl = rgbToHsl([r, g, b]); + + r = r / 255; + g = g / 255; + b = b / 255; + + const white = Math.min(r, g, b); + const black = 1 - Math.max(r, g, b); + return [roundTo(hsl[0], 1), roundTo(white * 100, 1), roundTo(black * 100, 1)]; +} + +/** + * Convert rgb value to CIE LAB colorspace (https://en.wikipedia.org/wiki/CIELAB_color_space). + * Formula from http://www.easyrgb.com/en/math.php. + * + * @param {array} rgb + * Array of rgb values + * @return {array} + * Array of lab values. + */ +function rgbToLab([r, g, b]) { + // Convert rgb values to xyz coordinates. + r = r / 255; + g = g / 255; + b = b / 255; + + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + + r = r * 100; + g = g * 100; + b = b * 100; + + let [x, y, z] = [ + r * 0.4124 + g * 0.3576 + b * 0.1805, + r * 0.2126 + g * 0.7152 + b * 0.0722, + r * 0.0193 + g * 0.1192 + b * 0.9505, + ]; + + // Convert xyz coordinates to lab values. + // Divisors used are X_10, Y_10, Z_10 (CIE 1964) reference values for D65 + // illuminant (Daylight, sRGB, Adobe-RGB) taken from http://www.easyrgb.com/en/math.php + x = x / 94.811; + y = y / 100; + z = z / 107.304; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + + return [116 * y - 16, 500 * (x - y), 200 * (y - z)]; +} + +/** + * Calculates the CIE Delta-E value for two lab values (http://www.colorwiki.com/wiki/Delta_E%3a_The_Color_Difference#Delta-E_1976). + * Formula from http://www.easyrgb.com/en/math.php. + * + * @param {array} lab1 + * Array of lab values for the first color + * @param {array} lab2 + * Array of lab values for the second color + * @return {Number} + * DeltaE value between the two colors + */ +function calculateDeltaE([l1, a1, b1], [l2, a2, b2]) { + return Math.sqrt( + Math.pow(l1 - l2, 2) + Math.pow(a1 - a2, 2) + Math.pow(b1 - b2, 2) + ); +} + +function roundTo(number, digits) { + const multiplier = Math.pow(10, digits); + return Math.round(number * multiplier) / multiplier; +} + +/** + * Given a color, classify its type as one of the possible color + * units, as known by |CssColor.COLORUNIT|. + * + * @param {String} value + * The color, in any form accepted by CSS. + * @return {String} + * The color classification, one of "rgb", "hsl", "hwb", + * "hex", "name", or if no format is recognized, "authored". + */ +function classifyColor(value) { + value = value.toLowerCase(); + if (value.startsWith("rgb(") || value.startsWith("rgba(")) { + return CssColor.COLORUNIT.rgb; + } else if (value.startsWith("hsl(") || value.startsWith("hsla(")) { + return CssColor.COLORUNIT.hsl; + } else if (value.startsWith("hwb(")) { + return CssColor.COLORUNIT.hwb; + } else if (/^#[0-9a-f]+$/.exec(value)) { + return CssColor.COLORUNIT.hex; + } else if (/^[a-z\-]+$/.exec(value)) { + return CssColor.COLORUNIT.name; + } + return CssColor.COLORUNIT.authored; +} + +/** + * A helper function to convert a hex string like "F0C" or "F0C8" to a color. + * + * @param {String} name the color string + * @param {Boolean} highResolution Forces returned alpha value to be in the + * range 0 - 255 as opposed to 0.0 - 1.0. + * @return {Object} an object of the form {r, g, b, a}; or null if the + * name was not a valid color + */ +function hexToRGBA(name, highResolution) { + let r, + g, + b, + a = 1; + + if (name.length === 3) { + // short hex string (e.g. F0C) + r = parseInt(name.charAt(0) + name.charAt(0), 16); + g = parseInt(name.charAt(1) + name.charAt(1), 16); + b = parseInt(name.charAt(2) + name.charAt(2), 16); + } else if (name.length === 4) { + // short alpha hex string (e.g. F0CA) + r = parseInt(name.charAt(0) + name.charAt(0), 16); + g = parseInt(name.charAt(1) + name.charAt(1), 16); + b = parseInt(name.charAt(2) + name.charAt(2), 16); + a = parseInt(name.charAt(3) + name.charAt(3), 16); + + if (!highResolution) { + a /= 255; + } + } else if (name.length === 6) { + // hex string (e.g. FD01CD) + r = parseInt(name.charAt(0) + name.charAt(1), 16); + g = parseInt(name.charAt(2) + name.charAt(3), 16); + b = parseInt(name.charAt(4) + name.charAt(5), 16); + } else if (name.length === 8) { + // alpha hex string (e.g. FD01CDAB) + r = parseInt(name.charAt(0) + name.charAt(1), 16); + g = parseInt(name.charAt(2) + name.charAt(3), 16); + b = parseInt(name.charAt(4) + name.charAt(5), 16); + a = parseInt(name.charAt(6) + name.charAt(7), 16); + + if (!highResolution) { + a /= 255; + } + } else { + return null; + } + if (!highResolution) { + a = Math.round(a * 10) / 10; + } + return { r, g, b, a }; +} + +/** + * Calculates the luminance of a rgba tuple based on the formula given in + * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + * + * @param {Array} rgba An array with [r,g,b,a] values. + * @return {Number} The calculated luminance. + */ +function calculateLuminance(rgba) { + for (let i = 0; i < 3; i++) { + rgba[i] /= 255; + rgba[i] = + rgba[i] < 0.03928 + ? rgba[i] / 12.92 + : Math.pow((rgba[i] + 0.055) / 1.055, 2.4); + } + return 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]; +} + +/** + * Blend background and foreground colors takign alpha into account. + * @param {Array} foregroundColor + * An array with [r,g,b,a] values containing the foreground color. + * @param {Array} backgroundColor + * An array with [r,g,b,a] values containing the background color. Defaults to + * [ 255, 255, 255, 1 ]. + * @return {Array} + * An array with combined [r,g,b,a] colors. + */ +function blendColors(foregroundColor, backgroundColor = [255, 255, 255, 1]) { + const [fgR, fgG, fgB, fgA] = foregroundColor; + const [bgR, bgG, bgB, bgA] = backgroundColor; + if (fgA === 1) { + return foregroundColor; + } + + return [ + (1 - fgA) * bgR + fgA * fgR, + (1 - fgA) * bgG + fgA * fgG, + (1 - fgA) * bgB + fgA * fgB, + fgA + bgA * (1 - fgA), + ]; +} + +/** + * Calculates the contrast ratio of 2 rgba tuples based on the formula in + * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast7 + * + * @param {Array} backgroundColor An array with [r,g,b,a] values containing + * the background color. + * @param {Array} textColor An array with [r,g,b,a] values containing + * the text color. + * @return {Number} The calculated luminance. + */ +function calculateContrastRatio(backgroundColor, textColor) { + // Do not modify given colors. + backgroundColor = Array.from(backgroundColor); + textColor = Array.from(textColor); + + backgroundColor = blendColors(backgroundColor); + textColor = blendColors(textColor, backgroundColor); + + const backgroundLuminance = calculateLuminance(backgroundColor); + const textLuminance = calculateLuminance(textColor); + const ratio = (textLuminance + 0.05) / (backgroundLuminance + 0.05); + + return ratio > 1.0 ? ratio : 1 / ratio; +} + +function colorIsUppercase(color) { + // Specifically exclude the case where the color is + // case-insensitive. This makes it so that "#000" isn't + // considered "upper case" for the purposes of color cycling. + return color === color.toUpperCase() && color !== color.toLowerCase(); +} + +module.exports.colorUtils = { + CssColor, + rgbToHsl, + rgbToHwb, + rgbToLab, + classifyColor, + calculateContrastRatio, + calculateDeltaE, + calculateLuminance, + blendColors, + colorIsUppercase, +}; diff --git a/devtools/shared/css/constants.js b/devtools/shared/css/constants.js new file mode 100644 index 0000000000..cc8748c553 --- /dev/null +++ b/devtools/shared/css/constants.js @@ -0,0 +1,38 @@ +/* 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"; + +/** + * All CSS <angle> types that properties can support. + */ +exports.CSS_ANGLEUNIT = { + deg: "deg", + rad: "rad", + grad: "grad", + turn: "turn", +}; + +/** + * @backward-compat { version 70 } Mapping of InspectorPropertyType to old type ID. + */ +exports.CSS_TYPES = { + color: 2, + gradient: 4, + "timing-function": 10, +}; + +/** + * Supported pseudo-class locks in the order in which they appear in the pseudo-class + * panel in the Rules sidebar panel of the Inspector. + */ +exports.PSEUDO_CLASSES = [ + ":hover", + ":active", + ":focus", + ":focus-visible", + ":focus-within", + ":visited", + ":target", +]; diff --git a/devtools/shared/css/lexer.js b/devtools/shared/css/lexer.js new file mode 100644 index 0000000000..18e78717d1 --- /dev/null +++ b/devtools/shared/css/lexer.js @@ -0,0 +1,1522 @@ +/* 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/. */ + +// A CSS Lexer. This file is a bit unusual -- it is a more or less +// direct translation of layout/style/nsCSSScanner.cpp and +// layout/style/CSSLexer.cpp into JS. This implemented the +// CSSLexer.webidl interface, and the intent is to try to keep it in +// sync with changes to the platform CSS lexer. Due to this goal, +// this file violates some naming conventions and consequently locally +// disables some eslint rules. + +/* eslint-disable camelcase, mozilla/no-aArgs, no-else-return, complexity */ + +"use strict"; + +// White space of any kind. No value fields are used. Note that +// comments do *not* count as white space; comments separate tokens +// but are not themselves tokens. +const eCSSToken_Whitespace = "whitespace"; // +// A comment. +const eCSSToken_Comment = "comment"; // /*...*/ + +// Identifier-like tokens. mIdent is the text of the identifier. +// The difference between ID and Hash is: if the text after the # +// would have been a valid Ident if the # hadn't been there, the +// scanner produces an ID token. Otherwise it produces a Hash token. +// (This distinction is required by css3-selectors.) +const eCSSToken_Ident = "ident"; // word +const eCSSToken_Function = "function"; // word( +const eCSSToken_AtKeyword = "at"; // @word +const eCSSToken_ID = "id"; // #word +const eCSSToken_Hash = "hash"; // #0word + +// Numeric tokens. mNumber is the floating-point value of the +// number, and mHasSign indicates whether there was an explicit sign +// (+ or -) in front of the number. If mIntegerValid is true, the +// number had the lexical form of an integer, and mInteger is its +// integer value. Lexically integer values outside the range of a +// 32-bit signed number are clamped to the maximum values; mNumber +// will indicate a 'truer' value in that case. Percentage tokens +// are always considered not to be integers, even if their numeric +// value is integral (100% => mNumber = 1.0). For Dimension +// tokens, mIdent holds the text of the unit. +const eCSSToken_Number = "number"; // 1 -5 +2e3 3.14159 7.297352e-3 +const eCSSToken_Dimension = "dimension"; // 24px 8.5in +const eCSSToken_Percentage = "percentage"; // 85% 1280.4% + +// String-like tokens. In all cases, mIdent holds the text +// belonging to the string, and mSymbol holds the delimiter +// character, which may be ', ", or zero (only for unquoted URLs). +// Bad_String and Bad_URL tokens are emitted when the closing +// delimiter or parenthesis was missing. +const eCSSToken_String = "string"; // 'foo bar' "foo bar" +const eCSSToken_Bad_String = "bad_string"; // 'foo bar +const eCSSToken_URL = "url"; // url(foobar) url("foo bar") +const eCSSToken_Bad_URL = "bad_url"; // url(foo + +// Any one-character symbol. mSymbol holds the character. +const eCSSToken_Symbol = "symbol"; // . ; { } ! * + +// Match operators. These are single tokens rather than pairs of +// Symbol tokens because css3-selectors forbids the presence of +// comments between the two characters. No value fields are used; +// the token type indicates which operator. +const eCSSToken_Includes = "includes"; // ~= +const eCSSToken_Dashmatch = "dashmatch"; // |= +const eCSSToken_Beginsmatch = "beginsmatch"; // ^= +const eCSSToken_Endsmatch = "endsmatch"; // $= +const eCSSToken_Containsmatch = "containsmatch"; // *= + +// Unicode-range token: currently used only in @font-face. +// The lexical rule for this token includes several forms that are +// semantically invalid. Therefore, mIdent always holds the +// complete original text of the token (so we can print it +// accurately in diagnostics), and mIntegerValid is true iff the +// token is semantically valid. In that case, mInteger holds the +// lowest value included in the range, and mInteger2 holds the +// highest value included in the range. +const eCSSToken_URange = "urange"; // U+007e U+01?? U+2000-206F + +// HTML comment delimiters, ignored as a unit when they appear at +// the top level of a style sheet, for compatibility with websites +// written for compatibility with pre-CSS browsers. This token type +// subsumes the css2.1 CDO and CDC tokens, which are always treated +// the same by the parser. mIdent holds the text of the token, for +// diagnostics. +const eCSSToken_HTMLComment = "htmlcomment"; // <!-- --> + +const eEOFCharacters_None = 0x0000; + +// to handle \<EOF> inside strings +const eEOFCharacters_DropBackslash = 0x0001; + +// to handle \<EOF> outside strings +const eEOFCharacters_ReplacementChar = 0x0002; + +// to close comments +const eEOFCharacters_Asterisk = 0x0004; +const eEOFCharacters_Slash = 0x0008; + +// to close double-quoted strings +const eEOFCharacters_DoubleQuote = 0x0010; + +// to close single-quoted strings +const eEOFCharacters_SingleQuote = 0x0020; + +// to close URLs +const eEOFCharacters_CloseParen = 0x0040; + +// Bridge the char/string divide. +const APOSTROPHE = "'".charCodeAt(0); +const ASTERISK = "*".charCodeAt(0); +const CARRIAGE_RETURN = "\r".charCodeAt(0); +const CIRCUMFLEX_ACCENT = "^".charCodeAt(0); +const COMMERCIAL_AT = "@".charCodeAt(0); +const DIGIT_NINE = "9".charCodeAt(0); +const DIGIT_ZERO = "0".charCodeAt(0); +const DOLLAR_SIGN = "$".charCodeAt(0); +const EQUALS_SIGN = "=".charCodeAt(0); +const EXCLAMATION_MARK = "!".charCodeAt(0); +const FULL_STOP = ".".charCodeAt(0); +const GREATER_THAN_SIGN = ">".charCodeAt(0); +const HYPHEN_MINUS = "-".charCodeAt(0); +const LATIN_CAPITAL_LETTER_E = "E".charCodeAt(0); +const LATIN_CAPITAL_LETTER_U = "U".charCodeAt(0); +const LATIN_SMALL_LETTER_E = "e".charCodeAt(0); +const LATIN_SMALL_LETTER_U = "u".charCodeAt(0); +const LEFT_PARENTHESIS = "(".charCodeAt(0); +const LESS_THAN_SIGN = "<".charCodeAt(0); +const LINE_FEED = "\n".charCodeAt(0); +const NUMBER_SIGN = "#".charCodeAt(0); +const PERCENT_SIGN = "%".charCodeAt(0); +const PLUS_SIGN = "+".charCodeAt(0); +const QUESTION_MARK = "?".charCodeAt(0); +const QUOTATION_MARK = '"'.charCodeAt(0); +const REVERSE_SOLIDUS = "\\".charCodeAt(0); +const RIGHT_PARENTHESIS = ")".charCodeAt(0); +const SOLIDUS = "/".charCodeAt(0); +const TILDE = "~".charCodeAt(0); +const VERTICAL_LINE = "|".charCodeAt(0); + +const UCS2_REPLACEMENT_CHAR = 0xfffd; + +const kImpliedEOFCharacters = [ + UCS2_REPLACEMENT_CHAR, + ASTERISK, + SOLIDUS, + QUOTATION_MARK, + APOSTROPHE, + RIGHT_PARENTHESIS, + 0, +]; + +// +const ARGS_LENGTH_MAX = 500 * 1000; + +/** + * Several methods in this helper can reach the 500000 limit for arguments in + * Firefox, see Bug 1414361. + * + * This will apply the provided method, on the provided scope with an array of + * arguments which can exceed the 500k limit supported by Firefox. + * + * In practice, the arguments array will be split in several chunks of 500k + * items maximum and each chunk will be applied separately. + * + * !! Note that if you are expecting to use the return value of the method, here + * we will return an array of each return value for each chunk. It will be up to + * the consumer to decide how to combine the results into a meaningful final + * result !! + * + * @param {Function} method + * The method to apply. + * @param {*} scope + * The scope ("this") to use when applying the method. + * @param {Array} args + * The array of arguments to apply. + * + * @returns {Array} + * The array of return values, one item for each chunk that had to be + * created. + */ +function safeApply(method, scope, args) { + let i = 0; + const res = []; + const length = args.length; + while (i < length) { + const _start = i; + i += ARGS_LENGTH_MAX; + res.push(method.apply(scope, args.slice(_start, i))); + } + return res; +} + +/** + * Ensure that the character is valid. If it is valid, return it; + * otherwise, return the replacement character. + * + * @param {Number} c the character to check + * @return {Number} the character or its replacement + */ +function ensureValidChar(c) { + if (c >= 0x00110000 || (c & 0xfff800) == 0xd800) { + // Out of range or a surrogate. + return UCS2_REPLACEMENT_CHAR; + } + return c; +} + +/** + * Turn a string into an array of character codes. + * + * @param {String} str the input string + * @return {Array} an array of character codes, one per character in + * the input string. + */ +function stringToCodes(str) { + // This is a hot path, and using a simple for loop is faster than any other mean (e.g. + // Array#map ). + const charCodes = []; + for (let i = 0; i < str.length; i++) { + charCodes.push(str.charCodeAt(i)); + } + return charCodes; +} + +const IS_HEX_DIGIT = 0x01; +const IS_IDSTART = 0x02; +const IS_IDCHAR = 0x04; +const IS_URL_CHAR = 0x08; +const IS_HSPACE = 0x10; +const IS_VSPACE = 0x20; +const IS_SPACE = IS_HSPACE | IS_VSPACE; +const IS_STRING = 0x40; + +const H = IS_HSPACE; +const V = IS_VSPACE; +const I = IS_IDCHAR; +const J = IS_IDSTART; +const U = IS_URL_CHAR; +const S = IS_STRING; +const X = IS_HEX_DIGIT; + +const SH = S | H; +const SU = S | U; +const SUI = S | U | I; +const SUIJ = S | U | I | J; +const SUIX = S | U | I | X; +const SUIJX = S | U | I | J | X; + +/* eslint-disable indent, indent-legacy, no-multi-spaces, comma-spacing, spaced-comment */ +const gLexTable = [ + // 00 01 02 03 04 05 06 07 + 0, + S, + S, + S, + S, + S, + S, + S, + // 08 TAB LF 0B FF CR 0E 0F + S, + SH, + V, + S, + V, + V, + S, + S, + // 10 11 12 13 14 15 16 17 + S, + S, + S, + S, + S, + S, + S, + S, + // 18 19 1A 1B 1C 1D 1E 1F + S, + S, + S, + S, + S, + S, + S, + S, + //SPC ! " # $ % & ' + SH, + SU, + 0, + SU, + SU, + SU, + SU, + 0, + // ( ) * + , - . / + S, + S, + SU, + SU, + SU, + SUI, + SU, + SU, + // 0 1 2 3 4 5 6 7 + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + // 8 9 : ; < = > ? + SUIX, + SUIX, + SU, + SU, + SU, + SU, + SU, + SU, + // @ A B C D E F G + SU, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJ, + // H I J K L M N O + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // P Q R S T U V W + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // X Y Z [ \ ] ^ _ + SUIJ, + SUIJ, + SUIJ, + SU, + J, + SU, + SU, + SUIJ, + // ` a b c d e f g + SU, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJ, + // h i j k l m n o + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // p q r s t u v w + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // x y z { | } ~ 7F + SUIJ, + SUIJ, + SUIJ, + SU, + SU, + SU, + SU, + S, +]; +/* eslint-enable indent, indent-legacy, no-multi-spaces, comma-spacing, spaced-comment */ + +/** + * True if 'ch' is in character class 'cls', which should be one of + * the constants above or some combination of them. All characters + * above U+007F are considered to be in 'cls'. EOF is never in 'cls'. + */ +function IsOpenCharClass(ch, cls) { + return ch >= 0 && (ch >= 128 || (gLexTable[ch] & cls) != 0); +} + +/** + * True if 'ch' is in character class 'cls', which should be one of + * the constants above or some combination of them. No characters + * above U+007F are considered to be in 'cls'. EOF is never in 'cls'. + */ +function IsClosedCharClass(ch, cls) { + return ch >= 0 && ch < 128 && (gLexTable[ch] & cls) != 0; +} + +/** + * True if 'ch' is CSS whitespace, i.e. any of the ASCII characters + * TAB, LF, FF, CR, or SPC. + */ +function IsWhitespace(ch) { + return IsClosedCharClass(ch, IS_SPACE); +} + +/** + * True if 'ch' is horizontal whitespace, i.e. TAB or SPC. + */ +function IsHorzSpace(ch) { + return IsClosedCharClass(ch, IS_HSPACE); +} + +/** + * True if 'ch' is vertical whitespace, i.e. LF, FF, or CR. Vertical + * whitespace requires special handling when consumed, see AdvanceLine. + */ +function IsVertSpace(ch) { + return IsClosedCharClass(ch, IS_VSPACE); +} + +/** + * True if 'ch' is a character that can appear in the middle of an identifier. + * This includes U+0000 since it is handled as U+FFFD, but for purposes of + * GatherText it should not be included in IsOpenCharClass. + */ +function IsIdentChar(ch) { + return IsOpenCharClass(ch, IS_IDCHAR) || ch == 0; +} + +/** + * True if 'ch' is a character that by itself begins an identifier. + * This includes U+0000 since it is handled as U+FFFD, but for purposes of + * GatherText it should not be included in IsOpenCharClass. + * (This is a subset of IsIdentChar.) + */ +function IsIdentStart(ch) { + return IsOpenCharClass(ch, IS_IDSTART) || ch == 0; +} + +/** + * True if the two-character sequence aFirstChar+aSecondChar begins an + * identifier. + */ +function StartsIdent(aFirstChar, aSecondChar) { + return ( + IsIdentStart(aFirstChar) || + (aFirstChar == HYPHEN_MINUS && + (aSecondChar == HYPHEN_MINUS || IsIdentStart(aSecondChar))) + ); +} + +/** + * True if 'ch' is a decimal digit. + */ +function IsDigit(ch) { + return ch >= DIGIT_ZERO && ch <= DIGIT_NINE; +} + +/** + * True if 'ch' is a hexadecimal digit. + */ +function IsHexDigit(ch) { + return IsClosedCharClass(ch, IS_HEX_DIGIT); +} + +/** + * Assuming that 'ch' is a decimal digit, return its numeric value. + */ +function DecimalDigitValue(ch) { + return ch - DIGIT_ZERO; +} + +/** + * Assuming that 'ch' is a hexadecimal digit, return its numeric value. + */ +function HexDigitValue(ch) { + if (IsDigit(ch)) { + return DecimalDigitValue(ch); + } else { + // Note: c&7 just keeps the low three bits which causes + // upper and lower case alphabetics to both yield their + // "relative to 10" value for computing the hex value. + return (ch & 0x7) + 9; + } +} + +/** + * If 'ch' can be the first character of a two-character match operator + * token, return the token type code for that token, otherwise return + * eCSSToken_Symbol to indicate that it can't. + */ +function MatchOperatorType(ch) { + switch (ch) { + case TILDE: + return eCSSToken_Includes; + case VERTICAL_LINE: + return eCSSToken_Dashmatch; + case CIRCUMFLEX_ACCENT: + return eCSSToken_Beginsmatch; + case DOLLAR_SIGN: + return eCSSToken_Endsmatch; + case ASTERISK: + return eCSSToken_Containsmatch; + default: + return eCSSToken_Symbol; + } +} + +function Scanner(buffer) { + this.mBuffer = buffer || ""; + this.mOffset = 0; + this.mCount = this.mBuffer.length; + this.mLineNumber = 1; + this.mLineOffset = 0; + this.mTokenLineOffset = 0; + this.mTokenOffset = 0; + this.mTokenLineNumber = 1; + this.mEOFCharacters = eEOFCharacters_None; +} + +Scanner.prototype = { + /** + * The line number of the most recently returned token. Line + * numbers are 0-based. + */ + get lineNumber() { + return this.mTokenLineNumber - 1; + }, + + /** + * The column number of the most recently returned token. Column + * numbers are 0-based. + */ + get columnNumber() { + return this.mTokenOffset - this.mTokenLineOffset; + }, + + /** + * When EOF is reached, the last token might be unterminated in some + * ways. This method takes an input string and appends the needed + * terminators. In particular: + * + * 1. If EOF occurs mid-string, this will append the correct quote. + * 2. If EOF occurs in a url token, this will append the close paren. + * 3. If EOF occurs in a comment this will append the comment closer. + * + * A trailing backslash might also have been present in the input + * string. This is handled in different ways, depending on the + * context and arguments. + * + * If preserveBackslash is true, then the existing backslash at the + * end of inputString is preserved, and a new backslash is appended. + * That is, the input |\| is transformed to |\\|, and the + * input |'\| is transformed to |'\\'|. + * + * Otherwise, preserveBackslash is false: + * If the backslash appears in a string context, then the trailing + * backslash is dropped from inputString. That is, |"\| is + * transformed to |""|. + * If the backslash appears outside of a string context, then + * U+FFFD is appended. That is, |\| is transformed to a string + * with two characters: backslash followed by U+FFFD. + * + * Passing false for preserveBackslash makes the result conform to + * the CSS Syntax specification. However, passing true may give + * somewhat more intuitive behavior. + * + * @param inputString the input string + * @param preserveBackslash how to handle trailing backslashes + * @return the input string with the termination characters appended + */ + performEOFFixup(aInputString, aPreserveBackslash) { + let result = aInputString; + + let eofChars = this.mEOFCharacters; + + if ( + aPreserveBackslash && + (eofChars & + (eEOFCharacters_DropBackslash | eEOFCharacters_ReplacementChar)) != + 0 + ) { + eofChars &= ~( + eEOFCharacters_DropBackslash | eEOFCharacters_ReplacementChar + ); + result += "\\"; + } + + if ( + (eofChars & eEOFCharacters_DropBackslash) != 0 && + !!result.length && + result.endsWith("\\") + ) { + result = result.slice(0, -1); + } + + const extra = []; + this.AppendImpliedEOFCharacters(eofChars, extra); + const asString = String.fromCharCode.apply(null, extra); + + return result + asString; + }, + + /** + * Return the next token, or null at EOF. + * + * The token object is described by the following WebIDL definition: + * + * dictionary CSSToken { + * // The token type. + * CSSTokenType tokenType = "whitespace"; + * + * // Offset of the first character of the token. + * unsigned long startOffset = 0; + * // Offset of the character after the final character of the token. + * // This is chosen so that the offsets can be passed to |substring| + * // to yield the exact contents of the token. + * unsigned long endOffset = 0; + * + * // If the token is a number, percentage, or dimension, this holds + * // the value. This is not present for other token types. + * double number; + * // If the token is a number, percentage, or dimension, this is true + * // iff the number had an explicit sign. This is not present for + * // other token types. + * boolean hasSign; + * // If the token is a number, percentage, or dimension, this is true + * // iff the number was specified as an integer. This is not present + * // for other token types. + * boolean isInteger; + * + * // Text associated with the token. This is not present for all + * // token types. In particular it is: + * // + * // Token type Meaning + * // =============================== + * // ident The identifier. + * // function The function name. Note that the "(" is part + * // of the token but is not present in |text|. + * // at The word. + * // id The word. + * // hash The word. + * // dimension The dimension. + * // string The string contents after escape processing. + * // bad_string Ditto. + * // url The URL after escape processing. + * // bad_url Ditto. + * // symbol The symbol text. + * DOMString text; + * }; + */ + nextToken() { + const token = {}; + if (!this.Next(token)) { + return null; + } + + const resultToken = {}; + resultToken.tokenType = token.mType; + resultToken.startOffset = this.mTokenOffset; + resultToken.endOffset = this.mOffset; + const constructText = () => { + return safeApply(String.fromCharCode, null, token.mIdent).join(""); + }; + + switch (token.mType) { + case eCSSToken_Whitespace: + break; + + case eCSSToken_Ident: + case eCSSToken_Function: + case eCSSToken_AtKeyword: + case eCSSToken_ID: + case eCSSToken_Hash: + resultToken.text = constructText(); + break; + + case eCSSToken_Dimension: + resultToken.text = constructText(); + /* Fall through. */ + case eCSSToken_Number: + case eCSSToken_Percentage: + resultToken.number = token.mNumber; + resultToken.hasSign = token.mHasSign; + resultToken.isInteger = token.mIntegerValid; + break; + + case eCSSToken_String: + case eCSSToken_Bad_String: + case eCSSToken_URL: + case eCSSToken_Bad_URL: + resultToken.text = constructText(); + /* Don't bother emitting the delimiter, as it is readily extracted + from the source string when needed. */ + break; + + case eCSSToken_Symbol: + resultToken.text = String.fromCharCode(token.mSymbol); + break; + + case eCSSToken_Includes: + case eCSSToken_Dashmatch: + case eCSSToken_Beginsmatch: + case eCSSToken_Endsmatch: + case eCSSToken_Containsmatch: + case eCSSToken_URange: + break; + + case eCSSToken_Comment: + case eCSSToken_HTMLComment: + /* The comment text is easily extracted from the source string, + and is rarely useful. */ + break; + } + + return resultToken; + }, + + /** + * Return the raw UTF-16 code unit at position |this.mOffset + n| within + * the read buffer. If that is beyond the end of the buffer, returns + * -1 to indicate end of input. + */ + Peek(n = 0) { + if (this.mOffset + n >= this.mCount) { + return -1; + } + return this.mBuffer.charCodeAt(this.mOffset + n); + }, + + /** + * Advance |this.mOffset| over |n| code units. Advance(0) is a no-op. + * If |n| is greater than the distance to end of input, will silently + * stop at the end. May not be used to advance over a line boundary; + * AdvanceLine() must be used instead. + */ + Advance(n = 1) { + if (this.mOffset + n >= this.mCount || this.mOffset + n < this.mOffset) { + this.mOffset = this.mCount; + } else { + this.mOffset += n; + } + }, + + /** + * Advance |this.mOffset| over a line boundary. + */ + AdvanceLine() { + // Advance over \r\n as a unit. + if ( + this.mBuffer.charCodeAt(this.mOffset) == CARRIAGE_RETURN && + this.mOffset + 1 < this.mCount && + this.mBuffer.charCodeAt(this.mOffset + 1) == LINE_FEED + ) { + this.mOffset += 2; + } else { + this.mOffset += 1; + } + // 0 is a magical line number meaning that we don't know (i.e., script) + if (this.mLineNumber != 0) { + this.mLineNumber++; + } + this.mLineOffset = this.mOffset; + }, + + /** + * Skip over a sequence of whitespace characters (vertical or + * horizontal) starting at the current read position. + */ + SkipWhitespace() { + for (;;) { + const ch = this.Peek(); + if (!IsWhitespace(ch)) { + // EOF counts as non-whitespace + break; + } + if (IsVertSpace(ch)) { + this.AdvanceLine(); + } else { + this.Advance(); + } + } + }, + + /** + * Skip over one CSS comment starting at the current read position. + */ + SkipComment() { + this.Advance(2); + for (;;) { + let ch = this.Peek(); + if (ch < 0) { + this.SetEOFCharacters(eEOFCharacters_Asterisk | eEOFCharacters_Slash); + return; + } + if (ch == ASTERISK) { + this.Advance(); + ch = this.Peek(); + if (ch < 0) { + this.SetEOFCharacters(eEOFCharacters_Slash); + return; + } + if (ch == SOLIDUS) { + this.Advance(); + return; + } + } else if (IsVertSpace(ch)) { + this.AdvanceLine(); + } else { + this.Advance(); + } + } + }, + + /** + * If there is a valid escape sequence starting at the current read + * position, consume it, decode it, append the result to |aOutput|, + * and return true. Otherwise, consume nothing, leave |aOutput| + * unmodified, and return false. If |aInString| is true, accept the + * additional form of escape sequence allowed within string-like tokens. + */ + GatherEscape(aOutput, aInString) { + let ch = this.Peek(1); + if (ch < 0) { + // If we are in a string (or a url() containing a string), we want to drop + // the backslash on the floor. Otherwise, we want to treat it as a U+FFFD + // character. + this.Advance(); + if (aInString) { + this.SetEOFCharacters(eEOFCharacters_DropBackslash); + } else { + aOutput.push(UCS2_REPLACEMENT_CHAR); + this.SetEOFCharacters(eEOFCharacters_ReplacementChar); + } + return true; + } + if (IsVertSpace(ch)) { + if (aInString) { + // In strings (and in url() containing a string), escaped + // newlines are completely removed, to allow splitting over + // multiple lines. + this.Advance(); + this.AdvanceLine(); + return true; + } + // Outside of strings, backslash followed by a newline is not an escape. + return false; + } + + if (!IsHexDigit(ch)) { + // "Any character (except a hexadecimal digit, linefeed, carriage + // return, or form feed) can be escaped with a backslash to remove + // its special meaning." -- CSS2.1 section 4.1.3 + this.Advance(2); + if (ch == 0) { + aOutput.push(UCS2_REPLACEMENT_CHAR); + } else { + aOutput.push(ch); + } + return true; + } + + // "[at most six hexadecimal digits following a backslash] stand + // for the ISO 10646 character with that number, which must not be + // zero. (It is undefined in CSS 2.1 what happens if a style sheet + // does contain a character with Unicode codepoint zero.)" + // -- CSS2.1 section 4.1.3 + + // At this point we know we have \ followed by at least one + // hexadecimal digit, therefore the escape sequence is valid and we + // can go ahead and consume the backslash. + this.Advance(); + let val = 0; + let i = 0; + do { + val = val * 16 + HexDigitValue(ch); + i++; + this.Advance(); + ch = this.Peek(); + } while (i < 6 && IsHexDigit(ch)); + + // "Interpret the hex digits as a hexadecimal number. If this + // number is zero, or is greater than the maximum allowed + // codepoint, return U+FFFD REPLACEMENT CHARACTER" -- CSS Syntax + // Level 3 + if (val == 0) { + aOutput.push(UCS2_REPLACEMENT_CHAR); + } else { + aOutput.push(ensureValidChar(val)); + } + + // Consume exactly one whitespace character after a + // hexadecimal escape sequence. + if (IsVertSpace(ch)) { + this.AdvanceLine(); + } else if (IsHorzSpace(ch)) { + this.Advance(); + } + return true; + }, + + /** + * Consume a run of "text" beginning with the current read position, + * consisting of characters in the class |aClass| (which must be a + * suitable argument to IsOpenCharClass) plus escape sequences. + * Append the text to |aText|, after decoding escape sequences. + * + * Returns true if at least one character was appended to |aText|, + * false otherwise. + */ + GatherText(aClass, aText) { + const start = this.mOffset; + const inString = aClass == IS_STRING; + + for (;;) { + // Consume runs of unescaped characters in one go. + let n = this.mOffset; + while ( + n < this.mCount && + IsOpenCharClass(this.mBuffer.charCodeAt(n), aClass) + ) { + n++; + } + if (n > this.mOffset) { + const codes = stringToCodes(this.mBuffer.slice(this.mOffset, n)); + safeApply(Array.prototype.push, aText, codes); + this.mOffset = n; + } + if (n == this.mCount) { + break; + } + + const ch = this.Peek(); + if (ch == 0) { + this.Advance(); + aText.push(UCS2_REPLACEMENT_CHAR); + continue; + } + + if (ch != REVERSE_SOLIDUS) { + break; + } + if (!this.GatherEscape(aText, inString)) { + break; + } + } + + return this.mOffset > start; + }, + + /** + * Scan an Ident token. This also handles Function and URL tokens, + * both of which begin indistinguishably from an identifier. It can + * produce a Symbol token when an apparent identifier actually led + * into an invalid escape sequence. + */ + ScanIdent(aToken) { + if (!this.GatherText(IS_IDCHAR, aToken.mIdent)) { + aToken.mSymbol = this.Peek(); + this.Advance(); + return true; + } + + if (this.Peek() != LEFT_PARENTHESIS) { + aToken.mType = eCSSToken_Ident; + return true; + } + + this.Advance(); + aToken.mType = eCSSToken_Function; + + const asString = String.fromCharCode.apply(null, aToken.mIdent); + if (asString.toLowerCase() === "url") { + this.NextURL(aToken); + } + return true; + }, + + /** + * Scan an AtKeyword token. Also handles production of Symbol when + * an '@' is not followed by an identifier. + */ + ScanAtKeyword(aToken) { + // Fall back for when '@' isn't followed by an identifier. + aToken.mSymbol = COMMERCIAL_AT; + this.Advance(); + + const ch = this.Peek(); + if (StartsIdent(ch, this.Peek(1))) { + if (this.GatherText(IS_IDCHAR, aToken.mIdent)) { + aToken.mType = eCSSToken_AtKeyword; + } + } + return true; + }, + + /** + * Scan a Hash token. Handles the distinction between eCSSToken_ID + * and eCSSToken_Hash, and handles production of Symbol when a '#' + * is not followed by identifier characters. + */ + ScanHash(aToken) { + // Fall back for when '#' isn't followed by identifier characters. + aToken.mSymbol = NUMBER_SIGN; + this.Advance(); + + const ch = this.Peek(); + if (IsIdentChar(ch) || ch == REVERSE_SOLIDUS) { + const type = StartsIdent(ch, this.Peek(1)) + ? eCSSToken_ID + : eCSSToken_Hash; + aToken.mIdent.length = 0; + if (this.GatherText(IS_IDCHAR, aToken.mIdent)) { + aToken.mType = type; + } + } + + return true; + }, + + /** + * Scan a Number, Percentage, or Dimension token (all of which begin + * like a Number). Can produce a Symbol when a '.' is not followed by + * digits, or when '+' or '-' are not followed by either a digit or a + * '.' and then a digit. Can also produce a HTMLComment when it + * encounters '-->'. + */ + ScanNumber(aToken) { + let c = this.Peek(); + + // Sign of the mantissa (-1 or 1). + const sign = c == HYPHEN_MINUS ? -1 : 1; + // Absolute value of the integer part of the mantissa. This is a double so + // we don't run into overflow issues for consumers that only care about our + // floating-point value while still being able to express the full int32_t + // range for consumers who want integers. + let intPart = 0; + // Fractional part of the mantissa. This is a double so that when + // we convert to float at the end we'll end up rounding to nearest + // float instead of truncating down (as we would if fracPart were + // a float and we just effectively lost the last several digits). + let fracPart = 0; + // Absolute value of the power of 10 that we should multiply by + // (only relevant for numbers in scientific notation). Has to be + // a signed integer, because multiplication of signed by unsigned + // converts the unsigned to signed, so if we plan to actually + // multiply by expSign... + let exponent = 0; + // Sign of the exponent. + let expSign = 1; + + aToken.mHasSign = c == PLUS_SIGN || c == HYPHEN_MINUS; + if (aToken.mHasSign) { + this.Advance(); + c = this.Peek(); + } + + let gotDot = c == FULL_STOP; + + if (!gotDot) { + // Scan the integer part of the mantissa. + do { + intPart = 10 * intPart + DecimalDigitValue(c); + this.Advance(); + c = this.Peek(); + } while (IsDigit(c)); + + gotDot = c == FULL_STOP && IsDigit(this.Peek(1)); + } + + if (gotDot) { + // Scan the fractional part of the mantissa. + this.Advance(); + c = this.Peek(); + // Power of ten by which we need to divide our next digit + let divisor = 10; + do { + fracPart += DecimalDigitValue(c) / divisor; + divisor *= 10; + this.Advance(); + c = this.Peek(); + } while (IsDigit(c)); + } + + let gotE = false; + if (c == LATIN_SMALL_LETTER_E || c == LATIN_CAPITAL_LETTER_E) { + const expSignChar = this.Peek(1); + const nextChar = this.Peek(2); + if ( + IsDigit(expSignChar) || + ((expSignChar == HYPHEN_MINUS || expSignChar == PLUS_SIGN) && + IsDigit(nextChar)) + ) { + gotE = true; + if (expSignChar == HYPHEN_MINUS) { + expSign = -1; + } + this.Advance(); // consumes the E + if (expSignChar == HYPHEN_MINUS || expSignChar == PLUS_SIGN) { + this.Advance(); + c = nextChar; + } else { + c = expSignChar; + } + do { + exponent = 10 * exponent + DecimalDigitValue(c); + this.Advance(); + c = this.Peek(); + } while (IsDigit(c)); + } + } + + let type = eCSSToken_Number; + + // Set mIntegerValid for all cases (except %, below) because we need + // it for the "2n" in :nth-child(2n). + aToken.mIntegerValid = false; + + // Time to reassemble our number. + // Do all the math in double precision so it's truncated only once. + let value = sign * (intPart + fracPart); + if (gotE) { + // Explicitly cast expSign*exponent to double to avoid issues with + // overloaded pow() on Windows. + value *= Math.pow(10.0, expSign * exponent); + } else if (!gotDot) { + // Clamp values outside of integer range. + if (sign > 0) { + aToken.mInteger = Math.min(intPart, Number.MAX_SAFE_INTEGER); + } else { + aToken.mInteger = Math.max(-intPart, Number.MIN_SAFE_INTEGER); + } + aToken.mIntegerValid = true; + } + + const ident = aToken.mIdent; + + // Check for Dimension and Percentage tokens. + if (c >= 0) { + if (StartsIdent(c, this.Peek(1))) { + if (this.GatherText(IS_IDCHAR, ident)) { + type = eCSSToken_Dimension; + } + } else if (c == PERCENT_SIGN) { + this.Advance(); + type = eCSSToken_Percentage; + value = value / 100.0; + aToken.mIntegerValid = false; + } + } + aToken.mNumber = value; + aToken.mType = type; + return true; + }, + + /** + * Scan a string constant ('foo' or "foo"). Will always produce + * either a String or a Bad_String token; the latter occurs when the + * close quote is missing. Always returns true (for convenience in Next()). + */ + ScanString(aToken) { + const aStop = this.Peek(); + aToken.mType = eCSSToken_String; + aToken.mSymbol = aStop; // Remember how it's quoted. + this.Advance(); + + for (;;) { + this.GatherText(IS_STRING, aToken.mIdent); + + const ch = this.Peek(); + if (ch == -1) { + this.AddEOFCharacters( + aStop == QUOTATION_MARK + ? eEOFCharacters_DoubleQuote + : eEOFCharacters_SingleQuote + ); + break; // EOF ends a string token with no error. + } + if (ch == aStop) { + this.Advance(); + break; + } + // Both " and ' are excluded from IS_STRING. + if (ch == QUOTATION_MARK || ch == APOSTROPHE) { + aToken.mIdent.push(ch); + this.Advance(); + continue; + } + + aToken.mType = eCSSToken_Bad_String; + break; + } + return true; + }, + + /** + * Scan a unicode-range token. These match the regular expression + * + * u\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})? + * + * However, some such tokens are "invalid". There are three valid forms: + * + * u+[0-9a-f]{x} 1 <= x <= 6 + * u+[0-9a-f]{x}\?{y} 1 <= x+y <= 6 + * u+[0-9a-f]{x}-[0-9a-f]{y} 1 <= x <= 6, 1 <= y <= 6 + * + * All unicode-range tokens have their text recorded in mIdent; valid ones + * are also decoded into mInteger and mInteger2, and mIntegerValid is set. + * Note that this does not validate the numeric range, only the syntactic + * form. + */ + ScanURange(aResult) { + const intro1 = this.Peek(); + const intro2 = this.Peek(1); + let ch = this.Peek(2); + + aResult.mIdent.push(intro1); + aResult.mIdent.push(intro2); + this.Advance(2); + + let valid = true; + let haveQues = false; + let low = 0; + let high = 0; + let i = 0; + + do { + aResult.mIdent.push(ch); + if (IsHexDigit(ch)) { + if (haveQues) { + valid = false; // All question marks should be at the end. + } + low = low * 16 + HexDigitValue(ch); + high = high * 16 + HexDigitValue(ch); + } else { + haveQues = true; + low = low * 16 + 0x0; + high = high * 16 + 0xf; + } + + i++; + this.Advance(); + ch = this.Peek(); + } while (i < 6 && (IsHexDigit(ch) || ch == QUESTION_MARK)); + + if (ch == HYPHEN_MINUS && IsHexDigit(this.Peek(1))) { + if (haveQues) { + valid = false; + } + + aResult.mIdent.push(ch); + this.Advance(); + ch = this.Peek(); + high = 0; + i = 0; + do { + aResult.mIdent.push(ch); + high = high * 16 + HexDigitValue(ch); + + i++; + this.Advance(); + ch = this.Peek(); + } while (i < 6 && IsHexDigit(ch)); + } + + aResult.mInteger = low; + aResult.mInteger2 = high; + aResult.mIntegerValid = valid; + aResult.mType = eCSSToken_URange; + return true; + }, + + SetEOFCharacters(aEOFCharacters) { + this.mEOFCharacters = aEOFCharacters; + }, + + AddEOFCharacters(aEOFCharacters) { + this.mEOFCharacters = this.mEOFCharacters | aEOFCharacters; + }, + + AppendImpliedEOFCharacters(aEOFCharacters, aResult) { + // First, ignore eEOFCharacters_DropBackslash. + let c = aEOFCharacters >> 1; + + // All of the remaining EOFCharacters bits represent appended characters, + // and the bits are in the order that they need appending. + for (const p of kImpliedEOFCharacters) { + if (c & 1) { + aResult.push(p); + } + c >>= 1; + } + }, + + /** + * Consume the part of an URL token after the initial 'url('. Caller + * is assumed to have consumed 'url(' already. Will always produce + * either an URL or a Bad_URL token. + * + * Exposed for use by nsCSSParser::ParseMozDocumentRule, which applies + * the special lexical rules for URL tokens in a nonstandard context. + */ + NextURL(aToken) { + this.SkipWhitespace(); + + // aToken.mIdent may be "url" at this point; clear that out + aToken.mIdent.length = 0; + + let hasString = false; + let ch = this.Peek(); + // Do we have a string? + if (ch == QUOTATION_MARK || ch == APOSTROPHE) { + this.ScanString(aToken); + if (aToken.mType == eCSSToken_Bad_String) { + aToken.mType = eCSSToken_Bad_URL; + return; + } + hasString = true; + } else { + // Otherwise, this is the start of a non-quoted url (which may be empty). + aToken.mSymbol = 0; + this.GatherText(IS_URL_CHAR, aToken.mIdent); + } + + // Consume trailing whitespace and then look for a close parenthesis. + this.SkipWhitespace(); + ch = this.Peek(); + // ch can be less than zero indicating EOF + if (ch < 0 || ch == RIGHT_PARENTHESIS) { + this.Advance(); + aToken.mType = eCSSToken_URL; + if (ch < 0) { + this.AddEOFCharacters(eEOFCharacters_CloseParen); + } + } else { + aToken.mType = eCSSToken_Bad_URL; + if (!hasString) { + // Consume until before the next right parenthesis, which follows + // how <bad-url-token> is consumed in CSS Syntax 3 spec. + // Note that, we only do this when "url(" is not followed by a + // string, because in the spec, "url(" followed by a string is + // handled as a url function rather than a <url-token>, so the + // rest of content before ")" should be consumed in balance, + // which will be done by the parser. + // The closing ")" is not consumed here. It is left to the parser + // so that the parser can handle both cases. + do { + if (IsVertSpace(ch)) { + this.AdvanceLine(); + } else { + this.Advance(); + } + ch = this.Peek(); + } while (ch >= 0 && ch != RIGHT_PARENTHESIS); + } + } + }, + + /** + * Primary scanner entry point. Consume one token and fill in + * |aToken| accordingly. Will skip over any number of comments first, + * and will also skip over rather than return whitespace and comment + * tokens, depending on the value of |aSkip|. + * + * Returns true if it successfully consumed a token, false if EOF has + * been reached. Will always advance the current read position by at + * least one character unless called when already at EOF. + */ + Next(aToken, aSkip) { + // do this here so we don't have to do it in dozens of other places + aToken.mIdent = []; + aToken.mType = eCSSToken_Symbol; + + this.mTokenOffset = this.mOffset; + this.mTokenLineOffset = this.mLineOffset; + this.mTokenLineNumber = this.mLineNumber; + + const ch = this.Peek(); + if (IsWhitespace(ch)) { + this.SkipWhitespace(); + aToken.mType = eCSSToken_Whitespace; + return true; + } + if ( + ch == SOLIDUS && // !IsSVGMode() && + this.Peek(1) == ASTERISK + ) { + this.SkipComment(); + aToken.mType = eCSSToken_Comment; + return true; + } + + // EOF + if (ch < 0) { + return false; + } + + // 'u' could be UNICODE-RANGE or an identifier-family token + if (ch == LATIN_SMALL_LETTER_U || ch == LATIN_CAPITAL_LETTER_U) { + const c2 = this.Peek(1); + const c3 = this.Peek(2); + if (c2 == PLUS_SIGN && (IsHexDigit(c3) || c3 == QUESTION_MARK)) { + return this.ScanURange(aToken); + } + return this.ScanIdent(aToken); + } + + // identifier family + if (IsIdentStart(ch)) { + return this.ScanIdent(aToken); + } + + // number family + if (IsDigit(ch)) { + return this.ScanNumber(aToken); + } + + if (ch == FULL_STOP && IsDigit(this.Peek(1))) { + return this.ScanNumber(aToken); + } + + if (ch == PLUS_SIGN) { + const c2 = this.Peek(1); + if (IsDigit(c2) || (c2 == FULL_STOP && IsDigit(this.Peek(2)))) { + return this.ScanNumber(aToken); + } + } + + // HYPHEN_MINUS can start an identifier-family token, a number-family token, + // or an HTML-comment + if (ch == HYPHEN_MINUS) { + const c2 = this.Peek(1); + const c3 = this.Peek(2); + if (IsIdentStart(c2) || (c2 == HYPHEN_MINUS && c3 != GREATER_THAN_SIGN)) { + return this.ScanIdent(aToken); + } + if (IsDigit(c2) || (c2 == FULL_STOP && IsDigit(c3))) { + return this.ScanNumber(aToken); + } + if (c2 == HYPHEN_MINUS && c3 == GREATER_THAN_SIGN) { + this.Advance(3); + aToken.mType = eCSSToken_HTMLComment; + aToken.mIdent = stringToCodes("-->"); + return true; + } + } + + // the other HTML-comment token + if ( + ch == LESS_THAN_SIGN && + this.Peek(1) == EXCLAMATION_MARK && + this.Peek(2) == HYPHEN_MINUS && + this.Peek(3) == HYPHEN_MINUS + ) { + this.Advance(4); + aToken.mType = eCSSToken_HTMLComment; + aToken.mIdent = stringToCodes("<!--"); + return true; + } + + // AT_KEYWORD + if (ch == COMMERCIAL_AT) { + return this.ScanAtKeyword(aToken); + } + + // HASH + if (ch == NUMBER_SIGN) { + return this.ScanHash(aToken); + } + + // STRING + if (ch == QUOTATION_MARK || ch == APOSTROPHE) { + return this.ScanString(aToken); + } + + // Match operators: ~= |= ^= $= *= + const opType = MatchOperatorType(ch); + if (opType != eCSSToken_Symbol && this.Peek(1) == EQUALS_SIGN) { + aToken.mType = opType; + this.Advance(2); + return true; + } + + // Otherwise, a symbol (DELIM). + aToken.mSymbol = ch; + this.Advance(); + return true; + }, +}; + +/** + * Create and return a new CSS lexer. + * + * @param {String} input the CSS text to lex + * @return {CSSLexer} the new lexer + */ +function getCSSLexer(input) { + return new Scanner(input); +} + +exports.getCSSLexer = getCSSLexer; diff --git a/devtools/shared/css/moz.build b/devtools/shared/css/moz.build new file mode 100644 index 0000000000..97231df661 --- /dev/null +++ b/devtools/shared/css/moz.build @@ -0,0 +1,13 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +DevToolsModules( + "color-db.js", + "color.js", + "constants.js", + "lexer.js", + "parsing-utils.js", +) diff --git a/devtools/shared/css/parsing-utils.js b/devtools/shared/css/parsing-utils.js new file mode 100644 index 0000000000..6234eb3255 --- /dev/null +++ b/devtools/shared/css/parsing-utils.js @@ -0,0 +1,783 @@ +/* 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/. */ + +// This file holds various CSS parsing and rewriting utilities. +// Some entry points of note are: +// parseDeclarations - parse a CSS rule into declarations +// parsePseudoClassesAndAttributes - parse selector and extract +// pseudo-classes +// parseSingleValue - parse a single CSS property value + +"use strict"; + +const { getCSSLexer } = require("resource://devtools/shared/css/lexer.js"); + +loader.lazyRequireGetter( + this, + "CSS_ANGLEUNIT", + "resource://devtools/shared/css/constants.js", + true +); + +const SELECTOR_ATTRIBUTE = (exports.SELECTOR_ATTRIBUTE = 1); +const SELECTOR_ELEMENT = (exports.SELECTOR_ELEMENT = 2); +const SELECTOR_PSEUDO_CLASS = (exports.SELECTOR_PSEUDO_CLASS = 3); +const CSS_BLOCKS = { "(": ")", "[": "]" }; + +// When commenting out a declaration, we put this character into the +// comment opener so that future parses of the commented text know to +// bypass the property name validity heuristic. +const COMMENT_PARSING_HEURISTIC_BYPASS_CHAR = + (exports.COMMENT_PARSING_HEURISTIC_BYPASS_CHAR = "!"); + +/** + * A generator function that lexes a CSS source string, yielding the + * CSS tokens. Comment tokens are dropped. + * + * @param {String} CSS source string + * @yield {CSSToken} The next CSSToken that is lexed + * @see CSSToken for details about the returned tokens + */ +function* cssTokenizer(string) { + const lexer = getCSSLexer(string); + while (true) { + const token = lexer.nextToken(); + if (!token) { + break; + } + // None of the existing consumers want comments. + if (token.tokenType !== "comment") { + yield token; + } + } +} + +/** + * Pass |string| to the CSS lexer and return an array of all the + * returned tokens. Comment tokens are not included. In addition to + * the usual information, each token will have starting and ending + * line and column information attached. Specifically, each token + * has an additional "loc" attribute. This attribute is an object + * of the form {line: L, column: C}. Lines and columns are both zero + * based. + * + * It's best not to add new uses of this function. In general it is + * simpler and better to use the CSSToken offsets, rather than line + * and column. Also, this function lexes the entire input string at + * once, rather than lazily yielding a token stream. Use + * |cssTokenizer| or |getCSSLexer| instead. + * + * @param{String} string The input string. + * @return {Array} An array of tokens (@see CSSToken) that have + * line and column information. + */ +function cssTokenizerWithLineColumn(string) { + const lexer = getCSSLexer(string); + const result = []; + let prevToken = undefined; + while (true) { + const token = lexer.nextToken(); + const lineNumber = lexer.lineNumber; + const columnNumber = lexer.columnNumber; + + if (prevToken) { + prevToken.loc.end = { + line: lineNumber, + column: columnNumber, + }; + } + + if (!token) { + break; + } + + if (token.tokenType === "comment") { + // We've already dealt with the previous token's location. + prevToken = undefined; + } else { + const startLoc = { + line: lineNumber, + column: columnNumber, + }; + token.loc = { start: startLoc }; + + result.push(token); + prevToken = token; + } + } + + return result; +} + +/** + * Escape a comment body. Find the comment start and end strings in a + * string and inserts backslashes so that the resulting text can + * itself be put inside a comment. + * + * @param {String} inputString + * input string + * @return {String} the escaped result + */ +function escapeCSSComment(inputString) { + const result = inputString.replace(/\/(\\*)\*/g, "/\\$1*"); + return result.replace(/\*(\\*)\//g, "*\\$1/"); +} + +/** + * Un-escape a comment body. This undoes any comment escaping that + * was done by escapeCSSComment. That is, given input like "/\* + * comment *\/", it will strip the backslashes. + * + * @param {String} inputString + * input string + * @return {String} the un-escaped result + */ +function unescapeCSSComment(inputString) { + const result = inputString.replace(/\/\\(\\*)\*/g, "/$1*"); + return result.replace(/\*\\(\\*)\//g, "*$1/"); +} + +/** + * A helper function for @see parseDeclarations that handles parsing + * of comment text. This wraps a recursive call to parseDeclarations + * with the processing needed to ensure that offsets in the result + * refer back to the original, unescaped, input string. + * + * @param {Function} isCssPropertyKnown + * A function to check if the CSS property is known. This is either an + * internal server function or from the CssPropertiesFront. + * @param {String} commentText The text of the comment, without the + * delimiters. + * @param {Number} startOffset The offset of the comment opener + * in the original text. + * @param {Number} endOffset The offset of the comment closer + * in the original text. + * @return {array} Array of declarations of the same form as returned + * by parseDeclarations. + */ +function parseCommentDeclarations( + isCssPropertyKnown, + commentText, + startOffset, + endOffset +) { + let commentOverride = false; + if (commentText === "") { + return []; + } else if (commentText[0] === COMMENT_PARSING_HEURISTIC_BYPASS_CHAR) { + // This is the special sign that the comment was written by + // rewriteDeclarations and so we should bypass the usual + // heuristic. + commentOverride = true; + commentText = commentText.substring(1); + } + + const rewrittenText = unescapeCSSComment(commentText); + + // We might have rewritten an embedded comment. For example + // /\* ... *\/ would turn into /* ... */. + // This rewriting is necessary for proper lexing, but it means + // that the offsets we get back can be off. So now we compute + // a map so that we can rewrite offsets later. The map is the same + // length as |rewrittenText| and tells us how to map an index + // into |rewrittenText| to an index into |commentText|. + // + // First, we find the location of each comment starter or closer in + // |rewrittenText|. At these spots we put a 1 into |rewrites|. + // Then we walk the array again, using the elements to compute a + // delta, which we use to make the final mapping. + // + // Note we allocate one extra entry because we can see an ending + // offset that is equal to the length. + const rewrites = new Array(rewrittenText.length + 1).fill(0); + + const commentRe = /\/\\*\*|\*\\*\//g; + while (true) { + const matchData = commentRe.exec(rewrittenText); + if (!matchData) { + break; + } + rewrites[matchData.index] = 1; + } + + let delta = 0; + for (let i = 0; i <= rewrittenText.length; ++i) { + delta += rewrites[i]; + // |startOffset| to add the offset from the comment starter, |+2| + // for the length of the "/*", then |i| and |delta| as described + // above. + rewrites[i] = startOffset + 2 + i + delta; + if (commentOverride) { + ++rewrites[i]; + } + } + + // Note that we pass "false" for parseComments here. It doesn't + // seem worthwhile to support declarations in comments-in-comments + // here, as there's no way to generate those using the tools, and + // users would be crazy to write such things. + const newDecls = parseDeclarationsInternal( + isCssPropertyKnown, + rewrittenText, + false, + true, + commentOverride + ); + for (const decl of newDecls) { + decl.offsets[0] = rewrites[decl.offsets[0]]; + decl.offsets[1] = rewrites[decl.offsets[1]]; + decl.colonOffsets[0] = rewrites[decl.colonOffsets[0]]; + decl.colonOffsets[1] = rewrites[decl.colonOffsets[1]]; + decl.commentOffsets = [startOffset, endOffset]; + } + return newDecls; +} + +/** + * A helper function for parseDeclarationsInternal that creates a new + * empty declaration. + * + * @return {object} an empty declaration of the form returned by + * parseDeclarations + */ +function getEmptyDeclaration() { + return { + name: "", + value: "", + priority: "", + terminator: "", + offsets: [undefined, undefined], + colonOffsets: false, + }; +} + +/** + * Like trim, but only trims CSS-allowed whitespace. + */ +function cssTrim(str) { + const match = /^[ \t\r\n\f]*(.*?)[ \t\r\n\f]*$/.exec(str); + if (match) { + return match[1]; + } + return str; +} + +/** + * A helper function that does all the parsing work for + * parseDeclarations. This is separate because it has some arguments + * that don't make sense in isolation. + * + * The return value and arguments are like parseDeclarations, with + * these additional arguments. + * + * @param {Function} isCssPropertyKnown + * Function to check if the CSS property is known. + * @param {Boolean} inComment + * If true, assume that this call is parsing some text + * which came from a comment in another declaration. + * In this case some heuristics are used to avoid parsing + * text which isn't obviously a series of declarations. + * @param {Boolean} commentOverride + * This only makes sense when inComment=true. + * When true, assume that the comment was generated by + * rewriteDeclarations, and skip the usual name-checking + * heuristic. + */ +// eslint-disable-next-line complexity +function parseDeclarationsInternal( + isCssPropertyKnown, + inputString, + parseComments, + inComment, + commentOverride +) { + if (inputString === null || inputString === undefined) { + throw new Error("empty input string"); + } + + const lexer = getCSSLexer(inputString); + + let declarations = [getEmptyDeclaration()]; + let lastProp = declarations[0]; + + // This tracks the various CSS blocks the current token is in currently. + // This is a stack we push to when a block is opened, and we pop from when a block is + // closed. Within a block, colons and semicolons don't advance the way they do outside + // of blocks. + let currentBlocks = []; + + // This tracks the "!important" parsing state. The states are: + // 0 - haven't seen anything + // 1 - have seen "!", looking for "important" next (possibly after + // whitespace). + // 2 - have seen "!important" + let importantState = 0; + // This is true if we saw whitespace or comments between the "!" and + // the "important". + let importantWS = false; + + // This tracks the nesting parsing state + let isInNested = false; + let nestingLevel = 0; + + let current = ""; + + const resetStateForNextDeclaration = () => { + current = ""; + currentBlocks = []; + importantState = 0; + importantWS = false; + declarations.push(getEmptyDeclaration()); + lastProp = declarations.at(-1); + }; + + while (true) { + const token = lexer.nextToken(); + if (!token) { + break; + } + + // Update the start and end offsets of the declaration, but only + // when we see a significant token. + if (token.tokenType !== "whitespace" && token.tokenType !== "comment") { + if (lastProp.offsets[0] === undefined) { + lastProp.offsets[0] = token.startOffset; + } + lastProp.offsets[1] = token.endOffset; + } else if ( + lastProp.name && + !current && + !importantState && + !lastProp.priority && + lastProp.colonOffsets[1] + ) { + // Whitespace appearing after the ":" is attributed to it. + lastProp.colonOffsets[1] = token.endOffset; + } else if (importantState === 1) { + importantWS = true; + } + + if ( + // If we're not already in a nested rule + !isInNested && + token.tokenType === "symbol" && + // and there's an opening curly bracket + token.text == "{" && + // and we're not inside a function or an attribute + !currentBlocks.length + ) { + // Assume we're encountering a nested rule. + isInNested = true; + nestingLevel = 1; + + continue; + } else if (isInNested) { + if (token.tokenType === "symbol") { + if (token.text == "{") { + nestingLevel++; + } + if (token.text == "}") { + nestingLevel--; + } + } + + // If we were in a nested rule, and we saw the last closing curly bracket, + // reset the state to parse possible declarations declared after the nested rule. + if (nestingLevel === 0) { + isInNested = false; + // We need to remove the previous pending declaration and reset the state + declarations.pop(); + resetStateForNextDeclaration(); + } + continue; + } else if ( + token.tokenType === "symbol" && + CSS_BLOCKS[currentBlocks.at(-1)] === token.text + ) { + // Closing the last block that was opened. + currentBlocks.pop(); + current += token.text; + } else if (token.tokenType === "symbol" && CSS_BLOCKS[token.text]) { + // Opening a new block. + currentBlocks.push(token.text); + current += token.text; + } else if (token.tokenType === "function") { + // Opening a function is like opening a new block, so push one to the stack. + currentBlocks.push("("); + current += token.text + "("; + } else if (token.tokenType === "symbol" && token.text === ":") { + // Either way, a "!important" we've seen is no longer valid now. + importantState = 0; + importantWS = false; + if (!lastProp.name) { + // Set the current declaration name if there's no name yet + lastProp.name = cssTrim(current); + lastProp.colonOffsets = [token.startOffset, token.endOffset]; + current = ""; + currentBlocks = []; + + // When parsing a comment body, if the left-hand-side is not a + // valid property name, then drop it and stop parsing. + if ( + inComment && + !commentOverride && + !isCssPropertyKnown(lastProp.name) + ) { + lastProp.name = null; + break; + } + } else { + // Otherwise, just append ':' to the current value (declaration value + // with colons) + current += ":"; + } + } else if ( + token.tokenType === "symbol" && + token.text === ";" && + !currentBlocks.length + ) { + lastProp.terminator = ""; + // When parsing a comment, if the name hasn't been set, then we + // have probably just seen an ordinary semicolon used in text, + // so drop this and stop parsing. + if (inComment && !lastProp.name) { + current = ""; + currentBlocks = []; + break; + } + if (importantState === 2) { + lastProp.priority = "important"; + } else if (importantState === 1) { + current += "!"; + if (importantWS) { + current += " "; + } + } + lastProp.value = cssTrim(current); + resetStateForNextDeclaration(); + } else if (token.tokenType === "ident") { + if (token.text === "important" && importantState === 1) { + importantState = 2; + } else { + if (importantState > 0) { + current += "!"; + if (importantWS) { + current += " "; + } + if (importantState === 2) { + current += "important "; + } + importantState = 0; + importantWS = false; + } + // Re-escape the token to avoid dequoting problems. + // See bug 1287620. + current += CSS.escape(token.text); + } + } else if (token.tokenType === "symbol" && token.text === "!") { + importantState = 1; + } else if (token.tokenType === "whitespace") { + if (current !== "") { + current = current.trimEnd() + " "; + } + } else if (token.tokenType === "comment") { + if (parseComments && !lastProp.name && !lastProp.value) { + const commentText = inputString.substring( + token.startOffset + 2, + token.endOffset - 2 + ); + const newDecls = parseCommentDeclarations( + isCssPropertyKnown, + commentText, + token.startOffset, + token.endOffset + ); + + // Insert the new declarations just before the final element. + const lastDecl = declarations.pop(); + declarations = [...declarations, ...newDecls, lastDecl]; + } else { + current = current.trimEnd() + " "; + } + } else { + if (importantState > 0) { + current += "!"; + if (importantWS) { + current += " "; + } + if (importantState === 2) { + current += "important "; + } + importantState = 0; + importantWS = false; + } + current += inputString.substring(token.startOffset, token.endOffset); + } + } + + // Handle whatever trailing properties or values might still be there + if (current) { + // If nested rule doesn't have closing bracket + if (isInNested && nestingLevel > 0) { + // We need to remove the previous (nested) pending declaration + declarations.pop(); + } else if (!lastProp.name) { + // Ignore this case in comments. + if (!inComment) { + // Trailing property found, e.g. p1:v1;p2:v2;p3 + lastProp.name = cssTrim(current); + } + } else { + // Trailing value found, i.e. value without an ending ; + if (importantState === 2) { + lastProp.priority = "important"; + } else if (importantState === 1) { + current += "!"; + } + lastProp.value = cssTrim(current); + const terminator = lexer.performEOFFixup("", true); + lastProp.terminator = terminator + ";"; + // If the input was unterminated, attribute the remainder to + // this property. This avoids some bad behavior when rewriting + // an unterminated comment. + if (terminator) { + lastProp.offsets[1] = inputString.length; + } + } + } + + // Remove declarations that have neither a name nor a value + declarations = declarations.filter(prop => prop.name || prop.value); + + return declarations; +} + +/** + * Returns an array of CSS declarations given a string. + * For example, parseDeclarations(isCssPropertyKnown, "width: 1px; height: 1px") + * would return: + * [{name:"width", value: "1px"}, {name: "height", "value": "1px"}] + * + * The input string is assumed to only contain declarations so { and } + * characters will be treated as part of either the property or value, + * depending where it's found. + * + * @param {Function} isCssPropertyKnown + * A function to check if the CSS property is known. This is either an + * internal server function or from the CssPropertiesFront. + * that are supported by the server. + * @param {String} inputString + * An input string of CSS + * @param {Boolean} parseComments + * If true, try to parse the contents of comments as well. + * A comment will only be parsed if it occurs outside of + * the body of some other declaration. + * @return {Array} an array of objects with the following signature: + * [{"name": string, "value": string, "priority": string, + * "terminator": string, + * "offsets": [start, end], "colonOffsets": [start, end]}, + * ...] + * Here, "offsets" holds the offsets of the start and end + * of the declaration text, in a form suitable for use with + * String.substring. + * "terminator" is a string to use to terminate the declaration, + * usually "" to mean no additional termination is needed. + * "colonOffsets" holds the start and end locations of the + * ":" that separates the property name from the value. + * If the declaration appears in a comment, then there will + * be an additional {"commentOffsets": [start, end] property + * on the object, which will hold the offsets of the start + * and end of the enclosing comment. + */ +function parseDeclarations( + isCssPropertyKnown, + inputString, + parseComments = false +) { + return parseDeclarationsInternal( + isCssPropertyKnown, + inputString, + parseComments, + false, + false + ); +} + +/** + * Like @see parseDeclarations, but removes properties that do not + * have a name. + */ +function parseNamedDeclarations( + isCssPropertyKnown, + inputString, + parseComments = false +) { + return parseDeclarations( + isCssPropertyKnown, + inputString, + parseComments + ).filter(item => !!item.name); +} + +/** + * Returns an array of the parsed CSS selector value and type given a string. + * + * The components making up the CSS selector can be extracted into 3 different + * types: element, attribute and pseudoclass. The object that is appended to + * the returned array contains the value related to one of the 3 types described + * along with the actual type. + * + * The following are the 3 types that can be returned in the object signature: + * (1) SELECTOR_ATTRIBUTE + * (2) SELECTOR_ELEMENT + * (3) SELECTOR_PSEUDO_CLASS + * + * @param {String} value + * The CSS selector text. + * @return {Array} an array of objects with the following signature: + * [{ "value": string, "type": integer }, ...] + */ +// eslint-disable-next-line complexity +function parsePseudoClassesAndAttributes(value) { + if (!value) { + throw new Error("empty input string"); + } + + const tokens = cssTokenizer(value); + const result = []; + let current = ""; + let functionCount = 0; + let hasAttribute = false; + let hasColon = false; + + for (const token of tokens) { + if (token.tokenType === "ident") { + current += value.substring(token.startOffset, token.endOffset); + + if (hasColon && !functionCount) { + if (current) { + result.push({ value: current, type: SELECTOR_PSEUDO_CLASS }); + } + + current = ""; + hasColon = false; + } + } else if (token.tokenType === "symbol" && token.text === ":") { + if (!hasColon) { + if (current) { + result.push({ value: current, type: SELECTOR_ELEMENT }); + } + + current = ""; + hasColon = true; + } + + current += token.text; + } else if (token.tokenType === "function") { + current += value.substring(token.startOffset, token.endOffset); + functionCount++; + } else if (token.tokenType === "symbol" && token.text === ")") { + current += token.text; + + if (hasColon && functionCount == 1) { + if (current) { + result.push({ value: current, type: SELECTOR_PSEUDO_CLASS }); + } + + current = ""; + functionCount--; + hasColon = false; + } else { + functionCount--; + } + } else if (token.tokenType === "symbol" && token.text === "[") { + if (!hasAttribute && !functionCount) { + if (current) { + result.push({ value: current, type: SELECTOR_ELEMENT }); + } + + current = ""; + hasAttribute = true; + } + + current += token.text; + } else if (token.tokenType === "symbol" && token.text === "]") { + current += token.text; + + if (hasAttribute && !functionCount) { + if (current) { + result.push({ value: current, type: SELECTOR_ATTRIBUTE }); + } + + current = ""; + hasAttribute = false; + } + } else { + current += value.substring(token.startOffset, token.endOffset); + } + } + + if (current) { + result.push({ value: current, type: SELECTOR_ELEMENT }); + } + + return result; +} + +/** + * Expects a single CSS value to be passed as the input and parses the value + * and priority. + * + * @param {Function} isCssPropertyKnown + * A function to check if the CSS property is known. This is either an + * internal server function or from the CssPropertiesFront. + * that are supported by the server. + * @param {String} value + * The value from the text editor. + * @return {Object} an object with 'value' and 'priority' properties. + */ +function parseSingleValue(isCssPropertyKnown, value) { + const declaration = parseDeclarations( + isCssPropertyKnown, + "a: " + value + ";" + )[0]; + return { + value: declaration ? declaration.value : "", + priority: declaration ? declaration.priority : "", + }; +} + +/** + * Convert an angle value to degree. + * + * @param {Number} angleValue The angle value. + * @param {CSS_ANGLEUNIT} angleUnit The angleValue's angle unit. + * @return {Number} An angle value in degree. + */ +function getAngleValueInDegrees(angleValue, angleUnit) { + switch (angleUnit) { + case CSS_ANGLEUNIT.deg: + return angleValue; + case CSS_ANGLEUNIT.grad: + return angleValue * 0.9; + case CSS_ANGLEUNIT.rad: + return (angleValue * 180) / Math.PI; + case CSS_ANGLEUNIT.turn: + return angleValue * 360; + default: + throw new Error("No matched angle unit."); + } +} + +exports.cssTokenizer = cssTokenizer; +exports.cssTokenizerWithLineColumn = cssTokenizerWithLineColumn; +exports.escapeCSSComment = escapeCSSComment; +exports.unescapeCSSComment = unescapeCSSComment; +exports.parseDeclarations = parseDeclarations; +exports.parseNamedDeclarations = parseNamedDeclarations; +// parseCommentDeclarations is exported for testing. +exports._parseCommentDeclarations = parseCommentDeclarations; +exports.parsePseudoClassesAndAttributes = parsePseudoClassesAndAttributes; +exports.parseSingleValue = parseSingleValue; +exports.getAngleValueInDegrees = getAngleValueInDegrees; |