You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10858 lines
358 KiB

1 year ago
  1. /*!
  2. CSSLint v1.0.4
  3. Copyright (c) 2016 Nicole Sullivan and Nicholas C. Zakas. All rights reserved.
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the 'Software'), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. var CSSLint = (function(){
  21. var module = module || {},
  22. exports = exports || {};
  23. /*!
  24. Parser-Lib
  25. Copyright (c) 2009-2016 Nicholas C. Zakas. All rights reserved.
  26. Permission is hereby granted, free of charge, to any person obtaining a copy
  27. of this software and associated documentation files (the "Software"), to deal
  28. in the Software without restriction, including without limitation the rights
  29. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  30. copies of the Software, and to permit persons to whom the Software is
  31. furnished to do so, subject to the following conditions:
  32. The above copyright notice and this permission notice shall be included in
  33. all copies or substantial portions of the Software.
  34. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  35. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  36. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  39. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40. THE SOFTWARE.
  41. */
  42. /* Version v1.1.0, Build time: 6-December-2016 10:31:29 */
  43. var parserlib = (function () {
  44. var require;
  45. require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  46. "use strict";
  47. /* exported Colors */
  48. var Colors = module.exports = {
  49. __proto__ :null,
  50. aliceblue :"#f0f8ff",
  51. antiquewhite :"#faebd7",
  52. aqua :"#00ffff",
  53. aquamarine :"#7fffd4",
  54. azure :"#f0ffff",
  55. beige :"#f5f5dc",
  56. bisque :"#ffe4c4",
  57. black :"#000000",
  58. blanchedalmond :"#ffebcd",
  59. blue :"#0000ff",
  60. blueviolet :"#8a2be2",
  61. brown :"#a52a2a",
  62. burlywood :"#deb887",
  63. cadetblue :"#5f9ea0",
  64. chartreuse :"#7fff00",
  65. chocolate :"#d2691e",
  66. coral :"#ff7f50",
  67. cornflowerblue :"#6495ed",
  68. cornsilk :"#fff8dc",
  69. crimson :"#dc143c",
  70. cyan :"#00ffff",
  71. darkblue :"#00008b",
  72. darkcyan :"#008b8b",
  73. darkgoldenrod :"#b8860b",
  74. darkgray :"#a9a9a9",
  75. darkgrey :"#a9a9a9",
  76. darkgreen :"#006400",
  77. darkkhaki :"#bdb76b",
  78. darkmagenta :"#8b008b",
  79. darkolivegreen :"#556b2f",
  80. darkorange :"#ff8c00",
  81. darkorchid :"#9932cc",
  82. darkred :"#8b0000",
  83. darksalmon :"#e9967a",
  84. darkseagreen :"#8fbc8f",
  85. darkslateblue :"#483d8b",
  86. darkslategray :"#2f4f4f",
  87. darkslategrey :"#2f4f4f",
  88. darkturquoise :"#00ced1",
  89. darkviolet :"#9400d3",
  90. deeppink :"#ff1493",
  91. deepskyblue :"#00bfff",
  92. dimgray :"#696969",
  93. dimgrey :"#696969",
  94. dodgerblue :"#1e90ff",
  95. firebrick :"#b22222",
  96. floralwhite :"#fffaf0",
  97. forestgreen :"#228b22",
  98. fuchsia :"#ff00ff",
  99. gainsboro :"#dcdcdc",
  100. ghostwhite :"#f8f8ff",
  101. gold :"#ffd700",
  102. goldenrod :"#daa520",
  103. gray :"#808080",
  104. grey :"#808080",
  105. green :"#008000",
  106. greenyellow :"#adff2f",
  107. honeydew :"#f0fff0",
  108. hotpink :"#ff69b4",
  109. indianred :"#cd5c5c",
  110. indigo :"#4b0082",
  111. ivory :"#fffff0",
  112. khaki :"#f0e68c",
  113. lavender :"#e6e6fa",
  114. lavenderblush :"#fff0f5",
  115. lawngreen :"#7cfc00",
  116. lemonchiffon :"#fffacd",
  117. lightblue :"#add8e6",
  118. lightcoral :"#f08080",
  119. lightcyan :"#e0ffff",
  120. lightgoldenrodyellow :"#fafad2",
  121. lightgray :"#d3d3d3",
  122. lightgrey :"#d3d3d3",
  123. lightgreen :"#90ee90",
  124. lightpink :"#ffb6c1",
  125. lightsalmon :"#ffa07a",
  126. lightseagreen :"#20b2aa",
  127. lightskyblue :"#87cefa",
  128. lightslategray :"#778899",
  129. lightslategrey :"#778899",
  130. lightsteelblue :"#b0c4de",
  131. lightyellow :"#ffffe0",
  132. lime :"#00ff00",
  133. limegreen :"#32cd32",
  134. linen :"#faf0e6",
  135. magenta :"#ff00ff",
  136. maroon :"#800000",
  137. mediumaquamarine:"#66cdaa",
  138. mediumblue :"#0000cd",
  139. mediumorchid :"#ba55d3",
  140. mediumpurple :"#9370d8",
  141. mediumseagreen :"#3cb371",
  142. mediumslateblue :"#7b68ee",
  143. mediumspringgreen :"#00fa9a",
  144. mediumturquoise :"#48d1cc",
  145. mediumvioletred :"#c71585",
  146. midnightblue :"#191970",
  147. mintcream :"#f5fffa",
  148. mistyrose :"#ffe4e1",
  149. moccasin :"#ffe4b5",
  150. navajowhite :"#ffdead",
  151. navy :"#000080",
  152. oldlace :"#fdf5e6",
  153. olive :"#808000",
  154. olivedrab :"#6b8e23",
  155. orange :"#ffa500",
  156. orangered :"#ff4500",
  157. orchid :"#da70d6",
  158. palegoldenrod :"#eee8aa",
  159. palegreen :"#98fb98",
  160. paleturquoise :"#afeeee",
  161. palevioletred :"#d87093",
  162. papayawhip :"#ffefd5",
  163. peachpuff :"#ffdab9",
  164. peru :"#cd853f",
  165. pink :"#ffc0cb",
  166. plum :"#dda0dd",
  167. powderblue :"#b0e0e6",
  168. purple :"#800080",
  169. red :"#ff0000",
  170. rosybrown :"#bc8f8f",
  171. royalblue :"#4169e1",
  172. saddlebrown :"#8b4513",
  173. salmon :"#fa8072",
  174. sandybrown :"#f4a460",
  175. seagreen :"#2e8b57",
  176. seashell :"#fff5ee",
  177. sienna :"#a0522d",
  178. silver :"#c0c0c0",
  179. skyblue :"#87ceeb",
  180. slateblue :"#6a5acd",
  181. slategray :"#708090",
  182. slategrey :"#708090",
  183. snow :"#fffafa",
  184. springgreen :"#00ff7f",
  185. steelblue :"#4682b4",
  186. tan :"#d2b48c",
  187. teal :"#008080",
  188. thistle :"#d8bfd8",
  189. tomato :"#ff6347",
  190. turquoise :"#40e0d0",
  191. violet :"#ee82ee",
  192. wheat :"#f5deb3",
  193. white :"#ffffff",
  194. whitesmoke :"#f5f5f5",
  195. yellow :"#ffff00",
  196. yellowgreen :"#9acd32",
  197. //'currentColor' color keyword https://www.w3.org/TR/css3-color/#currentcolor
  198. currentColor :"The value of the 'color' property.",
  199. //CSS2 system colors https://www.w3.org/TR/css3-color/#css2-system
  200. activeBorder :"Active window border.",
  201. activecaption :"Active window caption.",
  202. appworkspace :"Background color of multiple document interface.",
  203. background :"Desktop background.",
  204. buttonface :"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.",
  205. buttonhighlight :"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",
  206. buttonshadow :"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",
  207. buttontext :"Text on push buttons.",
  208. captiontext :"Text in caption, size box, and scrollbar arrow box.",
  209. graytext :"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.",
  210. greytext :"Greyed (disabled) text. This color is set to #000 if the current display driver does not support a solid grey color.",
  211. highlight :"Item(s) selected in a control.",
  212. highlighttext :"Text of item(s) selected in a control.",
  213. inactiveborder :"Inactive window border.",
  214. inactivecaption :"Inactive window caption.",
  215. inactivecaptiontext :"Color of text in an inactive caption.",
  216. infobackground :"Background color for tooltip controls.",
  217. infotext :"Text color for tooltip controls.",
  218. menu :"Menu background.",
  219. menutext :"Text in menus.",
  220. scrollbar :"Scroll bar gray area.",
  221. threeddarkshadow :"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
  222. threedface :"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
  223. threedhighlight :"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
  224. threedlightshadow :"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
  225. threedshadow :"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
  226. window :"Window background.",
  227. windowframe :"Window frame.",
  228. windowtext :"Text in windows."
  229. };
  230. },{}],2:[function(require,module,exports){
  231. "use strict";
  232. module.exports = Combinator;
  233. var SyntaxUnit = require("../util/SyntaxUnit");
  234. var Parser = require("./Parser");
  235. /**
  236. * Represents a selector combinator (whitespace, +, >).
  237. * @namespace parserlib.css
  238. * @class Combinator
  239. * @extends parserlib.util.SyntaxUnit
  240. * @constructor
  241. * @param {String} text The text representation of the unit.
  242. * @param {int} line The line of text on which the unit resides.
  243. * @param {int} col The column of text on which the unit resides.
  244. */
  245. function Combinator(text, line, col) {
  246. SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE);
  247. /**
  248. * The type of modifier.
  249. * @type String
  250. * @property type
  251. */
  252. this.type = "unknown";
  253. //pretty simple
  254. if (/^\s+$/.test(text)) {
  255. this.type = "descendant";
  256. } else if (text === ">") {
  257. this.type = "child";
  258. } else if (text === "+") {
  259. this.type = "adjacent-sibling";
  260. } else if (text === "~") {
  261. this.type = "sibling";
  262. }
  263. }
  264. Combinator.prototype = new SyntaxUnit();
  265. Combinator.prototype.constructor = Combinator;
  266. },{"../util/SyntaxUnit":26,"./Parser":6}],3:[function(require,module,exports){
  267. "use strict";
  268. module.exports = Matcher;
  269. var StringReader = require("../util/StringReader");
  270. var SyntaxError = require("../util/SyntaxError");
  271. /**
  272. * This class implements a combinator library for matcher functions.
  273. * The combinators are described at:
  274. * https://developer.mozilla.org/en-US/docs/Web/CSS/Value_definition_syntax#Component_value_combinators
  275. */
  276. function Matcher(matchFunc, toString) {
  277. this.match = function(expression) {
  278. // Save/restore marks to ensure that failed matches always restore
  279. // the original location in the expression.
  280. var result;
  281. expression.mark();
  282. result = matchFunc(expression);
  283. if (result) {
  284. expression.drop();
  285. } else {
  286. expression.restore();
  287. }
  288. return result;
  289. };
  290. this.toString = typeof toString === "function" ? toString : function() {
  291. return toString;
  292. };
  293. }
  294. /** Precedence table of combinators. */
  295. Matcher.prec = {
  296. MOD: 5,
  297. SEQ: 4,
  298. ANDAND: 3,
  299. OROR: 2,
  300. ALT: 1
  301. };
  302. /** Simple recursive-descent grammar to build matchers from strings. */
  303. Matcher.parse = function(str) {
  304. var reader, eat, expr, oror, andand, seq, mod, term, result;
  305. reader = new StringReader(str);
  306. eat = function(matcher) {
  307. var result = reader.readMatch(matcher);
  308. if (result === null) {
  309. throw new SyntaxError(
  310. "Expected "+matcher, reader.getLine(), reader.getCol());
  311. }
  312. return result;
  313. };
  314. expr = function() {
  315. // expr = oror (" | " oror)*
  316. var m = [ oror() ];
  317. while (reader.readMatch(" | ") !== null) {
  318. m.push(oror());
  319. }
  320. return m.length === 1 ? m[0] : Matcher.alt.apply(Matcher, m);
  321. };
  322. oror = function() {
  323. // oror = andand ( " || " andand)*
  324. var m = [ andand() ];
  325. while (reader.readMatch(" || ") !== null) {
  326. m.push(andand());
  327. }
  328. return m.length === 1 ? m[0] : Matcher.oror.apply(Matcher, m);
  329. };
  330. andand = function() {
  331. // andand = seq ( " && " seq)*
  332. var m = [ seq() ];
  333. while (reader.readMatch(" && ") !== null) {
  334. m.push(seq());
  335. }
  336. return m.length === 1 ? m[0] : Matcher.andand.apply(Matcher, m);
  337. };
  338. seq = function() {
  339. // seq = mod ( " " mod)*
  340. var m = [ mod() ];
  341. while (reader.readMatch(/^ (?![&|\]])/) !== null) {
  342. m.push(mod());
  343. }
  344. return m.length === 1 ? m[0] : Matcher.seq.apply(Matcher, m);
  345. };
  346. mod = function() {
  347. // mod = term ( "?" | "*" | "+" | "#" | "{<num>,<num>}" )?
  348. var m = term();
  349. if (reader.readMatch("?") !== null) {
  350. return m.question();
  351. } else if (reader.readMatch("*") !== null) {
  352. return m.star();
  353. } else if (reader.readMatch("+") !== null) {
  354. return m.plus();
  355. } else if (reader.readMatch("#") !== null) {
  356. return m.hash();
  357. } else if (reader.readMatch(/^\{\s*/) !== null) {
  358. var min = eat(/^\d+/);
  359. eat(/^\s*,\s*/);
  360. var max = eat(/^\d+/);
  361. eat(/^\s*\}/);
  362. return m.braces(+min, +max);
  363. }
  364. return m;
  365. };
  366. term = function() {
  367. // term = <nt> | literal | "[ " expression " ]"
  368. if (reader.readMatch("[ ") !== null) {
  369. var m = expr();
  370. eat(" ]");
  371. return m;
  372. }
  373. return Matcher.fromType(eat(/^[^ ?*+#{]+/));
  374. };
  375. result = expr();
  376. if (!reader.eof()) {
  377. throw new SyntaxError(
  378. "Expected end of string", reader.getLine(), reader.getCol());
  379. }
  380. return result;
  381. };
  382. /**
  383. * Convert a string to a matcher (parsing simple alternations),
  384. * or do nothing if the argument is already a matcher.
  385. */
  386. Matcher.cast = function(m) {
  387. if (m instanceof Matcher) {
  388. return m;
  389. }
  390. return Matcher.parse(m);
  391. };
  392. /**
  393. * Create a matcher for a single type.
  394. */
  395. Matcher.fromType = function(type) {
  396. // Late require of ValidationTypes to break a dependency cycle.
  397. var ValidationTypes = require("./ValidationTypes");
  398. return new Matcher(function(expression) {
  399. return expression.hasNext() && ValidationTypes.isType(expression, type);
  400. }, type);
  401. };
  402. /**
  403. * Create a matcher for one or more juxtaposed words, which all must
  404. * occur, in the given order.
  405. */
  406. Matcher.seq = function() {
  407. var ms = Array.prototype.slice.call(arguments).map(Matcher.cast);
  408. if (ms.length === 1) {
  409. return ms[0];
  410. }
  411. return new Matcher(function(expression) {
  412. var i, result = true;
  413. for (i = 0; result && i < ms.length; i++) {
  414. result = ms[i].match(expression);
  415. }
  416. return result;
  417. }, function(prec) {
  418. var p = Matcher.prec.SEQ;
  419. var s = ms.map(function(m) {
  420. return m.toString(p);
  421. }).join(" ");
  422. if (prec > p) {
  423. s = "[ " + s + " ]";
  424. }
  425. return s;
  426. });
  427. };
  428. /**
  429. * Create a matcher for one or more alternatives, where exactly one
  430. * must occur.
  431. */
  432. Matcher.alt = function() {
  433. var ms = Array.prototype.slice.call(arguments).map(Matcher.cast);
  434. if (ms.length === 1) {
  435. return ms[0];
  436. }
  437. return new Matcher(function(expression) {
  438. var i, result = false;
  439. for (i = 0; !result && i < ms.length; i++) {
  440. result = ms[i].match(expression);
  441. }
  442. return result;
  443. }, function(prec) {
  444. var p = Matcher.prec.ALT;
  445. var s = ms.map(function(m) {
  446. return m.toString(p);
  447. }).join(" | ");
  448. if (prec > p) {
  449. s = "[ " + s + " ]";
  450. }
  451. return s;
  452. });
  453. };
  454. /**
  455. * Create a matcher for two or more options. This implements the
  456. * double bar (||) and double ampersand (&&) operators, as well as
  457. * variants of && where some of the alternatives are optional.
  458. * This will backtrack through even successful matches to try to
  459. * maximize the number of items matched.
  460. */
  461. Matcher.many = function(required) {
  462. var ms = Array.prototype.slice.call(arguments, 1).reduce(function(acc, v) {
  463. if (v.expand) {
  464. // Insert all of the options for the given complex rule as
  465. // individual options.
  466. var ValidationTypes = require("./ValidationTypes");
  467. acc.push.apply(acc, ValidationTypes.complex[v.expand].options);
  468. } else {
  469. acc.push(Matcher.cast(v));
  470. }
  471. return acc;
  472. }, []);
  473. if (required === true) {
  474. required = ms.map(function() {
  475. return true;
  476. });
  477. }
  478. var result = new Matcher(function(expression) {
  479. var seen = [], max = 0, pass = 0;
  480. var success = function(matchCount) {
  481. if (pass === 0) {
  482. max = Math.max(matchCount, max);
  483. return matchCount === ms.length;
  484. } else {
  485. return matchCount === max;
  486. }
  487. };
  488. var tryMatch = function(matchCount) {
  489. for (var i = 0; i < ms.length; i++) {
  490. if (seen[i]) {
  491. continue;
  492. }
  493. expression.mark();
  494. if (ms[i].match(expression)) {
  495. seen[i] = true;
  496. // Increase matchCount iff this was a required element
  497. // (or if all the elements are optional)
  498. if (tryMatch(matchCount + ((required === false || required[i]) ? 1 : 0))) {
  499. expression.drop();
  500. return true;
  501. }
  502. // Backtrack: try *not* matching using this rule, and
  503. // let's see if it leads to a better overall match.
  504. expression.restore();
  505. seen[i] = false;
  506. } else {
  507. expression.drop();
  508. }
  509. }
  510. return success(matchCount);
  511. };
  512. if (!tryMatch(0)) {
  513. // Couldn't get a complete match, retrace our steps to make the
  514. // match with the maximum # of required elements.
  515. pass++;
  516. tryMatch(0);
  517. }
  518. if (required === false) {
  519. return max > 0;
  520. }
  521. // Use finer-grained specification of which matchers are required.
  522. for (var i = 0; i < ms.length; i++) {
  523. if (required[i] && !seen[i]) {
  524. return false;
  525. }
  526. }
  527. return true;
  528. }, function(prec) {
  529. var p = required === false ? Matcher.prec.OROR : Matcher.prec.ANDAND;
  530. var s = ms.map(function(m, i) {
  531. if (required !== false && !required[i]) {
  532. return m.toString(Matcher.prec.MOD) + "?";
  533. }
  534. return m.toString(p);
  535. }).join(required === false ? " || " : " && ");
  536. if (prec > p) {
  537. s = "[ " + s + " ]";
  538. }
  539. return s;
  540. });
  541. result.options = ms;
  542. return result;
  543. };
  544. /**
  545. * Create a matcher for two or more options, where all options are
  546. * mandatory but they may appear in any order.
  547. */
  548. Matcher.andand = function() {
  549. var args = Array.prototype.slice.call(arguments);
  550. args.unshift(true);
  551. return Matcher.many.apply(Matcher, args);
  552. };
  553. /**
  554. * Create a matcher for two or more options, where options are
  555. * optional and may appear in any order, but at least one must be
  556. * present.
  557. */
  558. Matcher.oror = function() {
  559. var args = Array.prototype.slice.call(arguments);
  560. args.unshift(false);
  561. return Matcher.many.apply(Matcher, args);
  562. };
  563. /** Instance methods on Matchers. */
  564. Matcher.prototype = {
  565. constructor: Matcher,
  566. // These are expected to be overridden in every instance.
  567. match: function() { throw new Error("unimplemented"); },
  568. toString: function() { throw new Error("unimplemented"); },
  569. // This returns a standalone function to do the matching.
  570. func: function() { return this.match.bind(this); },
  571. // Basic combinators
  572. then: function(m) { return Matcher.seq(this, m); },
  573. or: function(m) { return Matcher.alt(this, m); },
  574. andand: function(m) { return Matcher.many(true, this, m); },
  575. oror: function(m) { return Matcher.many(false, this, m); },
  576. // Component value multipliers
  577. star: function() { return this.braces(0, Infinity, "*"); },
  578. plus: function() { return this.braces(1, Infinity, "+"); },
  579. question: function() { return this.braces(0, 1, "?"); },
  580. hash: function() {
  581. return this.braces(1, Infinity, "#", Matcher.cast(","));
  582. },
  583. braces: function(min, max, marker, optSep) {
  584. var m1 = this, m2 = optSep ? optSep.then(this) : this;
  585. if (!marker) {
  586. marker = "{" + min + "," + max + "}";
  587. }
  588. return new Matcher(function(expression) {
  589. var result = true, i;
  590. for (i = 0; i < max; i++) {
  591. if (i > 0 && optSep) {
  592. result = m2.match(expression);
  593. } else {
  594. result = m1.match(expression);
  595. }
  596. if (!result) {
  597. break;
  598. }
  599. }
  600. return i >= min;
  601. }, function() {
  602. return m1.toString(Matcher.prec.MOD) + marker;
  603. });
  604. }
  605. };
  606. },{"../util/StringReader":24,"../util/SyntaxError":25,"./ValidationTypes":21}],4:[function(require,module,exports){
  607. "use strict";
  608. module.exports = MediaFeature;
  609. var SyntaxUnit = require("../util/SyntaxUnit");
  610. var Parser = require("./Parser");
  611. /**
  612. * Represents a media feature, such as max-width:500.
  613. * @namespace parserlib.css
  614. * @class MediaFeature
  615. * @extends parserlib.util.SyntaxUnit
  616. * @constructor
  617. * @param {SyntaxUnit} name The name of the feature.
  618. * @param {SyntaxUnit} value The value of the feature or null if none.
  619. */
  620. function MediaFeature(name, value) {
  621. SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE);
  622. /**
  623. * The name of the media feature
  624. * @type String
  625. * @property name
  626. */
  627. this.name = name;
  628. /**
  629. * The value for the feature or null if there is none.
  630. * @type SyntaxUnit
  631. * @property value
  632. */
  633. this.value = value;
  634. }
  635. MediaFeature.prototype = new SyntaxUnit();
  636. MediaFeature.prototype.constructor = MediaFeature;
  637. },{"../util/SyntaxUnit":26,"./Parser":6}],5:[function(require,module,exports){
  638. "use strict";
  639. module.exports = MediaQuery;
  640. var SyntaxUnit = require("../util/SyntaxUnit");
  641. var Parser = require("./Parser");
  642. /**
  643. * Represents an individual media query.
  644. * @namespace parserlib.css
  645. * @class MediaQuery
  646. * @extends parserlib.util.SyntaxUnit
  647. * @constructor
  648. * @param {String} modifier The modifier "not" or "only" (or null).
  649. * @param {String} mediaType The type of media (i.e., "print").
  650. * @param {Array} parts Array of selectors parts making up this selector.
  651. * @param {int} line The line of text on which the unit resides.
  652. * @param {int} col The column of text on which the unit resides.
  653. */
  654. function MediaQuery(modifier, mediaType, features, line, col) {
  655. SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType : "") + (mediaType && features.length > 0 ? " and " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE);
  656. /**
  657. * The media modifier ("not" or "only")
  658. * @type String
  659. * @property modifier
  660. */
  661. this.modifier = modifier;
  662. /**
  663. * The mediaType (i.e., "print")
  664. * @type String
  665. * @property mediaType
  666. */
  667. this.mediaType = mediaType;
  668. /**
  669. * The parts that make up the selector.
  670. * @type Array
  671. * @property features
  672. */
  673. this.features = features;
  674. }
  675. MediaQuery.prototype = new SyntaxUnit();
  676. MediaQuery.prototype.constructor = MediaQuery;
  677. },{"../util/SyntaxUnit":26,"./Parser":6}],6:[function(require,module,exports){
  678. "use strict";
  679. module.exports = Parser;
  680. var EventTarget = require("../util/EventTarget");
  681. var SyntaxError = require("../util/SyntaxError");
  682. var SyntaxUnit = require("../util/SyntaxUnit");
  683. var Combinator = require("./Combinator");
  684. var MediaFeature = require("./MediaFeature");
  685. var MediaQuery = require("./MediaQuery");
  686. var PropertyName = require("./PropertyName");
  687. var PropertyValue = require("./PropertyValue");
  688. var PropertyValuePart = require("./PropertyValuePart");
  689. var Selector = require("./Selector");
  690. var SelectorPart = require("./SelectorPart");
  691. var SelectorSubPart = require("./SelectorSubPart");
  692. var TokenStream = require("./TokenStream");
  693. var Tokens = require("./Tokens");
  694. var Validation = require("./Validation");
  695. /**
  696. * A CSS3 parser.
  697. * @namespace parserlib.css
  698. * @class Parser
  699. * @constructor
  700. * @param {Object} options (Optional) Various options for the parser:
  701. * starHack (true|false) to allow IE6 star hack as valid,
  702. * underscoreHack (true|false) to interpret leading underscores
  703. * as IE6-7 targeting for known properties, ieFilters (true|false)
  704. * to indicate that IE < 8 filters should be accepted and not throw
  705. * syntax errors.
  706. */
  707. function Parser(options) {
  708. //inherit event functionality
  709. EventTarget.call(this);
  710. this.options = options || {};
  711. this._tokenStream = null;
  712. }
  713. //Static constants
  714. Parser.DEFAULT_TYPE = 0;
  715. Parser.COMBINATOR_TYPE = 1;
  716. Parser.MEDIA_FEATURE_TYPE = 2;
  717. Parser.MEDIA_QUERY_TYPE = 3;
  718. Parser.PROPERTY_NAME_TYPE = 4;
  719. Parser.PROPERTY_VALUE_TYPE = 5;
  720. Parser.PROPERTY_VALUE_PART_TYPE = 6;
  721. Parser.SELECTOR_TYPE = 7;
  722. Parser.SELECTOR_PART_TYPE = 8;
  723. Parser.SELECTOR_SUB_PART_TYPE = 9;
  724. Parser.prototype = function() {
  725. var proto = new EventTarget(), //new prototype
  726. prop,
  727. additions = {
  728. __proto__: null,
  729. //restore constructor
  730. constructor: Parser,
  731. //instance constants - yuck
  732. DEFAULT_TYPE : 0,
  733. COMBINATOR_TYPE : 1,
  734. MEDIA_FEATURE_TYPE : 2,
  735. MEDIA_QUERY_TYPE : 3,
  736. PROPERTY_NAME_TYPE : 4,
  737. PROPERTY_VALUE_TYPE : 5,
  738. PROPERTY_VALUE_PART_TYPE : 6,
  739. SELECTOR_TYPE : 7,
  740. SELECTOR_PART_TYPE : 8,
  741. SELECTOR_SUB_PART_TYPE : 9,
  742. //-----------------------------------------------------------------
  743. // Grammar
  744. //-----------------------------------------------------------------
  745. _stylesheet: function() {
  746. /*
  747. * stylesheet
  748. * : [ CHARSET_SYM S* STRING S* ';' ]?
  749. * [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
  750. * [ namespace [S|CDO|CDC]* ]*
  751. * [ [ ruleset | media | page | font_face | keyframes_rule | supports_rule ] [S|CDO|CDC]* ]*
  752. * ;
  753. */
  754. var tokenStream = this._tokenStream,
  755. count,
  756. token,
  757. tt;
  758. this.fire("startstylesheet");
  759. //try to read character set
  760. this._charset();
  761. this._skipCruft();
  762. //try to read imports - may be more than one
  763. while (tokenStream.peek() === Tokens.IMPORT_SYM) {
  764. this._import();
  765. this._skipCruft();
  766. }
  767. //try to read namespaces - may be more than one
  768. while (tokenStream.peek() === Tokens.NAMESPACE_SYM) {
  769. this._namespace();
  770. this._skipCruft();
  771. }
  772. //get the next token
  773. tt = tokenStream.peek();
  774. //try to read the rest
  775. while (tt > Tokens.EOF) {
  776. try {
  777. switch (tt) {
  778. case Tokens.MEDIA_SYM:
  779. this._media();
  780. this._skipCruft();
  781. break;
  782. case Tokens.PAGE_SYM:
  783. this._page();
  784. this._skipCruft();
  785. break;
  786. case Tokens.FONT_FACE_SYM:
  787. this._font_face();
  788. this._skipCruft();
  789. break;
  790. case Tokens.KEYFRAMES_SYM:
  791. this._keyframes();
  792. this._skipCruft();
  793. break;
  794. case Tokens.VIEWPORT_SYM:
  795. this._viewport();
  796. this._skipCruft();
  797. break;
  798. case Tokens.DOCUMENT_SYM:
  799. this._document();
  800. this._skipCruft();
  801. break;
  802. case Tokens.SUPPORTS_SYM:
  803. this._supports();
  804. this._skipCruft();
  805. break;
  806. case Tokens.UNKNOWN_SYM: //unknown @ rule
  807. tokenStream.get();
  808. if (!this.options.strict) {
  809. //fire error event
  810. this.fire({
  811. type: "error",
  812. error: null,
  813. message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
  814. line: tokenStream.LT(0).startLine,
  815. col: tokenStream.LT(0).startCol
  816. });
  817. //skip braces
  818. count=0;
  819. while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) === Tokens.LBRACE) {
  820. count++; //keep track of nesting depth
  821. }
  822. while (count) {
  823. tokenStream.advance([Tokens.RBRACE]);
  824. count--;
  825. }
  826. } else {
  827. //not a syntax error, rethrow it
  828. throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol);
  829. }
  830. break;
  831. case Tokens.S:
  832. this._readWhitespace();
  833. break;
  834. default:
  835. if (!this._ruleset()) {
  836. //error handling for known issues
  837. switch (tt) {
  838. case Tokens.CHARSET_SYM:
  839. token = tokenStream.LT(1);
  840. this._charset(false);
  841. throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol);
  842. case Tokens.IMPORT_SYM:
  843. token = tokenStream.LT(1);
  844. this._import(false);
  845. throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
  846. case Tokens.NAMESPACE_SYM:
  847. token = tokenStream.LT(1);
  848. this._namespace(false);
  849. throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
  850. default:
  851. tokenStream.get(); //get the last token
  852. this._unexpectedToken(tokenStream.token());
  853. }
  854. }
  855. }
  856. } catch (ex) {
  857. if (ex instanceof SyntaxError && !this.options.strict) {
  858. this.fire({
  859. type: "error",
  860. error: ex,
  861. message: ex.message,
  862. line: ex.line,
  863. col: ex.col
  864. });
  865. } else {
  866. throw ex;
  867. }
  868. }
  869. tt = tokenStream.peek();
  870. }
  871. if (tt !== Tokens.EOF) {
  872. this._unexpectedToken(tokenStream.token());
  873. }
  874. this.fire("endstylesheet");
  875. },
  876. _charset: function(emit) {
  877. var tokenStream = this._tokenStream,
  878. charset,
  879. token,
  880. line,
  881. col;
  882. if (tokenStream.match(Tokens.CHARSET_SYM)) {
  883. line = tokenStream.token().startLine;
  884. col = tokenStream.token().startCol;
  885. this._readWhitespace();
  886. tokenStream.mustMatch(Tokens.STRING);
  887. token = tokenStream.token();
  888. charset = token.value;
  889. this._readWhitespace();
  890. tokenStream.mustMatch(Tokens.SEMICOLON);
  891. if (emit !== false) {
  892. this.fire({
  893. type: "charset",
  894. charset:charset,
  895. line: line,
  896. col: col
  897. });
  898. }
  899. }
  900. },
  901. _import: function(emit) {
  902. /*
  903. * import
  904. * : IMPORT_SYM S*
  905. * [STRING|URI] S* media_query_list? ';' S*
  906. */
  907. var tokenStream = this._tokenStream,
  908. uri,
  909. importToken,
  910. mediaList = [];
  911. //read import symbol
  912. tokenStream.mustMatch(Tokens.IMPORT_SYM);
  913. importToken = tokenStream.token();
  914. this._readWhitespace();
  915. tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
  916. //grab the URI value
  917. uri = tokenStream.token().value.replace(/^(?:url\()?["']?([^"']+?)["']?\)?$/, "$1");
  918. this._readWhitespace();
  919. mediaList = this._media_query_list();
  920. //must end with a semicolon
  921. tokenStream.mustMatch(Tokens.SEMICOLON);
  922. this._readWhitespace();
  923. if (emit !== false) {
  924. this.fire({
  925. type: "import",
  926. uri: uri,
  927. media: mediaList,
  928. line: importToken.startLine,
  929. col: importToken.startCol
  930. });
  931. }
  932. },
  933. _namespace: function(emit) {
  934. /*
  935. * namespace
  936. * : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
  937. */
  938. var tokenStream = this._tokenStream,
  939. line,
  940. col,
  941. prefix,
  942. uri;
  943. //read import symbol
  944. tokenStream.mustMatch(Tokens.NAMESPACE_SYM);
  945. line = tokenStream.token().startLine;
  946. col = tokenStream.token().startCol;
  947. this._readWhitespace();
  948. //it's a namespace prefix - no _namespace_prefix() method because it's just an IDENT
  949. if (tokenStream.match(Tokens.IDENT)) {
  950. prefix = tokenStream.token().value;
  951. this._readWhitespace();
  952. }
  953. tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
  954. /*if (!tokenStream.match(Tokens.STRING)){
  955. tokenStream.mustMatch(Tokens.URI);
  956. }*/
  957. //grab the URI value
  958. uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
  959. this._readWhitespace();
  960. //must end with a semicolon
  961. tokenStream.mustMatch(Tokens.SEMICOLON);
  962. this._readWhitespace();
  963. if (emit !== false) {
  964. this.fire({
  965. type: "namespace",
  966. prefix: prefix,
  967. uri: uri,
  968. line: line,
  969. col: col
  970. });
  971. }
  972. },
  973. _supports: function(emit) {
  974. /*
  975. * supports_rule
  976. * : SUPPORTS_SYM S* supports_condition S* group_rule_body
  977. * ;
  978. */
  979. var tokenStream = this._tokenStream,
  980. line,
  981. col;
  982. if (tokenStream.match(Tokens.SUPPORTS_SYM)) {
  983. line = tokenStream.token().startLine;
  984. col = tokenStream.token().startCol;
  985. this._readWhitespace();
  986. this._supports_condition();
  987. this._readWhitespace();
  988. tokenStream.mustMatch(Tokens.LBRACE);
  989. this._readWhitespace();
  990. if (emit !== false) {
  991. this.fire({
  992. type: "startsupports",
  993. line: line,
  994. col: col
  995. });
  996. }
  997. while (true) {
  998. if (!this._ruleset()) {
  999. break;
  1000. }
  1001. }
  1002. tokenStream.mustMatch(Tokens.RBRACE);
  1003. this._readWhitespace();
  1004. this.fire({
  1005. type: "endsupports",
  1006. line: line,
  1007. col: col
  1008. });
  1009. }
  1010. },
  1011. _supports_condition: function() {
  1012. /*
  1013. * supports_condition
  1014. * : supports_negation | supports_conjunction | supports_disjunction |
  1015. * supports_condition_in_parens
  1016. * ;
  1017. */
  1018. var tokenStream = this._tokenStream,
  1019. ident;
  1020. if (tokenStream.match(Tokens.IDENT)) {
  1021. ident = tokenStream.token().value.toLowerCase();
  1022. if (ident === "not") {
  1023. tokenStream.mustMatch(Tokens.S);
  1024. this._supports_condition_in_parens();
  1025. } else {
  1026. tokenStream.unget();
  1027. }
  1028. } else {
  1029. this._supports_condition_in_parens();
  1030. this._readWhitespace();
  1031. while (tokenStream.peek() === Tokens.IDENT) {
  1032. ident = tokenStream.LT(1).value.toLowerCase();
  1033. if (ident === "and" || ident === "or") {
  1034. tokenStream.mustMatch(Tokens.IDENT);
  1035. this._readWhitespace();
  1036. this._supports_condition_in_parens();
  1037. this._readWhitespace();
  1038. }
  1039. }
  1040. }
  1041. },
  1042. _supports_condition_in_parens: function() {
  1043. /*
  1044. * supports_condition_in_parens
  1045. * : ( '(' S* supports_condition S* ')' ) | supports_declaration_condition |
  1046. * general_enclosed
  1047. * ;
  1048. */
  1049. var tokenStream = this._tokenStream,
  1050. ident;
  1051. if (tokenStream.match(Tokens.LPAREN)) {
  1052. this._readWhitespace();
  1053. if (tokenStream.match(Tokens.IDENT)) {
  1054. // look ahead for not keyword, if not given, continue with declaration condition.
  1055. ident = tokenStream.token().value.toLowerCase();
  1056. if (ident === "not") {
  1057. this._readWhitespace();
  1058. this._supports_condition();
  1059. this._readWhitespace();
  1060. tokenStream.mustMatch(Tokens.RPAREN);
  1061. } else {
  1062. tokenStream.unget();
  1063. this._supports_declaration_condition(false);
  1064. }
  1065. } else {
  1066. this._supports_condition();
  1067. this._readWhitespace();
  1068. tokenStream.mustMatch(Tokens.RPAREN);
  1069. }
  1070. } else {
  1071. this._supports_declaration_condition();
  1072. }
  1073. },
  1074. _supports_declaration_condition: function(requireStartParen) {
  1075. /*
  1076. * supports_declaration_condition
  1077. * : '(' S* declaration ')'
  1078. * ;
  1079. */
  1080. var tokenStream = this._tokenStream;
  1081. if (requireStartParen !== false) {
  1082. tokenStream.mustMatch(Tokens.LPAREN);
  1083. }
  1084. this._readWhitespace();
  1085. this._declaration();
  1086. tokenStream.mustMatch(Tokens.RPAREN);
  1087. },
  1088. _media: function() {
  1089. /*
  1090. * media
  1091. * : MEDIA_SYM S* media_query_list S* '{' S* ruleset* '}' S*
  1092. * ;
  1093. */
  1094. var tokenStream = this._tokenStream,
  1095. line,
  1096. col,
  1097. mediaList;// = [];
  1098. //look for @media
  1099. tokenStream.mustMatch(Tokens.MEDIA_SYM);
  1100. line = tokenStream.token().startLine;
  1101. col = tokenStream.token().startCol;
  1102. this._readWhitespace();
  1103. mediaList = this._media_query_list();
  1104. tokenStream.mustMatch(Tokens.LBRACE);
  1105. this._readWhitespace();
  1106. this.fire({
  1107. type: "startmedia",
  1108. media: mediaList,
  1109. line: line,
  1110. col: col
  1111. });
  1112. while (true) {
  1113. if (tokenStream.peek() === Tokens.PAGE_SYM) {
  1114. this._page();
  1115. } else if (tokenStream.peek() === Tokens.FONT_FACE_SYM) {
  1116. this._font_face();
  1117. } else if (tokenStream.peek() === Tokens.VIEWPORT_SYM) {
  1118. this._viewport();
  1119. } else if (tokenStream.peek() === Tokens.DOCUMENT_SYM) {
  1120. this._document();
  1121. } else if (tokenStream.peek() === Tokens.SUPPORTS_SYM) {
  1122. this._supports();
  1123. } else if (tokenStream.peek() === Tokens.MEDIA_SYM) {
  1124. this._media();
  1125. } else if (!this._ruleset()) {
  1126. break;
  1127. }
  1128. }
  1129. tokenStream.mustMatch(Tokens.RBRACE);
  1130. this._readWhitespace();
  1131. this.fire({
  1132. type: "endmedia",
  1133. media: mediaList,
  1134. line: line,
  1135. col: col
  1136. });
  1137. },
  1138. //CSS3 Media Queries
  1139. _media_query_list: function() {
  1140. /*
  1141. * media_query_list
  1142. * : S* [media_query [ ',' S* media_query ]* ]?
  1143. * ;
  1144. */
  1145. var tokenStream = this._tokenStream,
  1146. mediaList = [];
  1147. this._readWhitespace();
  1148. if (tokenStream.peek() === Tokens.IDENT || tokenStream.peek() === Tokens.LPAREN) {
  1149. mediaList.push(this._media_query());
  1150. }
  1151. while (tokenStream.match(Tokens.COMMA)) {
  1152. this._readWhitespace();
  1153. mediaList.push(this._media_query());
  1154. }
  1155. return mediaList;
  1156. },
  1157. /*
  1158. * Note: "expression" in the grammar maps to the _media_expression
  1159. * method.
  1160. */
  1161. _media_query: function() {
  1162. /*
  1163. * media_query
  1164. * : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
  1165. * | expression [ AND S* expression ]*
  1166. * ;
  1167. */
  1168. var tokenStream = this._tokenStream,
  1169. type = null,
  1170. ident = null,
  1171. token = null,
  1172. expressions = [];
  1173. if (tokenStream.match(Tokens.IDENT)) {
  1174. ident = tokenStream.token().value.toLowerCase();
  1175. //since there's no custom tokens for these, need to manually check
  1176. if (ident !== "only" && ident !== "not") {
  1177. tokenStream.unget();
  1178. ident = null;
  1179. } else {
  1180. token = tokenStream.token();
  1181. }
  1182. }
  1183. this._readWhitespace();
  1184. if (tokenStream.peek() === Tokens.IDENT) {
  1185. type = this._media_type();
  1186. if (token === null) {
  1187. token = tokenStream.token();
  1188. }
  1189. } else if (tokenStream.peek() === Tokens.LPAREN) {
  1190. if (token === null) {
  1191. token = tokenStream.LT(1);
  1192. }
  1193. expressions.push(this._media_expression());
  1194. }
  1195. if (type === null && expressions.length === 0) {
  1196. return null;
  1197. } else {
  1198. this._readWhitespace();
  1199. while (tokenStream.match(Tokens.IDENT)) {
  1200. if (tokenStream.token().value.toLowerCase() !== "and") {
  1201. this._unexpectedToken(tokenStream.token());
  1202. }
  1203. this._readWhitespace();
  1204. expressions.push(this._media_expression());
  1205. }
  1206. }
  1207. return new MediaQuery(ident, type, expressions, token.startLine, token.startCol);
  1208. },
  1209. //CSS3 Media Queries
  1210. _media_type: function() {
  1211. /*
  1212. * media_type
  1213. * : IDENT
  1214. * ;
  1215. */
  1216. return this._media_feature();
  1217. },
  1218. /**
  1219. * Note: in CSS3 Media Queries, this is called "expression".
  1220. * Renamed here to avoid conflict with CSS3 Selectors
  1221. * definition of "expression". Also note that "expr" in the
  1222. * grammar now maps to "expression" from CSS3 selectors.
  1223. * @method _media_expression
  1224. * @private
  1225. */
  1226. _media_expression: function() {
  1227. /*
  1228. * expression
  1229. * : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
  1230. * ;
  1231. */
  1232. var tokenStream = this._tokenStream,
  1233. feature = null,
  1234. token,
  1235. expression = null;
  1236. tokenStream.mustMatch(Tokens.LPAREN);
  1237. feature = this._media_feature();
  1238. this._readWhitespace();
  1239. if (tokenStream.match(Tokens.COLON)) {
  1240. this._readWhitespace();
  1241. token = tokenStream.LT(1);
  1242. expression = this._expression();
  1243. }
  1244. tokenStream.mustMatch(Tokens.RPAREN);
  1245. this._readWhitespace();
  1246. return new MediaFeature(feature, expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null);
  1247. },
  1248. //CSS3 Media Queries
  1249. _media_feature: function() {
  1250. /*
  1251. * media_feature
  1252. * : IDENT
  1253. * ;
  1254. */
  1255. var tokenStream = this._tokenStream;
  1256. this._readWhitespace();
  1257. tokenStream.mustMatch(Tokens.IDENT);
  1258. return SyntaxUnit.fromToken(tokenStream.token());
  1259. },
  1260. //CSS3 Paged Media
  1261. _page: function() {
  1262. /*
  1263. * page:
  1264. * PAGE_SYM S* IDENT? pseudo_page? S*
  1265. * '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
  1266. * ;
  1267. */
  1268. var tokenStream = this._tokenStream,
  1269. line,
  1270. col,
  1271. identifier = null,
  1272. pseudoPage = null;
  1273. //look for @page
  1274. tokenStream.mustMatch(Tokens.PAGE_SYM);
  1275. line = tokenStream.token().startLine;
  1276. col = tokenStream.token().startCol;
  1277. this._readWhitespace();
  1278. if (tokenStream.match(Tokens.IDENT)) {
  1279. identifier = tokenStream.token().value;
  1280. //The value 'auto' may not be used as a page name and MUST be treated as a syntax error.
  1281. if (identifier.toLowerCase() === "auto") {
  1282. this._unexpectedToken(tokenStream.token());
  1283. }
  1284. }
  1285. //see if there's a colon upcoming
  1286. if (tokenStream.peek() === Tokens.COLON) {
  1287. pseudoPage = this._pseudo_page();
  1288. }
  1289. this._readWhitespace();
  1290. this.fire({
  1291. type: "startpage",
  1292. id: identifier,
  1293. pseudo: pseudoPage,
  1294. line: line,
  1295. col: col
  1296. });
  1297. this._readDeclarations(true, true);
  1298. this.fire({
  1299. type: "endpage",
  1300. id: identifier,
  1301. pseudo: pseudoPage,
  1302. line: line,
  1303. col: col
  1304. });
  1305. },
  1306. //CSS3 Paged Media
  1307. _margin: function() {
  1308. /*
  1309. * margin :
  1310. * margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S*
  1311. * ;
  1312. */
  1313. var tokenStream = this._tokenStream,
  1314. line,
  1315. col,
  1316. marginSym = this._margin_sym();
  1317. if (marginSym) {
  1318. line = tokenStream.token().startLine;
  1319. col = tokenStream.token().startCol;
  1320. this.fire({
  1321. type: "startpagemargin",
  1322. margin: marginSym,
  1323. line: line,
  1324. col: col
  1325. });
  1326. this._readDeclarations(true);
  1327. this.fire({
  1328. type: "endpagemargin",
  1329. margin: marginSym,
  1330. line: line,
  1331. col: col
  1332. });
  1333. return true;
  1334. } else {
  1335. return false;
  1336. }
  1337. },
  1338. //CSS3 Paged Media
  1339. _margin_sym: function() {
  1340. /*
  1341. * margin_sym :
  1342. * TOPLEFTCORNER_SYM |
  1343. * TOPLEFT_SYM |
  1344. * TOPCENTER_SYM |
  1345. * TOPRIGHT_SYM |
  1346. * TOPRIGHTCORNER_SYM |
  1347. * BOTTOMLEFTCORNER_SYM |
  1348. * BOTTOMLEFT_SYM |
  1349. * BOTTOMCENTER_SYM |
  1350. * BOTTOMRIGHT_SYM |
  1351. * BOTTOMRIGHTCORNER_SYM |
  1352. * LEFTTOP_SYM |
  1353. * LEFTMIDDLE_SYM |
  1354. * LEFTBOTTOM_SYM |
  1355. * RIGHTTOP_SYM |
  1356. * RIGHTMIDDLE_SYM |
  1357. * RIGHTBOTTOM_SYM
  1358. * ;
  1359. */
  1360. var tokenStream = this._tokenStream;
  1361. if (tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM,
  1362. Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM,
  1363. Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM,
  1364. Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM,
  1365. Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM,
  1366. Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM,
  1367. Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM])) {
  1368. return SyntaxUnit.fromToken(tokenStream.token());
  1369. } else {
  1370. return null;
  1371. }
  1372. },
  1373. _pseudo_page: function() {
  1374. /*
  1375. * pseudo_page
  1376. * : ':' IDENT
  1377. * ;
  1378. */
  1379. var tokenStream = this._tokenStream;
  1380. tokenStream.mustMatch(Tokens.COLON);
  1381. tokenStream.mustMatch(Tokens.IDENT);
  1382. //TODO: CSS3 Paged Media says only "left", "center", and "right" are allowed
  1383. return tokenStream.token().value;
  1384. },
  1385. _font_face: function() {
  1386. /*
  1387. * font_face
  1388. * : FONT_FACE_SYM S*
  1389. * '{' S* declaration [ ';' S* declaration ]* '}' S*
  1390. * ;
  1391. */
  1392. var tokenStream = this._tokenStream,
  1393. line,
  1394. col;
  1395. //look for @page
  1396. tokenStream.mustMatch(Tokens.FONT_FACE_SYM);
  1397. line = tokenStream.token().startLine;
  1398. col = tokenStream.token().startCol;
  1399. this._readWhitespace();
  1400. this.fire({
  1401. type: "startfontface",
  1402. line: line,
  1403. col: col
  1404. });
  1405. this._readDeclarations(true);
  1406. this.fire({
  1407. type: "endfontface",
  1408. line: line,
  1409. col: col
  1410. });
  1411. },
  1412. _viewport: function() {
  1413. /*
  1414. * viewport
  1415. * : VIEWPORT_SYM S*
  1416. * '{' S* declaration? [ ';' S* declaration? ]* '}' S*
  1417. * ;
  1418. */
  1419. var tokenStream = this._tokenStream,
  1420. line,
  1421. col;
  1422. tokenStream.mustMatch(Tokens.VIEWPORT_SYM);
  1423. line = tokenStream.token().startLine;
  1424. col = tokenStream.token().startCol;
  1425. this._readWhitespace();
  1426. this.fire({
  1427. type: "startviewport",
  1428. line: line,
  1429. col: col
  1430. });
  1431. this._readDeclarations(true);
  1432. this.fire({
  1433. type: "endviewport",
  1434. line: line,
  1435. col: col
  1436. });
  1437. },
  1438. _document: function() {
  1439. /*
  1440. * document
  1441. * : DOCUMENT_SYM S*
  1442. * _document_function [ ',' S* _document_function ]* S*
  1443. * '{' S* ruleset* '}'
  1444. * ;
  1445. */
  1446. var tokenStream = this._tokenStream,
  1447. token,
  1448. functions = [],
  1449. prefix = "";
  1450. tokenStream.mustMatch(Tokens.DOCUMENT_SYM);
  1451. token = tokenStream.token();
  1452. if (/^@\-([^\-]+)\-/.test(token.value)) {
  1453. prefix = RegExp.$1;
  1454. }
  1455. this._readWhitespace();
  1456. functions.push(this._document_function());
  1457. while (tokenStream.match(Tokens.COMMA)) {
  1458. this._readWhitespace();
  1459. functions.push(this._document_function());
  1460. }
  1461. tokenStream.mustMatch(Tokens.LBRACE);
  1462. this._readWhitespace();
  1463. this.fire({
  1464. type: "startdocument",
  1465. functions: functions,
  1466. prefix: prefix,
  1467. line: token.startLine,
  1468. col: token.startCol
  1469. });
  1470. var ok = true;
  1471. while (ok) {
  1472. switch (tokenStream.peek()) {
  1473. case Tokens.PAGE_SYM:
  1474. this._page();
  1475. break;
  1476. case Tokens.FONT_FACE_SYM:
  1477. this._font_face();
  1478. break;
  1479. case Tokens.VIEWPORT_SYM:
  1480. this._viewport();
  1481. break;
  1482. case Tokens.MEDIA_SYM:
  1483. this._media();
  1484. break;
  1485. case Tokens.KEYFRAMES_SYM:
  1486. this._keyframes();
  1487. break;
  1488. case Tokens.DOCUMENT_SYM:
  1489. this._document();
  1490. break;
  1491. default:
  1492. ok = Boolean(this._ruleset());
  1493. }
  1494. }
  1495. tokenStream.mustMatch(Tokens.RBRACE);
  1496. token = tokenStream.token();
  1497. this._readWhitespace();
  1498. this.fire({
  1499. type: "enddocument",
  1500. functions: functions,
  1501. prefix: prefix,
  1502. line: token.startLine,
  1503. col: token.startCol
  1504. });
  1505. },
  1506. _document_function: function() {
  1507. /*
  1508. * document_function
  1509. * : function | URI S*
  1510. * ;
  1511. */
  1512. var tokenStream = this._tokenStream,
  1513. value;
  1514. if (tokenStream.match(Tokens.URI)) {
  1515. value = tokenStream.token().value;
  1516. this._readWhitespace();
  1517. } else {
  1518. value = this._function();
  1519. }
  1520. return value;
  1521. },
  1522. _operator: function(inFunction) {
  1523. /*
  1524. * operator (outside function)
  1525. * : '/' S* | ',' S* | /( empty )/
  1526. * operator (inside function)
  1527. * : '/' S* | '+' S* | '*' S* | '-' S* /( empty )/
  1528. * ;
  1529. */
  1530. var tokenStream = this._tokenStream,
  1531. token = null;
  1532. if (tokenStream.match([Tokens.SLASH, Tokens.COMMA]) ||
  1533. (inFunction && tokenStream.match([Tokens.PLUS, Tokens.STAR, Tokens.MINUS]))) {
  1534. token = tokenStream.token();
  1535. this._readWhitespace();
  1536. }
  1537. return token ? PropertyValuePart.fromToken(token) : null;
  1538. },
  1539. _combinator: function() {
  1540. /*
  1541. * combinator
  1542. * : PLUS S* | GREATER S* | TILDE S* | S+
  1543. * ;
  1544. */
  1545. var tokenStream = this._tokenStream,
  1546. value = null,
  1547. token;
  1548. if (tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])) {
  1549. token = tokenStream.token();
  1550. value = new Combinator(token.value, token.startLine, token.startCol);
  1551. this._readWhitespace();
  1552. }
  1553. return value;
  1554. },
  1555. _unary_operator: function() {
  1556. /*
  1557. * unary_operator
  1558. * : '-' | '+'
  1559. * ;
  1560. */
  1561. var tokenStream = this._tokenStream;
  1562. if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])) {
  1563. return tokenStream.token().value;
  1564. } else {
  1565. return null;
  1566. }
  1567. },
  1568. _property: function() {
  1569. /*
  1570. * property
  1571. * : IDENT S*
  1572. * ;
  1573. */
  1574. var tokenStream = this._tokenStream,
  1575. value = null,
  1576. hack = null,
  1577. tokenValue,
  1578. token,
  1579. line,
  1580. col;
  1581. //check for star hack - throws error if not allowed
  1582. if (tokenStream.peek() === Tokens.STAR && this.options.starHack) {
  1583. tokenStream.get();
  1584. token = tokenStream.token();
  1585. hack = token.value;
  1586. line = token.startLine;
  1587. col = token.startCol;
  1588. }
  1589. if (tokenStream.match(Tokens.IDENT)) {
  1590. token = tokenStream.token();
  1591. tokenValue = token.value;
  1592. //check for underscore hack - no error if not allowed because it's valid CSS syntax
  1593. if (tokenValue.charAt(0) === "_" && this.options.underscoreHack) {
  1594. hack = "_";
  1595. tokenValue = tokenValue.substring(1);
  1596. }
  1597. value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol));
  1598. this._readWhitespace();
  1599. }
  1600. return value;
  1601. },
  1602. //Augmented with CSS3 Selectors
  1603. _ruleset: function() {
  1604. /*
  1605. * ruleset
  1606. * : selectors_group
  1607. * '{' S* declaration? [ ';' S* declaration? ]* '}' S*
  1608. * ;
  1609. */
  1610. var tokenStream = this._tokenStream,
  1611. tt,
  1612. selectors;
  1613. /*
  1614. * Error Recovery: If even a single selector fails to parse,
  1615. * then the entire ruleset should be thrown away.
  1616. */
  1617. try {
  1618. selectors = this._selectors_group();
  1619. } catch (ex) {
  1620. if (ex instanceof SyntaxError && !this.options.strict) {
  1621. //fire error event
  1622. this.fire({
  1623. type: "error",
  1624. error: ex,
  1625. message: ex.message,
  1626. line: ex.line,
  1627. col: ex.col
  1628. });
  1629. //skip over everything until closing brace
  1630. tt = tokenStream.advance([Tokens.RBRACE]);
  1631. if (tt === Tokens.RBRACE) {
  1632. //if there's a right brace, the rule is finished so don't do anything
  1633. } else {
  1634. //otherwise, rethrow the error because it wasn't handled properly
  1635. throw ex;
  1636. }
  1637. } else {
  1638. //not a syntax error, rethrow it
  1639. throw ex;
  1640. }
  1641. //trigger parser to continue
  1642. return true;
  1643. }
  1644. //if it got here, all selectors parsed
  1645. if (selectors) {
  1646. this.fire({
  1647. type: "startrule",
  1648. selectors: selectors,
  1649. line: selectors[0].line,
  1650. col: selectors[0].col
  1651. });
  1652. this._readDeclarations(true);
  1653. this.fire({
  1654. type: "endrule",
  1655. selectors: selectors,
  1656. line: selectors[0].line,
  1657. col: selectors[0].col
  1658. });
  1659. }
  1660. return selectors;
  1661. },
  1662. //CSS3 Selectors
  1663. _selectors_group: function() {
  1664. /*
  1665. * selectors_group
  1666. * : selector [ COMMA S* selector ]*
  1667. * ;
  1668. */
  1669. var tokenStream = this._tokenStream,
  1670. selectors = [],
  1671. selector;
  1672. selector = this._selector();
  1673. if (selector !== null) {
  1674. selectors.push(selector);
  1675. while (tokenStream.match(Tokens.COMMA)) {
  1676. this._readWhitespace();
  1677. selector = this._selector();
  1678. if (selector !== null) {
  1679. selectors.push(selector);
  1680. } else {
  1681. this._unexpectedToken(tokenStream.LT(1));
  1682. }
  1683. }
  1684. }
  1685. return selectors.length ? selectors : null;
  1686. },
  1687. //CSS3 Selectors
  1688. _selector: function() {
  1689. /*
  1690. * selector
  1691. * : simple_selector_sequence [ combinator simple_selector_sequence ]*
  1692. * ;
  1693. */
  1694. var tokenStream = this._tokenStream,
  1695. selector = [],
  1696. nextSelector = null,
  1697. combinator = null,
  1698. ws = null;
  1699. //if there's no simple selector, then there's no selector
  1700. nextSelector = this._simple_selector_sequence();
  1701. if (nextSelector === null) {
  1702. return null;
  1703. }
  1704. selector.push(nextSelector);
  1705. do {
  1706. //look for a combinator
  1707. combinator = this._combinator();
  1708. if (combinator !== null) {
  1709. selector.push(combinator);
  1710. nextSelector = this._simple_selector_sequence();
  1711. //there must be a next selector
  1712. if (nextSelector === null) {
  1713. this._unexpectedToken(tokenStream.LT(1));
  1714. } else {
  1715. //nextSelector is an instance of SelectorPart
  1716. selector.push(nextSelector);
  1717. }
  1718. } else {
  1719. //if there's not whitespace, we're done
  1720. if (this._readWhitespace()) {
  1721. //add whitespace separator
  1722. ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol);
  1723. //combinator is not required
  1724. combinator = this._combinator();
  1725. //selector is required if there's a combinator
  1726. nextSelector = this._simple_selector_sequence();
  1727. if (nextSelector === null) {
  1728. if (combinator !== null) {
  1729. this._unexpectedToken(tokenStream.LT(1));
  1730. }
  1731. } else {
  1732. if (combinator !== null) {
  1733. selector.push(combinator);
  1734. } else {
  1735. selector.push(ws);
  1736. }
  1737. selector.push(nextSelector);
  1738. }
  1739. } else {
  1740. break;
  1741. }
  1742. }
  1743. } while (true);
  1744. return new Selector(selector, selector[0].line, selector[0].col);
  1745. },
  1746. //CSS3 Selectors
  1747. _simple_selector_sequence: function() {
  1748. /*
  1749. * simple_selector_sequence
  1750. * : [ type_selector | universal ]
  1751. * [ HASH | class | attrib | pseudo | negation ]*
  1752. * | [ HASH | class | attrib | pseudo | negation ]+
  1753. * ;
  1754. */
  1755. var tokenStream = this._tokenStream,
  1756. //parts of a simple selector
  1757. elementName = null,
  1758. modifiers = [],
  1759. //complete selector text
  1760. selectorText= "",
  1761. //the different parts after the element name to search for
  1762. components = [
  1763. //HASH
  1764. function() {
  1765. return tokenStream.match(Tokens.HASH) ?
  1766. new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
  1767. null;
  1768. },
  1769. this._class,
  1770. this._attrib,
  1771. this._pseudo,
  1772. this._negation
  1773. ],
  1774. i = 0,
  1775. len = components.length,
  1776. component = null,
  1777. line,
  1778. col;
  1779. //get starting line and column for the selector
  1780. line = tokenStream.LT(1).startLine;
  1781. col = tokenStream.LT(1).startCol;
  1782. elementName = this._type_selector();
  1783. if (!elementName) {
  1784. elementName = this._universal();
  1785. }
  1786. if (elementName !== null) {
  1787. selectorText += elementName;
  1788. }
  1789. while (true) {
  1790. //whitespace means we're done
  1791. if (tokenStream.peek() === Tokens.S) {
  1792. break;
  1793. }
  1794. //check for each component
  1795. while (i < len && component === null) {
  1796. component = components[i++].call(this);
  1797. }
  1798. if (component === null) {
  1799. //we don't have a selector
  1800. if (selectorText === "") {
  1801. return null;
  1802. } else {
  1803. break;
  1804. }
  1805. } else {
  1806. i = 0;
  1807. modifiers.push(component);
  1808. selectorText += component.toString();
  1809. component = null;
  1810. }
  1811. }
  1812. return selectorText !== "" ?
  1813. new SelectorPart(elementName, modifiers, selectorText, line, col) :
  1814. null;
  1815. },
  1816. //CSS3 Selectors
  1817. _type_selector: function() {
  1818. /*
  1819. * type_selector
  1820. * : [ namespace_prefix ]? element_name
  1821. * ;
  1822. */
  1823. var tokenStream = this._tokenStream,
  1824. ns = this._namespace_prefix(),
  1825. elementName = this._element_name();
  1826. if (!elementName) {
  1827. /*
  1828. * Need to back out the namespace that was read due to both
  1829. * type_selector and universal reading namespace_prefix
  1830. * first. Kind of hacky, but only way I can figure out
  1831. * right now how to not change the grammar.
  1832. */
  1833. if (ns) {
  1834. tokenStream.unget();
  1835. if (ns.length > 1) {
  1836. tokenStream.unget();
  1837. }
  1838. }
  1839. return null;
  1840. } else {
  1841. if (ns) {
  1842. elementName.text = ns + elementName.text;
  1843. elementName.col -= ns.length;
  1844. }
  1845. return elementName;
  1846. }
  1847. },
  1848. //CSS3 Selectors
  1849. _class: function() {
  1850. /*
  1851. * class
  1852. * : '.' IDENT
  1853. * ;
  1854. */
  1855. var tokenStream = this._tokenStream,
  1856. token;
  1857. if (tokenStream.match(Tokens.DOT)) {
  1858. tokenStream.mustMatch(Tokens.IDENT);
  1859. token = tokenStream.token();
  1860. return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1);
  1861. } else {
  1862. return null;
  1863. }
  1864. },
  1865. //CSS3 Selectors
  1866. _element_name: function() {
  1867. /*
  1868. * element_name
  1869. * : IDENT
  1870. * ;
  1871. */
  1872. var tokenStream = this._tokenStream,
  1873. token;
  1874. if (tokenStream.match(Tokens.IDENT)) {
  1875. token = tokenStream.token();
  1876. return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol);
  1877. } else {
  1878. return null;
  1879. }
  1880. },
  1881. //CSS3 Selectors
  1882. _namespace_prefix: function() {
  1883. /*
  1884. * namespace_prefix
  1885. * : [ IDENT | '*' ]? '|'
  1886. * ;
  1887. */
  1888. var tokenStream = this._tokenStream,
  1889. value = "";
  1890. //verify that this is a namespace prefix
  1891. if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE) {
  1892. if (tokenStream.match([Tokens.IDENT, Tokens.STAR])) {
  1893. value += tokenStream.token().value;
  1894. }
  1895. tokenStream.mustMatch(Tokens.PIPE);
  1896. value += "|";
  1897. }
  1898. return value.length ? value : null;
  1899. },
  1900. //CSS3 Selectors
  1901. _universal: function() {
  1902. /*
  1903. * universal
  1904. * : [ namespace_prefix ]? '*'
  1905. * ;
  1906. */
  1907. var tokenStream = this._tokenStream,
  1908. value = "",
  1909. ns;
  1910. ns = this._namespace_prefix();
  1911. if (ns) {
  1912. value += ns;
  1913. }
  1914. if (tokenStream.match(Tokens.STAR)) {
  1915. value += "*";
  1916. }
  1917. return value.length ? value : null;
  1918. },
  1919. //CSS3 Selectors
  1920. _attrib: function() {
  1921. /*
  1922. * attrib
  1923. * : '[' S* [ namespace_prefix ]? IDENT S*
  1924. * [ [ PREFIXMATCH |
  1925. * SUFFIXMATCH |
  1926. * SUBSTRINGMATCH |
  1927. * '=' |
  1928. * INCLUDES |
  1929. * DASHMATCH ] S* [ IDENT | STRING ] S*
  1930. * ]? ']'
  1931. * ;
  1932. */
  1933. var tokenStream = this._tokenStream,
  1934. value = null,
  1935. ns,
  1936. token;
  1937. if (tokenStream.match(Tokens.LBRACKET)) {
  1938. token = tokenStream.token();
  1939. value = token.value;
  1940. value += this._readWhitespace();
  1941. ns = this._namespace_prefix();
  1942. if (ns) {
  1943. value += ns;
  1944. }
  1945. tokenStream.mustMatch(Tokens.IDENT);
  1946. value += tokenStream.token().value;
  1947. value += this._readWhitespace();
  1948. if (tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH,
  1949. Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])) {
  1950. value += tokenStream.token().value;
  1951. value += this._readWhitespace();
  1952. tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
  1953. value += tokenStream.token().value;
  1954. value += this._readWhitespace();
  1955. }
  1956. tokenStream.mustMatch(Tokens.RBRACKET);
  1957. return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol);
  1958. } else {
  1959. return null;
  1960. }
  1961. },
  1962. //CSS3 Selectors
  1963. _pseudo: function() {
  1964. /*
  1965. * pseudo
  1966. * : ':' ':'? [ IDENT | functional_pseudo ]
  1967. * ;
  1968. */
  1969. var tokenStream = this._tokenStream,
  1970. pseudo = null,
  1971. colons = ":",
  1972. line,
  1973. col;
  1974. if (tokenStream.match(Tokens.COLON)) {
  1975. if (tokenStream.match(Tokens.COLON)) {
  1976. colons += ":";
  1977. }
  1978. if (tokenStream.match(Tokens.IDENT)) {
  1979. pseudo = tokenStream.token().value;
  1980. line = tokenStream.token().startLine;
  1981. col = tokenStream.token().startCol - colons.length;
  1982. } else if (tokenStream.peek() === Tokens.FUNCTION) {
  1983. line = tokenStream.LT(1).startLine;
  1984. col = tokenStream.LT(1).startCol - colons.length;
  1985. pseudo = this._functional_pseudo();
  1986. }
  1987. if (pseudo) {
  1988. pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col);
  1989. } else {
  1990. var startLine = tokenStream.LT(1).startLine,
  1991. startCol = tokenStream.LT(0).startCol;
  1992. throw new SyntaxError("Expected a `FUNCTION` or `IDENT` after colon at line " + startLine + ", col " + startCol + ".", startLine, startCol);
  1993. }
  1994. }
  1995. return pseudo;
  1996. },
  1997. //CSS3 Selectors
  1998. _functional_pseudo: function() {
  1999. /*
  2000. * functional_pseudo
  2001. * : FUNCTION S* expression ')'
  2002. * ;
  2003. */
  2004. var tokenStream = this._tokenStream,
  2005. value = null;
  2006. if (tokenStream.match(Tokens.FUNCTION)) {
  2007. value = tokenStream.token().value;
  2008. value += this._readWhitespace();
  2009. value += this._expression();
  2010. tokenStream.mustMatch(Tokens.RPAREN);
  2011. value += ")";
  2012. }
  2013. return value;
  2014. },
  2015. //CSS3 Selectors
  2016. _expression: function() {
  2017. /*
  2018. * expression
  2019. * : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
  2020. * ;
  2021. */
  2022. var tokenStream = this._tokenStream,
  2023. value = "";
  2024. while (tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION,
  2025. Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH,
  2026. Tokens.FREQ, Tokens.ANGLE, Tokens.TIME,
  2027. Tokens.RESOLUTION, Tokens.SLASH])) {
  2028. value += tokenStream.token().value;
  2029. value += this._readWhitespace();
  2030. }
  2031. return value.length ? value : null;
  2032. },
  2033. //CSS3 Selectors
  2034. _negation: function() {
  2035. /*
  2036. * negation
  2037. * : NOT S* negation_arg S* ')'
  2038. * ;
  2039. */
  2040. var tokenStream = this._tokenStream,
  2041. line,
  2042. col,
  2043. value = "",
  2044. arg,
  2045. subpart = null;
  2046. if (tokenStream.match(Tokens.NOT)) {
  2047. value = tokenStream.token().value;
  2048. line = tokenStream.token().startLine;
  2049. col = tokenStream.token().startCol;
  2050. value += this._readWhitespace();
  2051. arg = this._negation_arg();
  2052. value += arg;
  2053. value += this._readWhitespace();
  2054. tokenStream.match(Tokens.RPAREN);
  2055. value += tokenStream.token().value;
  2056. subpart = new SelectorSubPart(value, "not", line, col);
  2057. subpart.args.push(arg);
  2058. }
  2059. return subpart;
  2060. },
  2061. //CSS3 Selectors
  2062. _negation_arg: function() {
  2063. /*
  2064. * negation_arg
  2065. * : type_selector | universal | HASH | class | attrib | pseudo
  2066. * ;
  2067. */
  2068. var tokenStream = this._tokenStream,
  2069. args = [
  2070. this._type_selector,
  2071. this._universal,
  2072. function() {
  2073. return tokenStream.match(Tokens.HASH) ?
  2074. new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
  2075. null;
  2076. },
  2077. this._class,
  2078. this._attrib,
  2079. this._pseudo
  2080. ],
  2081. arg = null,
  2082. i = 0,
  2083. len = args.length,
  2084. line,
  2085. col,
  2086. part;
  2087. line = tokenStream.LT(1).startLine;
  2088. col = tokenStream.LT(1).startCol;
  2089. while (i < len && arg === null) {
  2090. arg = args[i].call(this);
  2091. i++;
  2092. }
  2093. //must be a negation arg
  2094. if (arg === null) {
  2095. this._unexpectedToken(tokenStream.LT(1));
  2096. }
  2097. //it's an element name
  2098. if (arg.type === "elementName") {
  2099. part = new SelectorPart(arg, [], arg.toString(), line, col);
  2100. } else {
  2101. part = new SelectorPart(null, [arg], arg.toString(), line, col);
  2102. }
  2103. return part;
  2104. },
  2105. _declaration: function() {
  2106. /*
  2107. * declaration
  2108. * : property ':' S* expr prio?
  2109. * | /( empty )/
  2110. * ;
  2111. */
  2112. var tokenStream = this._tokenStream,
  2113. property = null,
  2114. expr = null,
  2115. prio = null,
  2116. invalid = null,
  2117. propertyName= "";
  2118. property = this._property();
  2119. if (property !== null) {
  2120. tokenStream.mustMatch(Tokens.COLON);
  2121. this._readWhitespace();
  2122. expr = this._expr();
  2123. //if there's no parts for the value, it's an error
  2124. if (!expr || expr.length === 0) {
  2125. this._unexpectedToken(tokenStream.LT(1));
  2126. }
  2127. prio = this._prio();
  2128. /*
  2129. * If hacks should be allowed, then only check the root
  2130. * property. If hacks should not be allowed, treat
  2131. * _property or *property as invalid properties.
  2132. */
  2133. propertyName = property.toString();
  2134. if (this.options.starHack && property.hack === "*" ||
  2135. this.options.underscoreHack && property.hack === "_") {
  2136. propertyName = property.text;
  2137. }
  2138. try {
  2139. this._validateProperty(propertyName, expr);
  2140. } catch (ex) {
  2141. invalid = ex;
  2142. }
  2143. this.fire({
  2144. type: "property",
  2145. property: property,
  2146. value: expr,
  2147. important: prio,
  2148. line: property.line,
  2149. col: property.col,
  2150. invalid: invalid
  2151. });
  2152. return true;
  2153. } else {
  2154. return false;
  2155. }
  2156. },
  2157. _prio: function() {
  2158. /*
  2159. * prio
  2160. * : IMPORTANT_SYM S*
  2161. * ;
  2162. */
  2163. var tokenStream = this._tokenStream,
  2164. result = tokenStream.match(Tokens.IMPORTANT_SYM);
  2165. this._readWhitespace();
  2166. return result;
  2167. },
  2168. _expr: function(inFunction) {
  2169. /*
  2170. * expr
  2171. * : term [ operator term ]*
  2172. * ;
  2173. */
  2174. var values = [],
  2175. //valueParts = [],
  2176. value = null,
  2177. operator = null;
  2178. value = this._term(inFunction);
  2179. if (value !== null) {
  2180. values.push(value);
  2181. do {
  2182. operator = this._operator(inFunction);
  2183. //if there's an operator, keep building up the value parts
  2184. if (operator) {
  2185. values.push(operator);
  2186. } /*else {
  2187. //if there's not an operator, you have a full value
  2188. values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
  2189. valueParts = [];
  2190. }*/
  2191. value = this._term(inFunction);
  2192. if (value === null) {
  2193. break;
  2194. } else {
  2195. values.push(value);
  2196. }
  2197. } while (true);
  2198. }
  2199. //cleanup
  2200. /*if (valueParts.length) {
  2201. values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
  2202. }*/
  2203. return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null;
  2204. },
  2205. _term: function(inFunction) {
  2206. /*
  2207. * term
  2208. * : unary_operator?
  2209. * [ NUMBER S* | PERCENTAGE S* | LENGTH S* | ANGLE S* |
  2210. * TIME S* | FREQ S* | function | ie_function ]
  2211. * | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor
  2212. * ;
  2213. */
  2214. var tokenStream = this._tokenStream,
  2215. unary = null,
  2216. value = null,
  2217. endChar = null,
  2218. part = null,
  2219. token,
  2220. line,
  2221. col;
  2222. //returns the operator or null
  2223. unary = this._unary_operator();
  2224. if (unary !== null) {
  2225. line = tokenStream.token().startLine;
  2226. col = tokenStream.token().startCol;
  2227. }
  2228. //exception for IE filters
  2229. if (tokenStream.peek() === Tokens.IE_FUNCTION && this.options.ieFilters) {
  2230. value = this._ie_function();
  2231. if (unary === null) {
  2232. line = tokenStream.token().startLine;
  2233. col = tokenStream.token().startCol;
  2234. }
  2235. //see if it's a simple block
  2236. } else if (inFunction && tokenStream.match([Tokens.LPAREN, Tokens.LBRACE, Tokens.LBRACKET])) {
  2237. token = tokenStream.token();
  2238. endChar = token.endChar;
  2239. value = token.value + this._expr(inFunction).text;
  2240. if (unary === null) {
  2241. line = tokenStream.token().startLine;
  2242. col = tokenStream.token().startCol;
  2243. }
  2244. tokenStream.mustMatch(Tokens.type(endChar));
  2245. value += endChar;
  2246. this._readWhitespace();
  2247. //see if there's a simple match
  2248. } else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
  2249. Tokens.ANGLE, Tokens.TIME,
  2250. Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])) {
  2251. value = tokenStream.token().value;
  2252. if (unary === null) {
  2253. line = tokenStream.token().startLine;
  2254. col = tokenStream.token().startCol;
  2255. // Correct potentially-inaccurate IDENT parsing in
  2256. // PropertyValuePart constructor.
  2257. part = PropertyValuePart.fromToken(tokenStream.token());
  2258. }
  2259. this._readWhitespace();
  2260. } else {
  2261. //see if it's a color
  2262. token = this._hexcolor();
  2263. if (token === null) {
  2264. //if there's no unary, get the start of the next token for line/col info
  2265. if (unary === null) {
  2266. line = tokenStream.LT(1).startLine;
  2267. col = tokenStream.LT(1).startCol;
  2268. }
  2269. //has to be a function
  2270. if (value === null) {
  2271. /*
  2272. * This checks for alpha(opacity=0) style of IE
  2273. * functions. IE_FUNCTION only presents progid: style.
  2274. */
  2275. if (tokenStream.LA(3) === Tokens.EQUALS && this.options.ieFilters) {
  2276. value = this._ie_function();
  2277. } else {
  2278. value = this._function();
  2279. }
  2280. }
  2281. /*if (value === null) {
  2282. return null;
  2283. //throw new Error("Expected identifier at line " + tokenStream.token().startLine + ", character " + tokenStream.token().startCol + ".");
  2284. }*/
  2285. } else {
  2286. value = token.value;
  2287. if (unary === null) {
  2288. line = token.startLine;
  2289. col = token.startCol;
  2290. }
  2291. }
  2292. }
  2293. return part !== null ? part : value !== null ?
  2294. new PropertyValuePart(unary !== null ? unary + value : value, line, col) :
  2295. null;
  2296. },
  2297. _function: function() {
  2298. /*
  2299. * function
  2300. * : FUNCTION S* expr ')' S*
  2301. * ;
  2302. */
  2303. var tokenStream = this._tokenStream,
  2304. functionText = null,
  2305. expr = null,
  2306. lt;
  2307. if (tokenStream.match(Tokens.FUNCTION)) {
  2308. functionText = tokenStream.token().value;
  2309. this._readWhitespace();
  2310. expr = this._expr(true);
  2311. functionText += expr;
  2312. //START: Horrible hack in case it's an IE filter
  2313. if (this.options.ieFilters && tokenStream.peek() === Tokens.EQUALS) {
  2314. do {
  2315. if (this._readWhitespace()) {
  2316. functionText += tokenStream.token().value;
  2317. }
  2318. //might be second time in the loop
  2319. if (tokenStream.LA(0) === Tokens.COMMA) {
  2320. functionText += tokenStream.token().value;
  2321. }
  2322. tokenStream.match(Tokens.IDENT);
  2323. functionText += tokenStream.token().value;
  2324. tokenStream.match(Tokens.EQUALS);
  2325. functionText += tokenStream.token().value;
  2326. //functionText += this._term();
  2327. lt = tokenStream.peek();
  2328. while (lt !== Tokens.COMMA && lt !== Tokens.S && lt !== Tokens.RPAREN) {
  2329. tokenStream.get();
  2330. functionText += tokenStream.token().value;
  2331. lt = tokenStream.peek();
  2332. }
  2333. } while (tokenStream.match([Tokens.COMMA, Tokens.S]));
  2334. }
  2335. //END: Horrible Hack
  2336. tokenStream.match(Tokens.RPAREN);
  2337. functionText += ")";
  2338. this._readWhitespace();
  2339. }
  2340. return functionText;
  2341. },
  2342. _ie_function: function() {
  2343. /* (My own extension)
  2344. * ie_function
  2345. * : IE_FUNCTION S* IDENT '=' term [S* ','? IDENT '=' term]+ ')' S*
  2346. * ;
  2347. */
  2348. var tokenStream = this._tokenStream,
  2349. functionText = null,
  2350. lt;
  2351. //IE function can begin like a regular function, too
  2352. if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])) {
  2353. functionText = tokenStream.token().value;
  2354. do {
  2355. if (this._readWhitespace()) {
  2356. functionText += tokenStream.token().value;
  2357. }
  2358. //might be second time in the loop
  2359. if (tokenStream.LA(0) === Tokens.COMMA) {
  2360. functionText += tokenStream.token().value;
  2361. }
  2362. tokenStream.match(Tokens.IDENT);
  2363. functionText += tokenStream.token().value;
  2364. tokenStream.match(Tokens.EQUALS);
  2365. functionText += tokenStream.token().value;
  2366. //functionText += this._term();
  2367. lt = tokenStream.peek();
  2368. while (lt !== Tokens.COMMA && lt !== Tokens.S && lt !== Tokens.RPAREN) {
  2369. tokenStream.get();
  2370. functionText += tokenStream.token().value;
  2371. lt = tokenStream.peek();
  2372. }
  2373. } while (tokenStream.match([Tokens.COMMA, Tokens.S]));
  2374. tokenStream.match(Tokens.RPAREN);
  2375. functionText += ")";
  2376. this._readWhitespace();
  2377. }
  2378. return functionText;
  2379. },
  2380. _hexcolor: function() {
  2381. /*
  2382. * There is a constraint on the color that it must
  2383. * have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
  2384. * after the "#"; e.g., "#000" is OK, but "#abcd" is not.
  2385. *
  2386. * hexcolor
  2387. * : HASH S*
  2388. * ;
  2389. */
  2390. var tokenStream = this._tokenStream,
  2391. token = null,
  2392. color;
  2393. if (tokenStream.match(Tokens.HASH)) {
  2394. //need to do some validation here
  2395. token = tokenStream.token();
  2396. color = token.value;
  2397. if (!/#[a-f0-9]{3,6}/i.test(color)) {
  2398. throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
  2399. }
  2400. this._readWhitespace();
  2401. }
  2402. return token;
  2403. },
  2404. //-----------------------------------------------------------------
  2405. // Animations methods
  2406. //-----------------------------------------------------------------
  2407. _keyframes: function() {
  2408. /*
  2409. * keyframes:
  2410. * : KEYFRAMES_SYM S* keyframe_name S* '{' S* keyframe_rule* '}' {
  2411. * ;
  2412. */
  2413. var tokenStream = this._tokenStream,
  2414. token,
  2415. tt,
  2416. name,
  2417. prefix = "";
  2418. tokenStream.mustMatch(Tokens.KEYFRAMES_SYM);
  2419. token = tokenStream.token();
  2420. if (/^@\-([^\-]+)\-/.test(token.value)) {
  2421. prefix = RegExp.$1;
  2422. }
  2423. this._readWhitespace();
  2424. name = this._keyframe_name();
  2425. this._readWhitespace();
  2426. tokenStream.mustMatch(Tokens.LBRACE);
  2427. this.fire({
  2428. type: "startkeyframes",
  2429. name: name,
  2430. prefix: prefix,
  2431. line: token.startLine,
  2432. col: token.startCol
  2433. });
  2434. this._readWhitespace();
  2435. tt = tokenStream.peek();
  2436. //check for key
  2437. while (tt === Tokens.IDENT || tt === Tokens.PERCENTAGE) {
  2438. this._keyframe_rule();
  2439. this._readWhitespace();
  2440. tt = tokenStream.peek();
  2441. }
  2442. this.fire({
  2443. type: "endkeyframes",
  2444. name: name,
  2445. prefix: prefix,
  2446. line: token.startLine,
  2447. col: token.startCol
  2448. });
  2449. this._readWhitespace();
  2450. tokenStream.mustMatch(Tokens.RBRACE);
  2451. this._readWhitespace();
  2452. },
  2453. _keyframe_name: function() {
  2454. /*
  2455. * keyframe_name:
  2456. * : IDENT
  2457. * | STRING
  2458. * ;
  2459. */
  2460. var tokenStream = this._tokenStream;
  2461. tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
  2462. return SyntaxUnit.fromToken(tokenStream.token());
  2463. },
  2464. _keyframe_rule: function() {
  2465. /*
  2466. * keyframe_rule:
  2467. * : key_list S*
  2468. * '{' S* declaration [ ';' S* declaration ]* '}' S*
  2469. * ;
  2470. */
  2471. var keyList = this._key_list();
  2472. this.fire({
  2473. type: "startkeyframerule",
  2474. keys: keyList,
  2475. line: keyList[0].line,
  2476. col: keyList[0].col
  2477. });
  2478. this._readDeclarations(true);
  2479. this.fire({
  2480. type: "endkeyframerule",
  2481. keys: keyList,
  2482. line: keyList[0].line,
  2483. col: keyList[0].col
  2484. });
  2485. },
  2486. _key_list: function() {
  2487. /*
  2488. * key_list:
  2489. * : key [ S* ',' S* key]*
  2490. * ;
  2491. */
  2492. var tokenStream = this._tokenStream,
  2493. keyList = [];
  2494. //must be least one key
  2495. keyList.push(this._key());
  2496. this._readWhitespace();
  2497. while (tokenStream.match(Tokens.COMMA)) {
  2498. this._readWhitespace();
  2499. keyList.push(this._key());
  2500. this._readWhitespace();
  2501. }
  2502. return keyList;
  2503. },
  2504. _key: function() {
  2505. /*
  2506. * There is a restriction that IDENT can be only "from" or "to".
  2507. *
  2508. * key
  2509. * : PERCENTAGE
  2510. * | IDENT
  2511. * ;
  2512. */
  2513. var tokenStream = this._tokenStream,
  2514. token;
  2515. if (tokenStream.match(Tokens.PERCENTAGE)) {
  2516. return SyntaxUnit.fromToken(tokenStream.token());
  2517. } else if (tokenStream.match(Tokens.IDENT)) {
  2518. token = tokenStream.token();
  2519. if (/from|to/i.test(token.value)) {
  2520. return SyntaxUnit.fromToken(token);
  2521. }
  2522. tokenStream.unget();
  2523. }
  2524. //if it gets here, there wasn't a valid token, so time to explode
  2525. this._unexpectedToken(tokenStream.LT(1));
  2526. },
  2527. //-----------------------------------------------------------------
  2528. // Helper methods
  2529. //-----------------------------------------------------------------
  2530. /**
  2531. * Not part of CSS grammar, but useful for skipping over
  2532. * combination of white space and HTML-style comments.
  2533. * @return {void}
  2534. * @method _skipCruft
  2535. * @private
  2536. */
  2537. _skipCruft: function() {
  2538. while (this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])) {
  2539. //noop
  2540. }
  2541. },
  2542. /**
  2543. * Not part of CSS grammar, but this pattern occurs frequently
  2544. * in the official CSS grammar. Split out here to eliminate
  2545. * duplicate code.
  2546. * @param {Boolean} checkStart Indicates if the rule should check
  2547. * for the left brace at the beginning.
  2548. * @param {Boolean} readMargins Indicates if the rule should check
  2549. * for margin patterns.
  2550. * @return {void}
  2551. * @method _readDeclarations
  2552. * @private
  2553. */
  2554. _readDeclarations: function(checkStart, readMargins) {
  2555. /*
  2556. * Reads the pattern
  2557. * S* '{' S* declaration [ ';' S* declaration ]* '}' S*
  2558. * or
  2559. * S* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
  2560. * Note that this is how it is described in CSS3 Paged Media, but is actually incorrect.
  2561. * A semicolon is only necessary following a declaration if there's another declaration
  2562. * or margin afterwards.
  2563. */
  2564. var tokenStream = this._tokenStream,
  2565. tt;
  2566. this._readWhitespace();
  2567. if (checkStart) {
  2568. tokenStream.mustMatch(Tokens.LBRACE);
  2569. }
  2570. this._readWhitespace();
  2571. try {
  2572. while (true) {
  2573. if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())) {
  2574. //noop
  2575. } else if (this._declaration()) {
  2576. if (!tokenStream.match(Tokens.SEMICOLON)) {
  2577. break;
  2578. }
  2579. } else {
  2580. break;
  2581. }
  2582. //if ((!this._margin() && !this._declaration()) || !tokenStream.match(Tokens.SEMICOLON)){
  2583. // break;
  2584. //}
  2585. this._readWhitespace();
  2586. }
  2587. tokenStream.mustMatch(Tokens.RBRACE);
  2588. this._readWhitespace();
  2589. } catch (ex) {
  2590. if (ex instanceof SyntaxError && !this.options.strict) {
  2591. //fire error event
  2592. this.fire({
  2593. type: "error",
  2594. error: ex,
  2595. message: ex.message,
  2596. line: ex.line,
  2597. col: ex.col
  2598. });
  2599. //see if there's another declaration
  2600. tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]);
  2601. if (tt === Tokens.SEMICOLON) {
  2602. //if there's a semicolon, then there might be another declaration
  2603. this._readDeclarations(false, readMargins);
  2604. } else if (tt !== Tokens.RBRACE) {
  2605. //if there's a right brace, the rule is finished so don't do anything
  2606. //otherwise, rethrow the error because it wasn't handled properly
  2607. throw ex;
  2608. }
  2609. } else {
  2610. //not a syntax error, rethrow it
  2611. throw ex;
  2612. }
  2613. }
  2614. },
  2615. /**
  2616. * In some cases, you can end up with two white space tokens in a
  2617. * row. Instead of making a change in every function that looks for
  2618. * white space, this function is used to match as much white space
  2619. * as necessary.
  2620. * @method _readWhitespace
  2621. * @return {String} The white space if found, empty string if not.
  2622. * @private
  2623. */
  2624. _readWhitespace: function() {
  2625. var tokenStream = this._tokenStream,
  2626. ws = "";
  2627. while (tokenStream.match(Tokens.S)) {
  2628. ws += tokenStream.token().value;
  2629. }
  2630. return ws;
  2631. },
  2632. /**
  2633. * Throws an error when an unexpected token is found.
  2634. * @param {Object} token The token that was found.
  2635. * @method _unexpectedToken
  2636. * @return {void}
  2637. * @private
  2638. */
  2639. _unexpectedToken: function(token) {
  2640. throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
  2641. },
  2642. /**
  2643. * Helper method used for parsing subparts of a style sheet.
  2644. * @return {void}
  2645. * @method _verifyEnd
  2646. * @private
  2647. */
  2648. _verifyEnd: function() {
  2649. if (this._tokenStream.LA(1) !== Tokens.EOF) {
  2650. this._unexpectedToken(this._tokenStream.LT(1));
  2651. }
  2652. },
  2653. //-----------------------------------------------------------------
  2654. // Validation methods
  2655. //-----------------------------------------------------------------
  2656. _validateProperty: function(property, value) {
  2657. Validation.validate(property, value);
  2658. },
  2659. //-----------------------------------------------------------------
  2660. // Parsing methods
  2661. //-----------------------------------------------------------------
  2662. parse: function(input) {
  2663. this._tokenStream = new TokenStream(input, Tokens);
  2664. this._stylesheet();
  2665. },
  2666. parseStyleSheet: function(input) {
  2667. //just passthrough
  2668. return this.parse(input);
  2669. },
  2670. parseMediaQuery: function(input) {
  2671. this._tokenStream = new TokenStream(input, Tokens);
  2672. var result = this._media_query();
  2673. //if there's anything more, then it's an invalid selector
  2674. this._verifyEnd();
  2675. //otherwise return result
  2676. return result;
  2677. },
  2678. /**
  2679. * Parses a property value (everything after the semicolon).
  2680. * @return {parserlib.css.PropertyValue} The property value.
  2681. * @throws parserlib.util.SyntaxError If an unexpected token is found.
  2682. * @method parserPropertyValue
  2683. */
  2684. parsePropertyValue: function(input) {
  2685. this._tokenStream = new TokenStream(input, Tokens);
  2686. this._readWhitespace();
  2687. var result = this._expr();
  2688. //okay to have a trailing white space
  2689. this._readWhitespace();
  2690. //if there's anything more, then it's an invalid selector
  2691. this._verifyEnd();
  2692. //otherwise return result
  2693. return result;
  2694. },
  2695. /**
  2696. * Parses a complete CSS rule, including selectors and
  2697. * properties.
  2698. * @param {String} input The text to parser.
  2699. * @return {Boolean} True if the parse completed successfully, false if not.
  2700. * @method parseRule
  2701. */
  2702. parseRule: function(input) {
  2703. this._tokenStream = new TokenStream(input, Tokens);
  2704. //skip any leading white space
  2705. this._readWhitespace();
  2706. var result = this._ruleset();
  2707. //skip any trailing white space
  2708. this._readWhitespace();
  2709. //if there's anything more, then it's an invalid selector
  2710. this._verifyEnd();
  2711. //otherwise return result
  2712. return result;
  2713. },
  2714. /**
  2715. * Parses a single CSS selector (no comma)
  2716. * @param {String} input The text to parse as a CSS selector.
  2717. * @return {Selector} An object representing the selector.
  2718. * @throws parserlib.util.SyntaxError If an unexpected token is found.
  2719. * @method parseSelector
  2720. */
  2721. parseSelector: function(input) {
  2722. this._tokenStream = new TokenStream(input, Tokens);
  2723. //skip any leading white space
  2724. this._readWhitespace();
  2725. var result = this._selector();
  2726. //skip any trailing white space
  2727. this._readWhitespace();
  2728. //if there's anything more, then it's an invalid selector
  2729. this._verifyEnd();
  2730. //otherwise return result
  2731. return result;
  2732. },
  2733. /**
  2734. * Parses an HTML style attribute: a set of CSS declarations
  2735. * separated by semicolons.
  2736. * @param {String} input The text to parse as a style attribute
  2737. * @return {void}
  2738. * @method parseStyleAttribute
  2739. */
  2740. parseStyleAttribute: function(input) {
  2741. input += "}"; // for error recovery in _readDeclarations()
  2742. this._tokenStream = new TokenStream(input, Tokens);
  2743. this._readDeclarations();
  2744. }
  2745. };
  2746. //copy over onto prototype
  2747. for (prop in additions) {
  2748. if (Object.prototype.hasOwnProperty.call(additions, prop)) {
  2749. proto[prop] = additions[prop];
  2750. }
  2751. }
  2752. return proto;
  2753. }();
  2754. /*
  2755. nth
  2756. : S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? |
  2757. ['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S*
  2758. ;
  2759. */
  2760. },{"../util/EventTarget":23,"../util/SyntaxError":25,"../util/SyntaxUnit":26,"./Combinator":2,"./MediaFeature":4,"./MediaQuery":5,"./PropertyName":8,"./PropertyValue":9,"./PropertyValuePart":11,"./Selector":13,"./SelectorPart":14,"./SelectorSubPart":15,"./TokenStream":17,"./Tokens":18,"./Validation":19}],7:[function(require,module,exports){
  2761. "use strict";
  2762. /* exported Properties */
  2763. var Properties = module.exports = {
  2764. __proto__: null,
  2765. //A
  2766. "align-items" : "flex-start | flex-end | center | baseline | stretch",
  2767. "align-content" : "flex-start | flex-end | center | space-between | space-around | stretch",
  2768. "align-self" : "auto | flex-start | flex-end | center | baseline | stretch",
  2769. "all" : "initial | inherit | unset",
  2770. "-webkit-align-items" : "flex-start | flex-end | center | baseline | stretch",
  2771. "-webkit-align-content" : "flex-start | flex-end | center | space-between | space-around | stretch",
  2772. "-webkit-align-self" : "auto | flex-start | flex-end | center | baseline | stretch",
  2773. "alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>",
  2774. "alignment-baseline" : "auto | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
  2775. "animation" : 1,
  2776. "animation-delay" : "<time>#",
  2777. "animation-direction" : "<single-animation-direction>#",
  2778. "animation-duration" : "<time>#",
  2779. "animation-fill-mode" : "[ none | forwards | backwards | both ]#",
  2780. "animation-iteration-count" : "[ <number> | infinite ]#",
  2781. "animation-name" : "[ none | <single-animation-name> ]#",
  2782. "animation-play-state" : "[ running | paused ]#",
  2783. "animation-timing-function" : 1,
  2784. //vendor prefixed
  2785. "-moz-animation-delay" : "<time>#",
  2786. "-moz-animation-direction" : "[ normal | alternate ]#",
  2787. "-moz-animation-duration" : "<time>#",
  2788. "-moz-animation-iteration-count" : "[ <number> | infinite ]#",
  2789. "-moz-animation-name" : "[ none | <single-animation-name> ]#",
  2790. "-moz-animation-play-state" : "[ running | paused ]#",
  2791. "-ms-animation-delay" : "<time>#",
  2792. "-ms-animation-direction" : "[ normal | alternate ]#",
  2793. "-ms-animation-duration" : "<time>#",
  2794. "-ms-animation-iteration-count" : "[ <number> | infinite ]#",
  2795. "-ms-animation-name" : "[ none | <single-animation-name> ]#",
  2796. "-ms-animation-play-state" : "[ running | paused ]#",
  2797. "-webkit-animation-delay" : "<time>#",
  2798. "-webkit-animation-direction" : "[ normal | alternate ]#",
  2799. "-webkit-animation-duration" : "<time>#",
  2800. "-webkit-animation-fill-mode" : "[ none | forwards | backwards | both ]#",
  2801. "-webkit-animation-iteration-count" : "[ <number> | infinite ]#",
  2802. "-webkit-animation-name" : "[ none | <single-animation-name> ]#",
  2803. "-webkit-animation-play-state" : "[ running | paused ]#",
  2804. "-o-animation-delay" : "<time>#",
  2805. "-o-animation-direction" : "[ normal | alternate ]#",
  2806. "-o-animation-duration" : "<time>#",
  2807. "-o-animation-iteration-count" : "[ <number> | infinite ]#",
  2808. "-o-animation-name" : "[ none | <single-animation-name> ]#",
  2809. "-o-animation-play-state" : "[ running | paused ]#",
  2810. "appearance" : "none | auto",
  2811. "-moz-appearance" : "none | button | button-arrow-down | button-arrow-next | button-arrow-previous | button-arrow-up | button-bevel | button-focus | caret | checkbox | checkbox-container | checkbox-label | checkmenuitem | dualbutton | groupbox | listbox | listitem | menuarrow | menubar | menucheckbox | menuimage | menuitem | menuitemtext | menulist | menulist-button | menulist-text | menulist-textfield | menupopup | menuradio | menuseparator | meterbar | meterchunk | progressbar | progressbar-vertical | progresschunk | progresschunk-vertical | radio | radio-container | radio-label | radiomenuitem | range | range-thumb | resizer | resizerpanel | scale-horizontal | scalethumbend | scalethumb-horizontal | scalethumbstart | scalethumbtick | scalethumb-vertical | scale-vertical | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | separator | sheet | spinner | spinner-downbutton | spinner-textfield | spinner-upbutton | splitter | statusbar | statusbarpanel | tab | tabpanel | tabpanels | tab-scroll-arrow-back | tab-scroll-arrow-forward | textfield | textfield-multiline | toolbar | toolbarbutton | toolbarbutton-dropdown | toolbargripper | toolbox | tooltip | treeheader | treeheadercell | treeheadersortarrow | treeitem | treeline | treetwisty | treetwistyopen | treeview | -moz-mac-unified-toolbar | -moz-win-borderless-glass | -moz-win-browsertabbar-toolbox | -moz-win-communicationstext | -moz-win-communications-toolbox | -moz-win-exclude-glass | -moz-win-glass | -moz-win-mediatext | -moz-win-media-toolbox | -moz-window-button-box | -moz-window-button-box-maximized | -moz-window-button-close | -moz-window-button-maximize | -moz-window-button-minimize | -moz-window-button-restore | -moz-window-frame-bottom | -moz-window-frame-left | -moz-window-frame-right | -moz-window-titlebar | -moz-window-titlebar-maximized",
  2812. "-ms-appearance" : "none | icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal",
  2813. "-webkit-appearance" : "none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | listbox | listitem | media-fullscreen-button | media-mute-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | push-button | radio | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical",
  2814. "-o-appearance" : "none | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal",
  2815. "azimuth" : "<azimuth>",
  2816. //B
  2817. "backface-visibility" : "visible | hidden",
  2818. "background" : 1,
  2819. "background-attachment" : "<attachment>#",
  2820. "background-clip" : "<box>#",
  2821. "background-color" : "<color>",
  2822. "background-image" : "<bg-image>#",
  2823. "background-origin" : "<box>#",
  2824. "background-position" : "<bg-position>",
  2825. "background-repeat" : "<repeat-style>#",
  2826. "background-size" : "<bg-size>#",
  2827. "baseline-shift" : "baseline | sub | super | <percentage> | <length>",
  2828. "behavior" : 1,
  2829. "binding" : 1,
  2830. "bleed" : "<length>",
  2831. "bookmark-label" : "<content> | <attr> | <string>",
  2832. "bookmark-level" : "none | <integer>",
  2833. "bookmark-state" : "open | closed",
  2834. "bookmark-target" : "none | <uri> | <attr>",
  2835. "border" : "<border-width> || <border-style> || <color>",
  2836. "border-bottom" : "<border-width> || <border-style> || <color>",
  2837. "border-bottom-color" : "<color>",
  2838. "border-bottom-left-radius" : "<x-one-radius>",
  2839. "border-bottom-right-radius" : "<x-one-radius>",
  2840. "border-bottom-style" : "<border-style>",
  2841. "border-bottom-width" : "<border-width>",
  2842. "border-collapse" : "collapse | separate",
  2843. "border-color" : "<color>{1,4}",
  2844. "border-image" : 1,
  2845. "border-image-outset" : "[ <length> | <number> ]{1,4}",
  2846. "border-image-repeat" : "[ stretch | repeat | round ]{1,2}",
  2847. "border-image-slice" : "<border-image-slice>",
  2848. "border-image-source" : "<image> | none",
  2849. "border-image-width" : "[ <length> | <percentage> | <number> | auto ]{1,4}",
  2850. "border-left" : "<border-width> || <border-style> || <color>",
  2851. "border-left-color" : "<color>",
  2852. "border-left-style" : "<border-style>",
  2853. "border-left-width" : "<border-width>",
  2854. "border-radius" : "<border-radius>",
  2855. "border-right" : "<border-width> || <border-style> || <color>",
  2856. "border-right-color" : "<color>",
  2857. "border-right-style" : "<border-style>",
  2858. "border-right-width" : "<border-width>",
  2859. "border-spacing" : "<length>{1,2}",
  2860. "border-style" : "<border-style>{1,4}",
  2861. "border-top" : "<border-width> || <border-style> || <color>",
  2862. "border-top-color" : "<color>",
  2863. "border-top-left-radius" : "<x-one-radius>",
  2864. "border-top-right-radius" : "<x-one-radius>",
  2865. "border-top-style" : "<border-style>",
  2866. "border-top-width" : "<border-width>",
  2867. "border-width" : "<border-width>{1,4}",
  2868. "bottom" : "<margin-width>",
  2869. "-moz-box-align" : "start | end | center | baseline | stretch",
  2870. "-moz-box-decoration-break" : "slice | clone",
  2871. "-moz-box-direction" : "normal | reverse",
  2872. "-moz-box-flex" : "<number>",
  2873. "-moz-box-flex-group" : "<integer>",
  2874. "-moz-box-lines" : "single | multiple",
  2875. "-moz-box-ordinal-group" : "<integer>",
  2876. "-moz-box-orient" : "horizontal | vertical | inline-axis | block-axis",
  2877. "-moz-box-pack" : "start | end | center | justify",
  2878. "-o-box-decoration-break" : "slice | clone",
  2879. "-webkit-box-align" : "start | end | center | baseline | stretch",
  2880. "-webkit-box-decoration-break" : "slice | clone",
  2881. "-webkit-box-direction" : "normal | reverse",
  2882. "-webkit-box-flex" : "<number>",
  2883. "-webkit-box-flex-group" : "<integer>",
  2884. "-webkit-box-lines" : "single | multiple",
  2885. "-webkit-box-ordinal-group" : "<integer>",
  2886. "-webkit-box-orient" : "horizontal | vertical | inline-axis | block-axis",
  2887. "-webkit-box-pack" : "start | end | center | justify",
  2888. "box-decoration-break" : "slice | clone",
  2889. "box-shadow" : "<box-shadow>",
  2890. "box-sizing" : "content-box | border-box",
  2891. "break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
  2892. "break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
  2893. "break-inside" : "auto | avoid | avoid-page | avoid-column",
  2894. //C
  2895. "caption-side" : "top | bottom",
  2896. "clear" : "none | right | left | both",
  2897. "clip" : "<shape> | auto",
  2898. "-webkit-clip-path" : "<clip-source> | <clip-path> | none",
  2899. "clip-path" : "<clip-source> | <clip-path> | none",
  2900. "clip-rule" : "nonzero | evenodd",
  2901. "color" : "<color>",
  2902. "color-interpolation" : "auto | sRGB | linearRGB",
  2903. "color-interpolation-filters" : "auto | sRGB | linearRGB",
  2904. "color-profile" : 1,
  2905. "color-rendering" : "auto | optimizeSpeed | optimizeQuality",
  2906. "column-count" : "<integer> | auto", //https://www.w3.org/TR/css3-multicol/
  2907. "column-fill" : "auto | balance",
  2908. "column-gap" : "<length> | normal",
  2909. "column-rule" : "<border-width> || <border-style> || <color>",
  2910. "column-rule-color" : "<color>",
  2911. "column-rule-style" : "<border-style>",
  2912. "column-rule-width" : "<border-width>",
  2913. "column-span" : "none | all",
  2914. "column-width" : "<length> | auto",
  2915. "columns" : 1,
  2916. "content" : 1,
  2917. "counter-increment" : 1,
  2918. "counter-reset" : 1,
  2919. "crop" : "<shape> | auto",
  2920. "cue" : "cue-after | cue-before",
  2921. "cue-after" : 1,
  2922. "cue-before" : 1,
  2923. "cursor" : 1,
  2924. //D
  2925. "direction" : "ltr | rtl",
  2926. "display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | grid | inline-grid | run-in | ruby | ruby-base | ruby-text | ruby-base-container | ruby-text-container | contents | none | -moz-box | -moz-inline-block | -moz-inline-box | -moz-inline-grid | -moz-inline-stack | -moz-inline-table | -moz-grid | -moz-grid-group | -moz-grid-line | -moz-groupbox | -moz-deck | -moz-popup | -moz-stack | -moz-marker | -webkit-box | -webkit-inline-box | -ms-flexbox | -ms-inline-flexbox | flex | -webkit-flex | inline-flex | -webkit-inline-flex",
  2927. "dominant-baseline" : "auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge",
  2928. "drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>",
  2929. "drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
  2930. "drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>",
  2931. "drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
  2932. "drop-initial-size" : "auto | line | <length> | <percentage>",
  2933. "drop-initial-value" : "<integer>",
  2934. //E
  2935. "elevation" : "<angle> | below | level | above | higher | lower",
  2936. "empty-cells" : "show | hide",
  2937. "enable-background" : 1,
  2938. //F
  2939. "fill" : "<paint>",
  2940. "fill-opacity" : "<opacity-value>",
  2941. "fill-rule" : "nonzero | evenodd",
  2942. "filter" : "<filter-function-list> | none",
  2943. "fit" : "fill | hidden | meet | slice",
  2944. "fit-position" : 1,
  2945. "flex" : "<flex>",
  2946. "flex-basis" : "<width>",
  2947. "flex-direction" : "row | row-reverse | column | column-reverse",
  2948. "flex-flow" : "<flex-direction> || <flex-wrap>",
  2949. "flex-grow" : "<number>",
  2950. "flex-shrink" : "<number>",
  2951. "flex-wrap" : "nowrap | wrap | wrap-reverse",
  2952. "-webkit-flex" : "<flex>",
  2953. "-webkit-flex-basis" : "<width>",
  2954. "-webkit-flex-direction" : "row | row-reverse | column | column-reverse",
  2955. "-webkit-flex-flow" : "<flex-direction> || <flex-wrap>",
  2956. "-webkit-flex-grow" : "<number>",
  2957. "-webkit-flex-shrink" : "<number>",
  2958. "-webkit-flex-wrap" : "nowrap | wrap | wrap-reverse",
  2959. "-ms-flex" : "<flex>",
  2960. "-ms-flex-align" : "start | end | center | stretch | baseline",
  2961. "-ms-flex-direction" : "row | row-reverse | column | column-reverse",
  2962. "-ms-flex-order" : "<number>",
  2963. "-ms-flex-pack" : "start | end | center | justify",
  2964. "-ms-flex-wrap" : "nowrap | wrap | wrap-reverse",
  2965. "float" : "left | right | none",
  2966. "float-offset" : 1,
  2967. "flood-color" : 1,
  2968. "flood-opacity" : "<opacity-value>",
  2969. "font" : "<font-shorthand> | caption | icon | menu | message-box | small-caption | status-bar",
  2970. "font-family" : "<font-family>",
  2971. "font-feature-settings" : "<feature-tag-value> | normal",
  2972. "font-kerning" : "auto | normal | none",
  2973. "font-size" : "<font-size>",
  2974. "font-size-adjust" : "<number> | none",
  2975. "font-stretch" : "<font-stretch>",
  2976. "font-style" : "<font-style>",
  2977. "font-variant" : "<font-variant> | normal | none",
  2978. "font-variant-alternates" : "<font-variant-alternates> | normal",
  2979. "font-variant-caps" : "<font-variant-caps> | normal",
  2980. "font-variant-east-asian" : "<font-variant-east-asian> | normal",
  2981. "font-variant-ligatures" : "<font-variant-ligatures> | normal | none",
  2982. "font-variant-numeric" : "<font-variant-numeric> | normal",
  2983. "font-variant-position" : "normal | sub | super",
  2984. "font-weight" : "<font-weight>",
  2985. //G
  2986. "glyph-orientation-horizontal" : "<glyph-angle>",
  2987. "glyph-orientation-vertical" : "auto | <glyph-angle>",
  2988. "grid" : 1,
  2989. "grid-area" : 1,
  2990. "grid-auto-columns" : 1,
  2991. "grid-auto-flow" : 1,
  2992. "grid-auto-position" : 1,
  2993. "grid-auto-rows" : 1,
  2994. "grid-cell-stacking" : "columns | rows | layer",
  2995. "grid-column" : 1,
  2996. "grid-columns" : 1,
  2997. "grid-column-align" : "start | end | center | stretch",
  2998. "grid-column-sizing" : 1,
  2999. "grid-column-start" : 1,
  3000. "grid-column-end" : 1,
  3001. "grid-column-span" : "<integer>",
  3002. "grid-flow" : "none | rows | columns",
  3003. "grid-layer" : "<integer>",
  3004. "grid-row" : 1,
  3005. "grid-rows" : 1,
  3006. "grid-row-align" : "start | end | center | stretch",
  3007. "grid-row-start" : 1,
  3008. "grid-row-end" : 1,
  3009. "grid-row-span" : "<integer>",
  3010. "grid-row-sizing" : 1,
  3011. "grid-template" : 1,
  3012. "grid-template-areas" : 1,
  3013. "grid-template-columns" : 1,
  3014. "grid-template-rows" : 1,
  3015. //H
  3016. "hanging-punctuation" : 1,
  3017. "height" : "<margin-width> | <content-sizing>",
  3018. "hyphenate-after" : "<integer> | auto",
  3019. "hyphenate-before" : "<integer> | auto",
  3020. "hyphenate-character" : "<string> | auto",
  3021. "hyphenate-lines" : "no-limit | <integer>",
  3022. "hyphenate-resource" : 1,
  3023. "hyphens" : "none | manual | auto",
  3024. //I
  3025. "icon" : 1,
  3026. "image-orientation" : "angle | auto",
  3027. "image-rendering" : "auto | optimizeSpeed | optimizeQuality",
  3028. "image-resolution" : 1,
  3029. "ime-mode" : "auto | normal | active | inactive | disabled",
  3030. "inline-box-align" : "last | <integer>",
  3031. //J
  3032. "justify-content" : "flex-start | flex-end | center | space-between | space-around",
  3033. "-webkit-justify-content" : "flex-start | flex-end | center | space-between | space-around",
  3034. //K
  3035. "kerning" : "auto | <length>",
  3036. //L
  3037. "left" : "<margin-width>",
  3038. "letter-spacing" : "<length> | normal",
  3039. "line-height" : "<line-height>",
  3040. "line-break" : "auto | loose | normal | strict",
  3041. "line-stacking" : 1,
  3042. "line-stacking-ruby" : "exclude-ruby | include-ruby",
  3043. "line-stacking-shift" : "consider-shifts | disregard-shifts",
  3044. "line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height",
  3045. "list-style" : 1,
  3046. "list-style-image" : "<uri> | none",
  3047. "list-style-position" : "inside | outside",
  3048. "list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none",
  3049. //M
  3050. "margin" : "<margin-width>{1,4}",
  3051. "margin-bottom" : "<margin-width>",
  3052. "margin-left" : "<margin-width>",
  3053. "margin-right" : "<margin-width>",
  3054. "margin-top" : "<margin-width>",
  3055. "mark" : 1,
  3056. "mark-after" : 1,
  3057. "mark-before" : 1,
  3058. "marker" : 1,
  3059. "marker-end" : 1,
  3060. "marker-mid" : 1,
  3061. "marker-start" : 1,
  3062. "marks" : 1,
  3063. "marquee-direction" : 1,
  3064. "marquee-play-count" : 1,
  3065. "marquee-speed" : 1,
  3066. "marquee-style" : 1,
  3067. "mask" : 1,
  3068. "max-height" : "<length> | <percentage> | <content-sizing> | none",
  3069. "max-width" : "<length> | <percentage> | <content-sizing> | none",
  3070. "min-height" : "<length> | <percentage> | <content-sizing> | contain-floats | -moz-contain-floats | -webkit-contain-floats",
  3071. "min-width" : "<length> | <percentage> | <content-sizing> | contain-floats | -moz-contain-floats | -webkit-contain-floats",
  3072. "move-to" : 1,
  3073. //N
  3074. "nav-down" : 1,
  3075. "nav-index" : 1,
  3076. "nav-left" : 1,
  3077. "nav-right" : 1,
  3078. "nav-up" : 1,
  3079. //O
  3080. "object-fit" : "fill | contain | cover | none | scale-down",
  3081. "object-position" : "<position>",
  3082. "opacity" : "<opacity-value>",
  3083. "order" : "<integer>",
  3084. "-webkit-order" : "<integer>",
  3085. "orphans" : "<integer>",
  3086. "outline" : 1,
  3087. "outline-color" : "<color> | invert",
  3088. "outline-offset" : 1,
  3089. "outline-style" : "<border-style>",
  3090. "outline-width" : "<border-width>",
  3091. "overflow" : "visible | hidden | scroll | auto",
  3092. "overflow-style" : 1,
  3093. "overflow-wrap" : "normal | break-word",
  3094. "overflow-x" : 1,
  3095. "overflow-y" : 1,
  3096. //P
  3097. "padding" : "<padding-width>{1,4}",
  3098. "padding-bottom" : "<padding-width>",
  3099. "padding-left" : "<padding-width>",
  3100. "padding-right" : "<padding-width>",
  3101. "padding-top" : "<padding-width>",
  3102. "page" : 1,
  3103. "page-break-after" : "auto | always | avoid | left | right",
  3104. "page-break-before" : "auto | always | avoid | left | right",
  3105. "page-break-inside" : "auto | avoid",
  3106. "page-policy" : 1,
  3107. "pause" : 1,
  3108. "pause-after" : 1,
  3109. "pause-before" : 1,
  3110. "perspective" : 1,
  3111. "perspective-origin" : 1,
  3112. "phonemes" : 1,
  3113. "pitch" : 1,
  3114. "pitch-range" : 1,
  3115. "play-during" : 1,
  3116. "pointer-events" : "auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all",
  3117. "position" : "static | relative | absolute | fixed",
  3118. "presentation-level" : 1,
  3119. "punctuation-trim" : 1,
  3120. //Q
  3121. "quotes" : 1,
  3122. //R
  3123. "rendering-intent" : 1,
  3124. "resize" : 1,
  3125. "rest" : 1,
  3126. "rest-after" : 1,
  3127. "rest-before" : 1,
  3128. "richness" : 1,
  3129. "right" : "<margin-width>",
  3130. "rotation" : 1,
  3131. "rotation-point" : 1,
  3132. "ruby-align" : 1,
  3133. "ruby-overhang" : 1,
  3134. "ruby-position" : 1,
  3135. "ruby-span" : 1,
  3136. //S
  3137. "shape-rendering" : "auto | optimizeSpeed | crispEdges | geometricPrecision",
  3138. "size" : 1,
  3139. "speak" : "normal | none | spell-out",
  3140. "speak-header" : "once | always",
  3141. "speak-numeral" : "digits | continuous",
  3142. "speak-punctuation" : "code | none",
  3143. "speech-rate" : 1,
  3144. "src" : 1,
  3145. "stop-color" : 1,
  3146. "stop-opacity" : "<opacity-value>",
  3147. "stress" : 1,
  3148. "string-set" : 1,
  3149. "stroke" : "<paint>",
  3150. "stroke-dasharray" : "none | <dasharray>",
  3151. "stroke-dashoffset" : "<percentage> | <length>",
  3152. "stroke-linecap" : "butt | round | square",
  3153. "stroke-linejoin" : "miter | round | bevel",
  3154. "stroke-miterlimit" : "<miterlimit>",
  3155. "stroke-opacity" : "<opacity-value>",
  3156. "stroke-width" : "<percentage> | <length>",
  3157. "table-layout" : "auto | fixed",
  3158. "tab-size" : "<integer> | <length>",
  3159. "target" : 1,
  3160. "target-name" : 1,
  3161. "target-new" : 1,
  3162. "target-position" : 1,
  3163. "text-align" : "left | right | center | justify | match-parent | start | end",
  3164. "text-align-last" : 1,
  3165. "text-anchor" : "start | middle | end",
  3166. "text-decoration" : "<text-decoration-line> || <text-decoration-style> || <text-decoration-color>",
  3167. "text-decoration-color" : "<text-decoration-color>",
  3168. "text-decoration-line" : "<text-decoration-line>",
  3169. "text-decoration-style" : "<text-decoration-style>",
  3170. "text-emphasis" : 1,
  3171. "text-height" : 1,
  3172. "text-indent" : "<length> | <percentage>",
  3173. "text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida",
  3174. "text-outline" : 1,
  3175. "text-overflow" : 1,
  3176. "text-rendering" : "auto | optimizeSpeed | optimizeLegibility | geometricPrecision",
  3177. "text-shadow" : 1,
  3178. "text-transform" : "capitalize | uppercase | lowercase | none",
  3179. "text-wrap" : "normal | none | avoid",
  3180. "top" : "<margin-width>",
  3181. "-ms-touch-action" : "auto | none | pan-x | pan-y | pan-left | pan-right | pan-up | pan-down | manipulation",
  3182. "touch-action" : "auto | none | pan-x | pan-y | pan-left | pan-right | pan-up | pan-down | manipulation",
  3183. "transform" : 1,
  3184. "transform-origin" : 1,
  3185. "transform-style" : 1,
  3186. "transition" : 1,
  3187. "transition-delay" : 1,
  3188. "transition-duration" : 1,
  3189. "transition-property" : 1,
  3190. "transition-timing-function" : 1,
  3191. //U
  3192. "unicode-bidi" : "normal | embed | isolate | bidi-override | isolate-override | plaintext",
  3193. "user-modify" : "read-only | read-write | write-only",
  3194. "user-select" : "none | text | toggle | element | elements | all",
  3195. //V
  3196. "vertical-align" : "auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length>",
  3197. "visibility" : "visible | hidden | collapse",
  3198. "voice-balance" : 1,
  3199. "voice-duration" : 1,
  3200. "voice-family" : 1,
  3201. "voice-pitch" : 1,
  3202. "voice-pitch-range" : 1,
  3203. "voice-rate" : 1,
  3204. "voice-stress" : 1,
  3205. "voice-volume" : 1,
  3206. "volume" : 1,
  3207. //W
  3208. "white-space" : "normal | pre | nowrap | pre-wrap | pre-line | -pre-wrap | -o-pre-wrap | -moz-pre-wrap | -hp-pre-wrap", // https://perishablepress.com/wrapping-content/
  3209. "white-space-collapse" : 1,
  3210. "widows" : "<integer>",
  3211. "width" : "<length> | <percentage> | <content-sizing> | auto",
  3212. "will-change" : "<will-change>",
  3213. "word-break" : "normal | keep-all | break-all",
  3214. "word-spacing" : "<length> | normal",
  3215. "word-wrap" : "normal | break-word",
  3216. "writing-mode" : "horizontal-tb | vertical-rl | vertical-lr | lr-tb | rl-tb | tb-rl | bt-rl | tb-lr | bt-lr | lr-bt | rl-bt | lr | rl | tb",
  3217. //Z
  3218. "z-index" : "<integer> | auto",
  3219. "zoom" : "<number> | <percentage> | normal"
  3220. };
  3221. },{}],8:[function(require,module,exports){
  3222. "use strict";
  3223. module.exports = PropertyName;
  3224. var SyntaxUnit = require("../util/SyntaxUnit");
  3225. var Parser = require("./Parser");
  3226. /**
  3227. * Represents a selector combinator (whitespace, +, >).
  3228. * @namespace parserlib.css
  3229. * @class PropertyName
  3230. * @extends parserlib.util.SyntaxUnit
  3231. * @constructor
  3232. * @param {String} text The text representation of the unit.
  3233. * @param {String} hack The type of IE hack applied ("*", "_", or null).
  3234. * @param {int} line The line of text on which the unit resides.
  3235. * @param {int} col The column of text on which the unit resides.
  3236. */
  3237. function PropertyName(text, hack, line, col) {
  3238. SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE);
  3239. /**
  3240. * The type of IE hack applied ("*", "_", or null).
  3241. * @type String
  3242. * @property hack
  3243. */
  3244. this.hack = hack;
  3245. }
  3246. PropertyName.prototype = new SyntaxUnit();
  3247. PropertyName.prototype.constructor = PropertyName;
  3248. PropertyName.prototype.toString = function() {
  3249. return (this.hack ? this.hack : "") + this.text;
  3250. };
  3251. },{"../util/SyntaxUnit":26,"./Parser":6}],9:[function(require,module,exports){
  3252. "use strict";
  3253. module.exports = PropertyValue;
  3254. var SyntaxUnit = require("../util/SyntaxUnit");
  3255. var Parser = require("./Parser");
  3256. /**
  3257. * Represents a single part of a CSS property value, meaning that it represents
  3258. * just everything single part between ":" and ";". If there are multiple values
  3259. * separated by commas, this type represents just one of the values.
  3260. * @param {String[]} parts An array of value parts making up this value.
  3261. * @param {int} line The line of text on which the unit resides.
  3262. * @param {int} col The column of text on which the unit resides.
  3263. * @namespace parserlib.css
  3264. * @class PropertyValue
  3265. * @extends parserlib.util.SyntaxUnit
  3266. * @constructor
  3267. */
  3268. function PropertyValue(parts, line, col) {
  3269. SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE);
  3270. /**
  3271. * The parts that make up the selector.
  3272. * @type Array
  3273. * @property parts
  3274. */
  3275. this.parts = parts;
  3276. }
  3277. PropertyValue.prototype = new SyntaxUnit();
  3278. PropertyValue.prototype.constructor = PropertyValue;
  3279. },{"../util/SyntaxUnit":26,"./Parser":6}],10:[function(require,module,exports){
  3280. "use strict";
  3281. module.exports = PropertyValueIterator;
  3282. /**
  3283. * A utility class that allows for easy iteration over the various parts of a
  3284. * property value.
  3285. * @param {parserlib.css.PropertyValue} value The property value to iterate over.
  3286. * @namespace parserlib.css
  3287. * @class PropertyValueIterator
  3288. * @constructor
  3289. */
  3290. function PropertyValueIterator(value) {
  3291. /**
  3292. * Iterator value
  3293. * @type int
  3294. * @property _i
  3295. * @private
  3296. */
  3297. this._i = 0;
  3298. /**
  3299. * The parts that make up the value.
  3300. * @type Array
  3301. * @property _parts
  3302. * @private
  3303. */
  3304. this._parts = value.parts;
  3305. /**
  3306. * Keeps track of bookmarks along the way.
  3307. * @type Array
  3308. * @property _marks
  3309. * @private
  3310. */
  3311. this._marks = [];
  3312. /**
  3313. * Holds the original property value.
  3314. * @type parserlib.css.PropertyValue
  3315. * @property value
  3316. */
  3317. this.value = value;
  3318. }
  3319. /**
  3320. * Returns the total number of parts in the value.
  3321. * @return {int} The total number of parts in the value.
  3322. * @method count
  3323. */
  3324. PropertyValueIterator.prototype.count = function() {
  3325. return this._parts.length;
  3326. };
  3327. /**
  3328. * Indicates if the iterator is positioned at the first item.
  3329. * @return {Boolean} True if positioned at first item, false if not.
  3330. * @method isFirst
  3331. */
  3332. PropertyValueIterator.prototype.isFirst = function() {
  3333. return this._i === 0;
  3334. };
  3335. /**
  3336. * Indicates if there are more parts of the property value.
  3337. * @return {Boolean} True if there are more parts, false if not.
  3338. * @method hasNext
  3339. */
  3340. PropertyValueIterator.prototype.hasNext = function() {
  3341. return this._i < this._parts.length;
  3342. };
  3343. /**
  3344. * Marks the current spot in the iteration so it can be restored to
  3345. * later on.
  3346. * @return {void}
  3347. * @method mark
  3348. */
  3349. PropertyValueIterator.prototype.mark = function() {
  3350. this._marks.push(this._i);
  3351. };
  3352. /**
  3353. * Returns the next part of the property value or null if there is no next
  3354. * part. Does not move the internal counter forward.
  3355. * @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next
  3356. * part.
  3357. * @method peek
  3358. */
  3359. PropertyValueIterator.prototype.peek = function(count) {
  3360. return this.hasNext() ? this._parts[this._i + (count || 0)] : null;
  3361. };
  3362. /**
  3363. * Returns the next part of the property value or null if there is no next
  3364. * part.
  3365. * @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next
  3366. * part.
  3367. * @method next
  3368. */
  3369. PropertyValueIterator.prototype.next = function() {
  3370. return this.hasNext() ? this._parts[this._i++] : null;
  3371. };
  3372. /**
  3373. * Returns the previous part of the property value or null if there is no
  3374. * previous part.
  3375. * @return {parserlib.css.PropertyValuePart} The previous part of the
  3376. * property value or null if there is no previous part.
  3377. * @method previous
  3378. */
  3379. PropertyValueIterator.prototype.previous = function() {
  3380. return this._i > 0 ? this._parts[--this._i] : null;
  3381. };
  3382. /**
  3383. * Restores the last saved bookmark.
  3384. * @return {void}
  3385. * @method restore
  3386. */
  3387. PropertyValueIterator.prototype.restore = function() {
  3388. if (this._marks.length) {
  3389. this._i = this._marks.pop();
  3390. }
  3391. };
  3392. /**
  3393. * Drops the last saved bookmark.
  3394. * @return {void}
  3395. * @method drop
  3396. */
  3397. PropertyValueIterator.prototype.drop = function() {
  3398. this._marks.pop();
  3399. };
  3400. },{}],11:[function(require,module,exports){
  3401. "use strict";
  3402. module.exports = PropertyValuePart;
  3403. var SyntaxUnit = require("../util/SyntaxUnit");
  3404. var Colors = require("./Colors");
  3405. var Parser = require("./Parser");
  3406. var Tokens = require("./Tokens");
  3407. /**
  3408. * Represents a single part of a CSS property value, meaning that it represents
  3409. * just one part of the data between ":" and ";".
  3410. * @param {String} text The text representation of the unit.
  3411. * @param {int} line The line of text on which the unit resides.
  3412. * @param {int} col The column of text on which the unit resides.
  3413. * @namespace parserlib.css
  3414. * @class PropertyValuePart
  3415. * @extends parserlib.util.SyntaxUnit
  3416. * @constructor
  3417. */
  3418. function PropertyValuePart(text, line, col, optionalHint) {
  3419. var hint = optionalHint || {};
  3420. SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE);
  3421. /**
  3422. * Indicates the type of value unit.
  3423. * @type String
  3424. * @property type
  3425. */
  3426. this.type = "unknown";
  3427. //figure out what type of data it is
  3428. var temp;
  3429. //it is a measurement?
  3430. if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)) { //dimension
  3431. this.type = "dimension";
  3432. this.value = +RegExp.$1;
  3433. this.units = RegExp.$2;
  3434. //try to narrow down
  3435. switch (this.units.toLowerCase()) {
  3436. case "em":
  3437. case "rem":
  3438. case "ex":
  3439. case "px":
  3440. case "cm":
  3441. case "mm":
  3442. case "in":
  3443. case "pt":
  3444. case "pc":
  3445. case "ch":
  3446. case "vh":
  3447. case "vw":
  3448. case "vmax":
  3449. case "vmin":
  3450. this.type = "length";
  3451. break;
  3452. case "fr":
  3453. this.type = "grid";
  3454. break;
  3455. case "deg":
  3456. case "rad":
  3457. case "grad":
  3458. case "turn":
  3459. this.type = "angle";
  3460. break;
  3461. case "ms":
  3462. case "s":
  3463. this.type = "time";
  3464. break;
  3465. case "hz":
  3466. case "khz":
  3467. this.type = "frequency";
  3468. break;
  3469. case "dpi":
  3470. case "dpcm":
  3471. this.type = "resolution";
  3472. break;
  3473. //default
  3474. }
  3475. } else if (/^([+\-]?[\d\.]+)%$/i.test(text)) { //percentage
  3476. this.type = "percentage";
  3477. this.value = +RegExp.$1;
  3478. } else if (/^([+\-]?\d+)$/i.test(text)) { //integer
  3479. this.type = "integer";
  3480. this.value = +RegExp.$1;
  3481. } else if (/^([+\-]?[\d\.]+)$/i.test(text)) { //number
  3482. this.type = "number";
  3483. this.value = +RegExp.$1;
  3484. } else if (/^#([a-f0-9]{3,6})/i.test(text)) { //hexcolor
  3485. this.type = "color";
  3486. temp = RegExp.$1;
  3487. if (temp.length === 3) {
  3488. this.red = parseInt(temp.charAt(0)+temp.charAt(0), 16);
  3489. this.green = parseInt(temp.charAt(1)+temp.charAt(1), 16);
  3490. this.blue = parseInt(temp.charAt(2)+temp.charAt(2), 16);
  3491. } else {
  3492. this.red = parseInt(temp.substring(0, 2), 16);
  3493. this.green = parseInt(temp.substring(2, 4), 16);
  3494. this.blue = parseInt(temp.substring(4, 6), 16);
  3495. }
  3496. } else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)) { //rgb() color with absolute numbers
  3497. this.type = "color";
  3498. this.red = +RegExp.$1;
  3499. this.green = +RegExp.$2;
  3500. this.blue = +RegExp.$3;
  3501. } else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)) { //rgb() color with percentages
  3502. this.type = "color";
  3503. this.red = +RegExp.$1 * 255 / 100;
  3504. this.green = +RegExp.$2 * 255 / 100;
  3505. this.blue = +RegExp.$3 * 255 / 100;
  3506. } else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)) { //rgba() color with absolute numbers
  3507. this.type = "color";
  3508. this.red = +RegExp.$1;
  3509. this.green = +RegExp.$2;
  3510. this.blue = +RegExp.$3;
  3511. this.alpha = +RegExp.$4;
  3512. } else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)) { //rgba() color with percentages
  3513. this.type = "color";
  3514. this.red = +RegExp.$1 * 255 / 100;
  3515. this.green = +RegExp.$2 * 255 / 100;
  3516. this.blue = +RegExp.$3 * 255 / 100;
  3517. this.alpha = +RegExp.$4;
  3518. } else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)) { //hsl()
  3519. this.type = "color";
  3520. this.hue = +RegExp.$1;
  3521. this.saturation = +RegExp.$2 / 100;
  3522. this.lightness = +RegExp.$3 / 100;
  3523. } else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)) { //hsla() color with percentages
  3524. this.type = "color";
  3525. this.hue = +RegExp.$1;
  3526. this.saturation = +RegExp.$2 / 100;
  3527. this.lightness = +RegExp.$3 / 100;
  3528. this.alpha = +RegExp.$4;
  3529. } else if (/^url\(("([^\\"]|\\.)*")\)/i.test(text)) { //URI
  3530. // generated by TokenStream.readURI, so always double-quoted.
  3531. this.type = "uri";
  3532. this.uri = PropertyValuePart.parseString(RegExp.$1);
  3533. } else if (/^([^\(]+)\(/i.test(text)) {
  3534. this.type = "function";
  3535. this.name = RegExp.$1;
  3536. this.value = text;
  3537. } else if (/^"([^\n\r\f\\"]|\\\r\n|\\[^\r0-9a-f]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?)*"/i.test(text)) { //double-quoted string
  3538. this.type = "string";
  3539. this.value = PropertyValuePart.parseString(text);
  3540. } else if (/^'([^\n\r\f\\']|\\\r\n|\\[^\r0-9a-f]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?)*'/i.test(text)) { //single-quoted string
  3541. this.type = "string";
  3542. this.value = PropertyValuePart.parseString(text);
  3543. } else if (Colors[text.toLowerCase()]) { //named color
  3544. this.type = "color";
  3545. temp = Colors[text.toLowerCase()].substring(1);
  3546. this.red = parseInt(temp.substring(0, 2), 16);
  3547. this.green = parseInt(temp.substring(2, 4), 16);
  3548. this.blue = parseInt(temp.substring(4, 6), 16);
  3549. } else if (/^[,\/]$/.test(text)) {
  3550. this.type = "operator";
  3551. this.value = text;
  3552. } else if (/^-?[a-z_\u00A0-\uFFFF][a-z0-9\-_\u00A0-\uFFFF]*$/i.test(text)) {
  3553. this.type = "identifier";
  3554. this.value = text;
  3555. }
  3556. // There can be ambiguity with escape sequences in identifiers, as
  3557. // well as with "color" parts which are also "identifiers", so record
  3558. // an explicit hint when the token generating this PropertyValuePart
  3559. // was an identifier.
  3560. this.wasIdent = Boolean(hint.ident);
  3561. }
  3562. PropertyValuePart.prototype = new SyntaxUnit();
  3563. PropertyValuePart.prototype.constructor = PropertyValuePart;
  3564. /**
  3565. * Helper method to parse a CSS string.
  3566. */
  3567. PropertyValuePart.parseString = function(str) {
  3568. str = str.slice(1, -1); // Strip surrounding single/double quotes
  3569. var replacer = function(match, esc) {
  3570. if (/^(\n|\r\n|\r|\f)$/.test(esc)) {
  3571. return "";
  3572. }
  3573. var m = /^[0-9a-f]{1,6}/i.exec(esc);
  3574. if (m) {
  3575. var codePoint = parseInt(m[0], 16);
  3576. if (String.fromCodePoint) {
  3577. return String.fromCodePoint(codePoint);
  3578. } else {
  3579. // XXX No support for surrogates on old JavaScript engines.
  3580. return String.fromCharCode(codePoint);
  3581. }
  3582. }
  3583. return esc;
  3584. };
  3585. return str.replace(/\\(\r\n|[^\r0-9a-f]|[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?)/ig,
  3586. replacer);
  3587. };
  3588. /**
  3589. * Helper method to serialize a CSS string.
  3590. */
  3591. PropertyValuePart.serializeString = function(value) {
  3592. var replacer = function(match, c) {
  3593. if (c === "\"") {
  3594. return "\\" + c;
  3595. }
  3596. var cp = String.codePointAt ? String.codePointAt(0) :
  3597. // We only escape non-surrogate chars, so using charCodeAt
  3598. // is harmless here.
  3599. String.charCodeAt(0);
  3600. return "\\" + cp.toString(16) + " ";
  3601. };
  3602. return "\"" + value.replace(/["\r\n\f]/g, replacer) + "\"";
  3603. };
  3604. /**
  3605. * Create a new syntax unit based solely on the given token.
  3606. * Convenience method for creating a new syntax unit when
  3607. * it represents a single token instead of multiple.
  3608. * @param {Object} token The token object to represent.
  3609. * @return {parserlib.css.PropertyValuePart} The object representing the token.
  3610. * @static
  3611. * @method fromToken
  3612. */
  3613. PropertyValuePart.fromToken = function(token) {
  3614. var part = new PropertyValuePart(token.value, token.startLine, token.startCol, {
  3615. // Tokens can have escaped characters that would fool the type
  3616. // identification in the PropertyValuePart constructor, so pass
  3617. // in a hint if this was an identifier.
  3618. ident: token.type === Tokens.IDENT
  3619. });
  3620. return part;
  3621. };
  3622. },{"../util/SyntaxUnit":26,"./Colors":1,"./Parser":6,"./Tokens":18}],12:[function(require,module,exports){
  3623. "use strict";
  3624. var Pseudos = module.exports = {
  3625. __proto__: null,
  3626. ":first-letter": 1,
  3627. ":first-line": 1,
  3628. ":before": 1,
  3629. ":after": 1
  3630. };
  3631. Pseudos.ELEMENT = 1;
  3632. Pseudos.CLASS = 2;
  3633. Pseudos.isElement = function(pseudo) {
  3634. return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] === Pseudos.ELEMENT;
  3635. };
  3636. },{}],13:[function(require,module,exports){
  3637. "use strict";
  3638. module.exports = Selector;
  3639. var SyntaxUnit = require("../util/SyntaxUnit");
  3640. var Parser = require("./Parser");
  3641. var Specificity = require("./Specificity");
  3642. /**
  3643. * Represents an entire single selector, including all parts but not
  3644. * including multiple selectors (those separated by commas).
  3645. * @namespace parserlib.css
  3646. * @class Selector
  3647. * @extends parserlib.util.SyntaxUnit
  3648. * @constructor
  3649. * @param {Array} parts Array of selectors parts making up this selector.
  3650. * @param {int} line The line of text on which the unit resides.
  3651. * @param {int} col The column of text on which the unit resides.
  3652. */
  3653. function Selector(parts, line, col) {
  3654. SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE);
  3655. /**
  3656. * The parts that make up the selector.
  3657. * @type Array
  3658. * @property parts
  3659. */
  3660. this.parts = parts;
  3661. /**
  3662. * The specificity of the selector.
  3663. * @type parserlib.css.Specificity
  3664. * @property specificity
  3665. */
  3666. this.specificity = Specificity.calculate(this);
  3667. }
  3668. Selector.prototype = new SyntaxUnit();
  3669. Selector.prototype.constructor = Selector;
  3670. },{"../util/SyntaxUnit":26,"./Parser":6,"./Specificity":16}],14:[function(require,module,exports){
  3671. "use strict";
  3672. module.exports = SelectorPart;
  3673. var SyntaxUnit = require("../util/SyntaxUnit");
  3674. var Parser = require("./Parser");
  3675. /**
  3676. * Represents a single part of a selector string, meaning a single set of
  3677. * element name and modifiers. This does not include combinators such as
  3678. * spaces, +, >, etc.
  3679. * @namespace parserlib.css
  3680. * @class SelectorPart
  3681. * @extends parserlib.util.SyntaxUnit
  3682. * @constructor
  3683. * @param {String} elementName The element name in the selector or null
  3684. * if there is no element name.
  3685. * @param {Array} modifiers Array of individual modifiers for the element.
  3686. * May be empty if there are none.
  3687. * @param {String} text The text representation of the unit.
  3688. * @param {int} line The line of text on which the unit resides.
  3689. * @param {int} col The column of text on which the unit resides.
  3690. */
  3691. function SelectorPart(elementName, modifiers, text, line, col) {
  3692. SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE);
  3693. /**
  3694. * The tag name of the element to which this part
  3695. * of the selector affects.
  3696. * @type String
  3697. * @property elementName
  3698. */
  3699. this.elementName = elementName;
  3700. /**
  3701. * The parts that come after the element name, such as class names, IDs,
  3702. * pseudo classes/elements, etc.
  3703. * @type Array
  3704. * @property modifiers
  3705. */
  3706. this.modifiers = modifiers;
  3707. }
  3708. SelectorPart.prototype = new SyntaxUnit();
  3709. SelectorPart.prototype.constructor = SelectorPart;
  3710. },{"../util/SyntaxUnit":26,"./Parser":6}],15:[function(require,module,exports){
  3711. "use strict";
  3712. module.exports = SelectorSubPart;
  3713. var SyntaxUnit = require("../util/SyntaxUnit");
  3714. var Parser = require("./Parser");
  3715. /**
  3716. * Represents a selector modifier string, meaning a class name, element name,
  3717. * element ID, pseudo rule, etc.
  3718. * @namespace parserlib.css
  3719. * @class SelectorSubPart
  3720. * @extends parserlib.util.SyntaxUnit
  3721. * @constructor
  3722. * @param {String} text The text representation of the unit.
  3723. * @param {String} type The type of selector modifier.
  3724. * @param {int} line The line of text on which the unit resides.
  3725. * @param {int} col The column of text on which the unit resides.
  3726. */
  3727. function SelectorSubPart(text, type, line, col) {
  3728. SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE);
  3729. /**
  3730. * The type of modifier.
  3731. * @type String
  3732. * @property type
  3733. */
  3734. this.type = type;
  3735. /**
  3736. * Some subparts have arguments, this represents them.
  3737. * @type Array
  3738. * @property args
  3739. */
  3740. this.args = [];
  3741. }
  3742. SelectorSubPart.prototype = new SyntaxUnit();
  3743. SelectorSubPart.prototype.constructor = SelectorSubPart;
  3744. },{"../util/SyntaxUnit":26,"./Parser":6}],16:[function(require,module,exports){
  3745. "use strict";
  3746. module.exports = Specificity;
  3747. var Pseudos = require("./Pseudos");
  3748. var SelectorPart = require("./SelectorPart");
  3749. /**
  3750. * Represents a selector's specificity.
  3751. * @namespace parserlib.css
  3752. * @class Specificity
  3753. * @constructor
  3754. * @param {int} a Should be 1 for inline styles, zero for stylesheet styles
  3755. * @param {int} b Number of ID selectors
  3756. * @param {int} c Number of classes and pseudo classes
  3757. * @param {int} d Number of element names and pseudo elements
  3758. */
  3759. function Specificity(a, b, c, d) {
  3760. this.a = a;
  3761. this.b = b;
  3762. this.c = c;
  3763. this.d = d;
  3764. }
  3765. Specificity.prototype = {
  3766. constructor: Specificity,
  3767. /**
  3768. * Compare this specificity to another.
  3769. * @param {Specificity} other The other specificity to compare to.
  3770. * @return {int} -1 if the other specificity is larger, 1 if smaller, 0 if equal.
  3771. * @method compare
  3772. */
  3773. compare: function(other) {
  3774. var comps = ["a", "b", "c", "d"],
  3775. i, len;
  3776. for (i=0, len=comps.length; i < len; i++) {
  3777. if (this[comps[i]] < other[comps[i]]) {
  3778. return -1;
  3779. } else if (this[comps[i]] > other[comps[i]]) {
  3780. return 1;
  3781. }
  3782. }
  3783. return 0;
  3784. },
  3785. /**
  3786. * Creates a numeric value for the specificity.
  3787. * @return {int} The numeric value for the specificity.
  3788. * @method valueOf
  3789. */
  3790. valueOf: function() {
  3791. return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d;
  3792. },
  3793. /**
  3794. * Returns a string representation for specificity.
  3795. * @return {String} The string representation of specificity.
  3796. * @method toString
  3797. */
  3798. toString: function() {
  3799. return this.a + "," + this.b + "," + this.c + "," + this.d;
  3800. }
  3801. };
  3802. /**
  3803. * Calculates the specificity of the given selector.
  3804. * @param {parserlib.css.Selector} The selector to calculate specificity for.
  3805. * @return {parserlib.css.Specificity} The specificity of the selector.
  3806. * @static
  3807. * @method calculate
  3808. */
  3809. Specificity.calculate = function(selector) {
  3810. var i, len,
  3811. part,
  3812. b=0, c=0, d=0;
  3813. function updateValues(part) {
  3814. var i, j, len, num,
  3815. elementName = part.elementName ? part.elementName.text : "",
  3816. modifier;
  3817. if (elementName && elementName.charAt(elementName.length-1) !== "*") {
  3818. d++;
  3819. }
  3820. for (i=0, len=part.modifiers.length; i < len; i++) {
  3821. modifier = part.modifiers[i];
  3822. switch (modifier.type) {
  3823. case "class":
  3824. case "attribute":
  3825. c++;
  3826. break;
  3827. case "id":
  3828. b++;
  3829. break;
  3830. case "pseudo":
  3831. if (Pseudos.isElement(modifier.text)) {
  3832. d++;
  3833. } else {
  3834. c++;
  3835. }
  3836. break;
  3837. case "not":
  3838. for (j=0, num=modifier.args.length; j < num; j++) {
  3839. updateValues(modifier.args[j]);
  3840. }
  3841. }
  3842. }
  3843. }
  3844. for (i=0, len=selector.parts.length; i < len; i++) {
  3845. part = selector.parts[i];
  3846. if (part instanceof SelectorPart) {
  3847. updateValues(part);
  3848. }
  3849. }
  3850. return new Specificity(0, b, c, d);
  3851. };
  3852. },{"./Pseudos":12,"./SelectorPart":14}],17:[function(require,module,exports){
  3853. "use strict";
  3854. module.exports = TokenStream;
  3855. var TokenStreamBase = require("../util/TokenStreamBase");
  3856. var PropertyValuePart = require("./PropertyValuePart");
  3857. var Tokens = require("./Tokens");
  3858. var h = /^[0-9a-fA-F]$/,
  3859. nonascii = /^[\u00A0-\uFFFF]$/,
  3860. nl = /\n|\r\n|\r|\f/,
  3861. whitespace = /\u0009|\u000a|\u000c|\u000d|\u0020/;
  3862. //-----------------------------------------------------------------------------
  3863. // Helper functions
  3864. //-----------------------------------------------------------------------------
  3865. function isHexDigit(c) {
  3866. return c !== null && h.test(c);
  3867. }
  3868. function isDigit(c) {
  3869. return c !== null && /\d/.test(c);
  3870. }
  3871. function isWhitespace(c) {
  3872. return c !== null && whitespace.test(c);
  3873. }
  3874. function isNewLine(c) {
  3875. return c !== null && nl.test(c);
  3876. }
  3877. function isNameStart(c) {
  3878. return c !== null && /[a-z_\u00A0-\uFFFF\\]/i.test(c);
  3879. }
  3880. function isNameChar(c) {
  3881. return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c));
  3882. }
  3883. function isIdentStart(c) {
  3884. return c !== null && (isNameStart(c) || /\-\\/.test(c));
  3885. }
  3886. function mix(receiver, supplier) {
  3887. for (var prop in supplier) {
  3888. if (Object.prototype.hasOwnProperty.call(supplier, prop)) {
  3889. receiver[prop] = supplier[prop];
  3890. }
  3891. }
  3892. return receiver;
  3893. }
  3894. //-----------------------------------------------------------------------------
  3895. // CSS Token Stream
  3896. //-----------------------------------------------------------------------------
  3897. /**
  3898. * A token stream that produces CSS tokens.
  3899. * @param {String|Reader} input The source of text to tokenize.
  3900. * @constructor
  3901. * @class TokenStream
  3902. * @namespace parserlib.css
  3903. */
  3904. function TokenStream(input) {
  3905. TokenStreamBase.call(this, input, Tokens);
  3906. }
  3907. TokenStream.prototype = mix(new TokenStreamBase(), {
  3908. /**
  3909. * Overrides the TokenStreamBase method of the same name
  3910. * to produce CSS tokens.
  3911. * @return {Object} A token object representing the next token.
  3912. * @method _getToken
  3913. * @private
  3914. */
  3915. _getToken: function() {
  3916. var c,
  3917. reader = this._reader,
  3918. token = null,
  3919. startLine = reader.getLine(),
  3920. startCol = reader.getCol();
  3921. c = reader.read();
  3922. while (c) {
  3923. switch (c) {
  3924. /*
  3925. * Potential tokens:
  3926. * - COMMENT
  3927. * - SLASH
  3928. * - CHAR
  3929. */
  3930. case "/":
  3931. if (reader.peek() === "*") {
  3932. token = this.commentToken(c, startLine, startCol);
  3933. } else {
  3934. token = this.charToken(c, startLine, startCol);
  3935. }
  3936. break;
  3937. /*
  3938. * Potential tokens:
  3939. * - DASHMATCH
  3940. * - INCLUDES
  3941. * - PREFIXMATCH
  3942. * - SUFFIXMATCH
  3943. * - SUBSTRINGMATCH
  3944. * - CHAR
  3945. */
  3946. case "|":
  3947. case "~":
  3948. case "^":
  3949. case "$":
  3950. case "*":
  3951. if (reader.peek() === "=") {
  3952. token = this.comparisonToken(c, startLine, startCol);
  3953. } else {
  3954. token = this.charToken(c, startLine, startCol);
  3955. }
  3956. break;
  3957. /*
  3958. * Potential tokens:
  3959. * - STRING
  3960. * - INVALID
  3961. */
  3962. case "\"":
  3963. case "'":
  3964. token = this.stringToken(c, startLine, startCol);
  3965. break;
  3966. /*
  3967. * Potential tokens:
  3968. * - HASH
  3969. * - CHAR
  3970. */
  3971. case "#":
  3972. if (isNameChar(reader.peek())) {
  3973. token = this.hashToken(c, startLine, startCol);
  3974. } else {
  3975. token = this.charToken(c, startLine, startCol);
  3976. }
  3977. break;
  3978. /*
  3979. * Potential tokens:
  3980. * - DOT
  3981. * - NUMBER
  3982. * - DIMENSION
  3983. * - PERCENTAGE
  3984. */
  3985. case ".":
  3986. if (isDigit(reader.peek())) {
  3987. token = this.numberToken(c, startLine, startCol);
  3988. } else {
  3989. token = this.charToken(c, startLine, startCol);
  3990. }
  3991. break;
  3992. /*
  3993. * Potential tokens:
  3994. * - CDC
  3995. * - MINUS
  3996. * - NUMBER
  3997. * - DIMENSION
  3998. * - PERCENTAGE
  3999. */
  4000. case "-":
  4001. if (reader.peek() === "-") { //could be closing HTML-style comment
  4002. token = this.htmlCommentEndToken(c, startLine, startCol);
  4003. } else if (isNameStart(reader.peek())) {
  4004. token = this.identOrFunctionToken(c, startLine, startCol);
  4005. } else {
  4006. token = this.charToken(c, startLine, startCol);
  4007. }
  4008. break;
  4009. /*
  4010. * Potential tokens:
  4011. * - IMPORTANT_SYM
  4012. * - CHAR
  4013. */
  4014. case "!":
  4015. token = this.importantToken(c, startLine, startCol);
  4016. break;
  4017. /*
  4018. * Any at-keyword or CHAR
  4019. */
  4020. case "@":
  4021. token = this.atRuleToken(c, startLine, startCol);
  4022. break;
  4023. /*
  4024. * Potential tokens:
  4025. * - NOT
  4026. * - CHAR
  4027. */
  4028. case ":":
  4029. token = this.notToken(c, startLine, startCol);
  4030. break;
  4031. /*
  4032. * Potential tokens:
  4033. * - CDO
  4034. * - CHAR
  4035. */
  4036. case "<":
  4037. token = this.htmlCommentStartToken(c, startLine, startCol);
  4038. break;
  4039. /*
  4040. * Potential tokens:
  4041. * - IDENT
  4042. * - CHAR
  4043. */
  4044. case "\\":
  4045. if (/[^\r\n\f]/.test(reader.peek())) {
  4046. token = this.identOrFunctionToken(this.readEscape(c, true), startLine, startCol);
  4047. } else {
  4048. token = this.charToken(c, startLine, startCol);
  4049. }
  4050. break;
  4051. /*
  4052. * Potential tokens:
  4053. * - UNICODE_RANGE
  4054. * - URL
  4055. * - CHAR
  4056. */
  4057. case "U":
  4058. case "u":
  4059. if (reader.peek() === "+") {
  4060. token = this.unicodeRangeToken(c, startLine, startCol);
  4061. break;
  4062. }
  4063. /* falls through */
  4064. default:
  4065. /*
  4066. * Potential tokens:
  4067. * - NUMBER
  4068. * - DIMENSION
  4069. * - LENGTH
  4070. * - FREQ
  4071. * - TIME
  4072. * - EMS
  4073. * - EXS
  4074. * - ANGLE
  4075. */
  4076. if (isDigit(c)) {
  4077. token = this.numberToken(c, startLine, startCol);
  4078. } else
  4079. /*
  4080. * Potential tokens:
  4081. * - S
  4082. */
  4083. if (isWhitespace(c)) {
  4084. token = this.whitespaceToken(c, startLine, startCol);
  4085. } else
  4086. /*
  4087. * Potential tokens:
  4088. * - IDENT
  4089. */
  4090. if (isIdentStart(c)) {
  4091. token = this.identOrFunctionToken(c, startLine, startCol);
  4092. } else {
  4093. /*
  4094. * Potential tokens:
  4095. * - CHAR
  4096. * - PLUS
  4097. */
  4098. token = this.charToken(c, startLine, startCol);
  4099. }
  4100. }
  4101. //make sure this token is wanted
  4102. //TODO: check channel
  4103. break;
  4104. }
  4105. if (!token && c === null) {
  4106. token = this.createToken(Tokens.EOF, null, startLine, startCol);
  4107. }
  4108. return token;
  4109. },
  4110. //-------------------------------------------------------------------------
  4111. // Methods to create tokens
  4112. //-------------------------------------------------------------------------
  4113. /**
  4114. * Produces a token based on available data and the current
  4115. * reader position information. This method is called by other
  4116. * private methods to create tokens and is never called directly.
  4117. * @param {int} tt The token type.
  4118. * @param {String} value The text value of the token.
  4119. * @param {int} startLine The beginning line for the character.
  4120. * @param {int} startCol The beginning column for the character.
  4121. * @param {Object} options (Optional) Specifies a channel property
  4122. * to indicate that a different channel should be scanned
  4123. * and/or a hide property indicating that the token should
  4124. * be hidden.
  4125. * @return {Object} A token object.
  4126. * @method createToken
  4127. */
  4128. createToken: function(tt, value, startLine, startCol, options) {
  4129. var reader = this._reader;
  4130. options = options || {};
  4131. return {
  4132. value: value,
  4133. type: tt,
  4134. channel: options.channel,
  4135. endChar: options.endChar,
  4136. hide: options.hide || false,
  4137. startLine: startLine,
  4138. startCol: startCol,
  4139. endLine: reader.getLine(),
  4140. endCol: reader.getCol()
  4141. };
  4142. },
  4143. //-------------------------------------------------------------------------
  4144. // Methods to create specific tokens
  4145. //-------------------------------------------------------------------------
  4146. /**
  4147. * Produces a token for any at-rule. If the at-rule is unknown, then
  4148. * the token is for a single "@" character.
  4149. * @param {String} first The first character for the token.
  4150. * @param {int} startLine The beginning line for the character.
  4151. * @param {int} startCol The beginning column for the character.
  4152. * @return {Object} A token object.
  4153. * @method atRuleToken
  4154. */
  4155. atRuleToken: function(first, startLine, startCol) {
  4156. var rule = first,
  4157. reader = this._reader,
  4158. tt = Tokens.CHAR,
  4159. ident;
  4160. /*
  4161. * First, mark where we are. There are only four @ rules,
  4162. * so anything else is really just an invalid token.
  4163. * Basically, if this doesn't match one of the known @
  4164. * rules, just return '@' as an unknown token and allow
  4165. * parsing to continue after that point.
  4166. */
  4167. reader.mark();
  4168. //try to find the at-keyword
  4169. ident = this.readName();
  4170. rule = first + ident;
  4171. tt = Tokens.type(rule.toLowerCase());
  4172. //if it's not valid, use the first character only and reset the reader
  4173. if (tt === Tokens.CHAR || tt === Tokens.UNKNOWN) {
  4174. if (rule.length > 1) {
  4175. tt = Tokens.UNKNOWN_SYM;
  4176. } else {
  4177. tt = Tokens.CHAR;
  4178. rule = first;
  4179. reader.reset();
  4180. }
  4181. }
  4182. return this.createToken(tt, rule, startLine, startCol);
  4183. },
  4184. /**
  4185. * Produces a character token based on the given character
  4186. * and location in the stream. If there's a special (non-standard)
  4187. * token name, this is used; otherwise CHAR is used.
  4188. * @param {String} c The character for the token.
  4189. * @param {int} startLine The beginning line for the character.
  4190. * @param {int} startCol The beginning column for the character.
  4191. * @return {Object} A token object.
  4192. * @method charToken
  4193. */
  4194. charToken: function(c, startLine, startCol) {
  4195. var tt = Tokens.type(c);
  4196. var opts = {};
  4197. if (tt === -1) {
  4198. tt = Tokens.CHAR;
  4199. } else {
  4200. opts.endChar = Tokens[tt].endChar;
  4201. }
  4202. return this.createToken(tt, c, startLine, startCol, opts);
  4203. },
  4204. /**
  4205. * Produces a character token based on the given character
  4206. * and location in the stream. If there's a special (non-standard)
  4207. * token name, this is used; otherwise CHAR is used.
  4208. * @param {String} first The first character for the token.
  4209. * @param {int} startLine The beginning line for the character.
  4210. * @param {int} startCol The beginning column for the character.
  4211. * @return {Object} A token object.
  4212. * @method commentToken
  4213. */
  4214. commentToken: function(first, startLine, startCol) {
  4215. var comment = this.readComment(first);
  4216. return this.createToken(Tokens.COMMENT, comment, startLine, startCol);
  4217. },
  4218. /**
  4219. * Produces a comparison token based on the given character
  4220. * and location in the stream. The next character must be
  4221. * read and is already known to be an equals sign.
  4222. * @param {String} c The character for the token.
  4223. * @param {int} startLine The beginning line for the character.
  4224. * @param {int} startCol The beginning column for the character.
  4225. * @return {Object} A token object.
  4226. * @method comparisonToken
  4227. */
  4228. comparisonToken: function(c, startLine, startCol) {
  4229. var reader = this._reader,
  4230. comparison = c + reader.read(),
  4231. tt = Tokens.type(comparison) || Tokens.CHAR;
  4232. return this.createToken(tt, comparison, startLine, startCol);
  4233. },
  4234. /**
  4235. * Produces a hash token based on the specified information. The
  4236. * first character provided is the pound sign (#) and then this
  4237. * method reads a name afterward.
  4238. * @param {String} first The first character (#) in the hash name.
  4239. * @param {int} startLine The beginning line for the character.
  4240. * @param {int} startCol The beginning column for the character.
  4241. * @return {Object} A token object.
  4242. * @method hashToken
  4243. */
  4244. hashToken: function(first, startLine, startCol) {
  4245. var name = this.readName(first);
  4246. return this.createToken(Tokens.HASH, name, startLine, startCol);
  4247. },
  4248. /**
  4249. * Produces a CDO or CHAR token based on the specified information. The
  4250. * first character is provided and the rest is read by the function to determine
  4251. * the correct token to create.
  4252. * @param {String} first The first character in the token.
  4253. * @param {int} startLine The beginning line for the character.
  4254. * @param {int} startCol The beginning column for the character.
  4255. * @return {Object} A token object.
  4256. * @method htmlCommentStartToken
  4257. */
  4258. htmlCommentStartToken: function(first, startLine, startCol) {
  4259. var reader = this._reader,
  4260. text = first;
  4261. reader.mark();
  4262. text += reader.readCount(3);
  4263. if (text === "<!--") {
  4264. return this.createToken(Tokens.CDO, text, startLine, startCol);
  4265. } else {
  4266. reader.reset();
  4267. return this.charToken(first, startLine, startCol);
  4268. }
  4269. },
  4270. /**
  4271. * Produces a CDC or CHAR token based on the specified information. The
  4272. * first character is provided and the rest is read by the function to determine
  4273. * the correct token to create.
  4274. * @param {String} first The first character in the token.
  4275. * @param {int} startLine The beginning line for the character.
  4276. * @param {int} startCol The beginning column for the character.
  4277. * @return {Object} A token object.
  4278. * @method htmlCommentEndToken
  4279. */
  4280. htmlCommentEndToken: function(first, startLine, startCol) {
  4281. var reader = this._reader,
  4282. text = first;
  4283. reader.mark();
  4284. text += reader.readCount(2);
  4285. if (text === "-->") {
  4286. return this.createToken(Tokens.CDC, text, startLine, startCol);
  4287. } else {
  4288. reader.reset();
  4289. return this.charToken(first, startLine, startCol);
  4290. }
  4291. },
  4292. /**
  4293. * Produces an IDENT or FUNCTION token based on the specified information. The
  4294. * first character is provided and the rest is read by the function to determine
  4295. * the correct token to create.
  4296. * @param {String} first The first character in the identifier.
  4297. * @param {int} startLine The beginning line for the character.
  4298. * @param {int} startCol The beginning column for the character.
  4299. * @return {Object} A token object.
  4300. * @method identOrFunctionToken
  4301. */
  4302. identOrFunctionToken: function(first, startLine, startCol) {
  4303. var reader = this._reader,
  4304. ident = this.readName(first),
  4305. tt = Tokens.IDENT,
  4306. uriFns = ["url(", "url-prefix(", "domain("],
  4307. uri;
  4308. //if there's a left paren immediately after, it's a URI or function
  4309. if (reader.peek() === "(") {
  4310. ident += reader.read();
  4311. if (uriFns.indexOf(ident.toLowerCase()) > -1) {
  4312. reader.mark();
  4313. uri = this.readURI(ident);
  4314. if (uri === null) {
  4315. //didn't find a valid URL or there's no closing paren
  4316. reader.reset();
  4317. tt = Tokens.FUNCTION;
  4318. } else {
  4319. tt = Tokens.URI;
  4320. ident = uri;
  4321. }
  4322. } else {
  4323. tt = Tokens.FUNCTION;
  4324. }
  4325. } else if (reader.peek() === ":") { //might be an IE function
  4326. //IE-specific functions always being with progid:
  4327. if (ident.toLowerCase() === "progid") {
  4328. ident += reader.readTo("(");
  4329. tt = Tokens.IE_FUNCTION;
  4330. }
  4331. }
  4332. return this.createToken(tt, ident, startLine, startCol);
  4333. },
  4334. /**
  4335. * Produces an IMPORTANT_SYM or CHAR token based on the specified information. The
  4336. * first character is provided and the rest is read by the function to determine
  4337. * the correct token to create.
  4338. * @param {String} first The first character in the token.
  4339. * @param {int} startLine The beginning line for the character.
  4340. * @param {int} startCol The beginning column for the character.
  4341. * @return {Object} A token object.
  4342. * @method importantToken
  4343. */
  4344. importantToken: function(first, startLine, startCol) {
  4345. var reader = this._reader,
  4346. important = first,
  4347. tt = Tokens.CHAR,
  4348. temp,
  4349. c;
  4350. reader.mark();
  4351. c = reader.read();
  4352. while (c) {
  4353. //there can be a comment in here
  4354. if (c === "/") {
  4355. //if the next character isn't a star, then this isn't a valid !important token
  4356. if (reader.peek() !== "*") {
  4357. break;
  4358. } else {
  4359. temp = this.readComment(c);
  4360. if (temp === "") { //broken!
  4361. break;
  4362. }
  4363. }
  4364. } else if (isWhitespace(c)) {
  4365. important += c + this.readWhitespace();
  4366. } else if (/i/i.test(c)) {
  4367. temp = reader.readCount(8);
  4368. if (/mportant/i.test(temp)) {
  4369. important += c + temp;
  4370. tt = Tokens.IMPORTANT_SYM;
  4371. }
  4372. break; //we're done
  4373. } else {
  4374. break;
  4375. }
  4376. c = reader.read();
  4377. }
  4378. if (tt === Tokens.CHAR) {
  4379. reader.reset();
  4380. return this.charToken(first, startLine, startCol);
  4381. } else {
  4382. return this.createToken(tt, important, startLine, startCol);
  4383. }
  4384. },
  4385. /**
  4386. * Produces a NOT or CHAR token based on the specified information. The
  4387. * first character is provided and the rest is read by the function to determine
  4388. * the correct token to create.
  4389. * @param {String} first The first character in the token.
  4390. * @param {int} startLine The beginning line for the character.
  4391. * @param {int} startCol The beginning column for the character.
  4392. * @return {Object} A token object.
  4393. * @method notToken
  4394. */
  4395. notToken: function(first, startLine, startCol) {
  4396. var reader = this._reader,
  4397. text = first;
  4398. reader.mark();
  4399. text += reader.readCount(4);
  4400. if (text.toLowerCase() === ":not(") {
  4401. return this.createToken(Tokens.NOT, text, startLine, startCol);
  4402. } else {
  4403. reader.reset();
  4404. return this.charToken(first, startLine, startCol);
  4405. }
  4406. },
  4407. /**
  4408. * Produces a number token based on the given character
  4409. * and location in the stream. This may return a token of
  4410. * NUMBER, EMS, EXS, LENGTH, ANGLE, TIME, FREQ, DIMENSION,
  4411. * or PERCENTAGE.
  4412. * @param {String} first The first character for the token.
  4413. * @param {int} startLine The beginning line for the character.
  4414. * @param {int} startCol The beginning column for the character.
  4415. * @return {Object} A token object.
  4416. * @method numberToken
  4417. */
  4418. numberToken: function(first, startLine, startCol) {
  4419. var reader = this._reader,
  4420. value = this.readNumber(first),
  4421. ident,
  4422. tt = Tokens.NUMBER,
  4423. c = reader.peek();
  4424. if (isIdentStart(c)) {
  4425. ident = this.readName(reader.read());
  4426. value += ident;
  4427. if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vmax$|^vmin$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)) {
  4428. tt = Tokens.LENGTH;
  4429. } else if (/^deg|^rad$|^grad$|^turn$/i.test(ident)) {
  4430. tt = Tokens.ANGLE;
  4431. } else if (/^ms$|^s$/i.test(ident)) {
  4432. tt = Tokens.TIME;
  4433. } else if (/^hz$|^khz$/i.test(ident)) {
  4434. tt = Tokens.FREQ;
  4435. } else if (/^dpi$|^dpcm$/i.test(ident)) {
  4436. tt = Tokens.RESOLUTION;
  4437. } else {
  4438. tt = Tokens.DIMENSION;
  4439. }
  4440. } else if (c === "%") {
  4441. value += reader.read();
  4442. tt = Tokens.PERCENTAGE;
  4443. }
  4444. return this.createToken(tt, value, startLine, startCol);
  4445. },
  4446. /**
  4447. * Produces a string token based on the given character
  4448. * and location in the stream. Since strings may be indicated
  4449. * by single or double quotes, a failure to match starting
  4450. * and ending quotes results in an INVALID token being generated.
  4451. * The first character in the string is passed in and then
  4452. * the rest are read up to and including the final quotation mark.
  4453. * @param {String} first The first character in the string.
  4454. * @param {int} startLine The beginning line for the character.
  4455. * @param {int} startCol The beginning column for the character.
  4456. * @return {Object} A token object.
  4457. * @method stringToken
  4458. */
  4459. stringToken: function(first, startLine, startCol) {
  4460. var delim = first,
  4461. string = first,
  4462. reader = this._reader,
  4463. tt = Tokens.STRING,
  4464. c = reader.read(),
  4465. i;
  4466. while (c) {
  4467. string += c;
  4468. if (c === "\\") {
  4469. c = reader.read();
  4470. if (c === null) {
  4471. break; // premature EOF after backslash
  4472. } else if (/[^\r\n\f0-9a-f]/i.test(c)) {
  4473. // single-character escape
  4474. string += c;
  4475. } else {
  4476. // read up to six hex digits
  4477. for (i=0; isHexDigit(c) && i<6; i++) {
  4478. string += c;
  4479. c = reader.read();
  4480. }
  4481. // swallow trailing newline or space
  4482. if (c === "\r" && reader.peek() === "\n") {
  4483. string += c;
  4484. c = reader.read();
  4485. }
  4486. if (isWhitespace(c)) {
  4487. string += c;
  4488. } else {
  4489. // This character is null or not part of the escape;
  4490. // jump back to the top to process it.
  4491. continue;
  4492. }
  4493. }
  4494. } else if (c === delim) {
  4495. break; // delimiter found.
  4496. } else if (isNewLine(reader.peek())) {
  4497. // newline without an escapement: it's an invalid string
  4498. tt = Tokens.INVALID;
  4499. break;
  4500. }
  4501. c = reader.read();
  4502. }
  4503. //if c is null, that means we're out of input and the string was never closed
  4504. if (c === null) {
  4505. tt = Tokens.INVALID;
  4506. }
  4507. return this.createToken(tt, string, startLine, startCol);
  4508. },
  4509. unicodeRangeToken: function(first, startLine, startCol) {
  4510. var reader = this._reader,
  4511. value = first,
  4512. temp,
  4513. tt = Tokens.CHAR;
  4514. //then it should be a unicode range
  4515. if (reader.peek() === "+") {
  4516. reader.mark();
  4517. value += reader.read();
  4518. value += this.readUnicodeRangePart(true);
  4519. //ensure there's an actual unicode range here
  4520. if (value.length === 2) {
  4521. reader.reset();
  4522. } else {
  4523. tt = Tokens.UNICODE_RANGE;
  4524. //if there's a ? in the first part, there can't be a second part
  4525. if (value.indexOf("?") === -1) {
  4526. if (reader.peek() === "-") {
  4527. reader.mark();
  4528. temp = reader.read();
  4529. temp += this.readUnicodeRangePart(false);
  4530. //if there's not another value, back up and just take the first
  4531. if (temp.length === 1) {
  4532. reader.reset();
  4533. } else {
  4534. value += temp;
  4535. }
  4536. }
  4537. }
  4538. }
  4539. }
  4540. return this.createToken(tt, value, startLine, startCol);
  4541. },
  4542. /**
  4543. * Produces a S token based on the specified information. Since whitespace
  4544. * may have multiple characters, this consumes all whitespace characters
  4545. * into a single token.
  4546. * @param {String} first The first character in the token.
  4547. * @param {int} startLine The beginning line for the character.
  4548. * @param {int} startCol The beginning column for the character.
  4549. * @return {Object} A token object.
  4550. * @method whitespaceToken
  4551. */
  4552. whitespaceToken: function(first, startLine, startCol) {
  4553. var value = first + this.readWhitespace();
  4554. return this.createToken(Tokens.S, value, startLine, startCol);
  4555. },
  4556. //-------------------------------------------------------------------------
  4557. // Methods to read values from the string stream
  4558. //-------------------------------------------------------------------------
  4559. readUnicodeRangePart: function(allowQuestionMark) {
  4560. var reader = this._reader,
  4561. part = "",
  4562. c = reader.peek();
  4563. //first read hex digits
  4564. while (isHexDigit(c) && part.length < 6) {
  4565. reader.read();
  4566. part += c;
  4567. c = reader.peek();
  4568. }
  4569. //then read question marks if allowed
  4570. if (allowQuestionMark) {
  4571. while (c === "?" && part.length < 6) {
  4572. reader.read();
  4573. part += c;
  4574. c = reader.peek();
  4575. }
  4576. }
  4577. //there can't be any other characters after this point
  4578. return part;
  4579. },
  4580. readWhitespace: function() {
  4581. var reader = this._reader,
  4582. whitespace = "",
  4583. c = reader.peek();
  4584. while (isWhitespace(c)) {
  4585. reader.read();
  4586. whitespace += c;
  4587. c = reader.peek();
  4588. }
  4589. return whitespace;
  4590. },
  4591. readNumber: function(first) {
  4592. var reader = this._reader,
  4593. number = first,
  4594. hasDot = (first === "."),
  4595. c = reader.peek();
  4596. while (c) {
  4597. if (isDigit(c)) {
  4598. number += reader.read();
  4599. } else if (c === ".") {
  4600. if (hasDot) {
  4601. break;
  4602. } else {
  4603. hasDot = true;
  4604. number += reader.read();
  4605. }
  4606. } else {
  4607. break;
  4608. }
  4609. c = reader.peek();
  4610. }
  4611. return number;
  4612. },
  4613. // returns null w/o resetting reader if string is invalid.
  4614. readString: function() {
  4615. var token = this.stringToken(this._reader.read(), 0, 0);
  4616. return token.type === Tokens.INVALID ? null : token.value;
  4617. },
  4618. // returns null w/o resetting reader if URI is invalid.
  4619. readURI: function(first) {
  4620. var reader = this._reader,
  4621. uri = first,
  4622. inner = "",
  4623. c = reader.peek();
  4624. //skip whitespace before
  4625. while (c && isWhitespace(c)) {
  4626. reader.read();
  4627. c = reader.peek();
  4628. }
  4629. //it's a string
  4630. if (c === "'" || c === "\"") {
  4631. inner = this.readString();
  4632. if (inner !== null) {
  4633. inner = PropertyValuePart.parseString(inner);
  4634. }
  4635. } else {
  4636. inner = this.readUnquotedURL();
  4637. }
  4638. c = reader.peek();
  4639. //skip whitespace after
  4640. while (c && isWhitespace(c)) {
  4641. reader.read();
  4642. c = reader.peek();
  4643. }
  4644. //if there was no inner value or the next character isn't closing paren, it's not a URI
  4645. if (inner === null || c !== ")") {
  4646. uri = null;
  4647. } else {
  4648. // Ensure argument to URL is always double-quoted
  4649. // (This simplifies later processing in PropertyValuePart.)
  4650. uri += PropertyValuePart.serializeString(inner) + reader.read();
  4651. }
  4652. return uri;
  4653. },
  4654. // This method never fails, although it may return an empty string.
  4655. readUnquotedURL: function(first) {
  4656. var reader = this._reader,
  4657. url = first || "",
  4658. c;
  4659. for (c = reader.peek(); c; c = reader.peek()) {
  4660. // Note that the grammar at
  4661. // https://www.w3.org/TR/CSS2/grammar.html#scanner
  4662. // incorrectly includes the backslash character in the
  4663. // `url` production, although it is correctly omitted in
  4664. // the `baduri1` production.
  4665. if (nonascii.test(c) || /^[\-!#$%&*-\[\]-~]$/.test(c)) {
  4666. url += c;
  4667. reader.read();
  4668. } else if (c === "\\") {
  4669. if (/^[^\r\n\f]$/.test(reader.peek(2))) {
  4670. url += this.readEscape(reader.read(), true);
  4671. } else {
  4672. break; // bad escape sequence.
  4673. }
  4674. } else {
  4675. break; // bad character
  4676. }
  4677. }
  4678. return url;
  4679. },
  4680. readName: function(first) {
  4681. var reader = this._reader,
  4682. ident = first || "",
  4683. c;
  4684. for (c = reader.peek(); c; c = reader.peek()) {
  4685. if (c === "\\") {
  4686. if (/^[^\r\n\f]$/.test(reader.peek(2))) {
  4687. ident += this.readEscape(reader.read(), true);
  4688. } else {
  4689. // Bad escape sequence.
  4690. break;
  4691. }
  4692. } else if (isNameChar(c)) {
  4693. ident += reader.read();
  4694. } else {
  4695. break;
  4696. }
  4697. }
  4698. return ident;
  4699. },
  4700. readEscape: function(first, unescape) {
  4701. var reader = this._reader,
  4702. cssEscape = first || "",
  4703. i = 0,
  4704. c = reader.peek();
  4705. if (isHexDigit(c)) {
  4706. do {
  4707. cssEscape += reader.read();
  4708. c = reader.peek();
  4709. } while (c && isHexDigit(c) && ++i < 6);
  4710. }
  4711. if (cssEscape.length === 1) {
  4712. if (/^[^\r\n\f0-9a-f]$/.test(c)) {
  4713. reader.read();
  4714. if (unescape) {
  4715. return c;
  4716. }
  4717. } else {
  4718. // We should never get here (readName won't call readEscape
  4719. // if the escape sequence is bad).
  4720. throw new Error("Bad escape sequence.");
  4721. }
  4722. } else if (c === "\r") {
  4723. reader.read();
  4724. if (reader.peek() === "\n") {
  4725. c += reader.read();
  4726. }
  4727. } else if (/^[ \t\n\f]$/.test(c)) {
  4728. reader.read();
  4729. } else {
  4730. c = "";
  4731. }
  4732. if (unescape) {
  4733. var cp = parseInt(cssEscape.slice(first.length), 16);
  4734. return String.fromCodePoint ? String.fromCodePoint(cp) :
  4735. String.fromCharCode(cp);
  4736. }
  4737. return cssEscape + c;
  4738. },
  4739. readComment: function(first) {
  4740. var reader = this._reader,
  4741. comment = first || "",
  4742. c = reader.read();
  4743. if (c === "*") {
  4744. while (c) {
  4745. comment += c;
  4746. //look for end of comment
  4747. if (comment.length > 2 && c === "*" && reader.peek() === "/") {
  4748. comment += reader.read();
  4749. break;
  4750. }
  4751. c = reader.read();
  4752. }
  4753. return comment;
  4754. } else {
  4755. return "";
  4756. }
  4757. }
  4758. });
  4759. },{"../util/TokenStreamBase":27,"./PropertyValuePart":11,"./Tokens":18}],18:[function(require,module,exports){
  4760. "use strict";
  4761. var Tokens = module.exports = [
  4762. /*
  4763. * The following token names are defined in CSS3 Grammar: https://www.w3.org/TR/css3-syntax/#lexical
  4764. */
  4765. // HTML-style comments
  4766. { name: "CDO" },
  4767. { name: "CDC" },
  4768. // ignorables
  4769. { name: "S", whitespace: true/*, channel: "ws"*/ },
  4770. { name: "COMMENT", comment: true, hide: true, channel: "comment" },
  4771. // attribute equality
  4772. { name: "INCLUDES", text: "~=" },
  4773. { name: "DASHMATCH", text: "|=" },
  4774. { name: "PREFIXMATCH", text: "^=" },
  4775. { name: "SUFFIXMATCH", text: "$=" },
  4776. { name: "SUBSTRINGMATCH", text: "*=" },
  4777. // identifier types
  4778. { name: "STRING" },
  4779. { name: "IDENT" },
  4780. { name: "HASH" },
  4781. // at-keywords
  4782. { name: "IMPORT_SYM", text: "@import" },
  4783. { name: "PAGE_SYM", text: "@page" },
  4784. { name: "MEDIA_SYM", text: "@media" },
  4785. { name: "FONT_FACE_SYM", text: "@font-face" },
  4786. { name: "CHARSET_SYM", text: "@charset" },
  4787. { name: "NAMESPACE_SYM", text: "@namespace" },
  4788. { name: "SUPPORTS_SYM", text: "@supports" },
  4789. { name: "VIEWPORT_SYM", text: ["@viewport", "@-ms-viewport", "@-o-viewport"] },
  4790. { name: "DOCUMENT_SYM", text: ["@document", "@-moz-document"] },
  4791. { name: "UNKNOWN_SYM" },
  4792. //{ name: "ATKEYWORD"},
  4793. // CSS3 animations
  4794. { name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-o-keyframes" ] },
  4795. // important symbol
  4796. { name: "IMPORTANT_SYM" },
  4797. // measurements
  4798. { name: "LENGTH" },
  4799. { name: "ANGLE" },
  4800. { name: "TIME" },
  4801. { name: "FREQ" },
  4802. { name: "DIMENSION" },
  4803. { name: "PERCENTAGE" },
  4804. { name: "NUMBER" },
  4805. // functions
  4806. { name: "URI" },
  4807. { name: "FUNCTION" },
  4808. // Unicode ranges
  4809. { name: "UNICODE_RANGE" },
  4810. /*
  4811. * The following token names are defined in CSS3 Selectors: https://www.w3.org/TR/css3-selectors/#selector-syntax
  4812. */
  4813. // invalid string
  4814. { name: "INVALID" },
  4815. // combinators
  4816. { name: "PLUS", text: "+" },
  4817. { name: "GREATER", text: ">" },
  4818. { name: "COMMA", text: "," },
  4819. { name: "TILDE", text: "~" },
  4820. // modifier
  4821. { name: "NOT" },
  4822. /*
  4823. * Defined in CSS3 Paged Media
  4824. */
  4825. { name: "TOPLEFTCORNER_SYM", text: "@top-left-corner" },
  4826. { name: "TOPLEFT_SYM", text: "@top-left" },
  4827. { name: "TOPCENTER_SYM", text: "@top-center" },
  4828. { name: "TOPRIGHT_SYM", text: "@top-right" },
  4829. { name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner" },
  4830. { name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner" },
  4831. { name: "BOTTOMLEFT_SYM", text: "@bottom-left" },
  4832. { name: "BOTTOMCENTER_SYM", text: "@bottom-center" },
  4833. { name: "BOTTOMRIGHT_SYM", text: "@bottom-right" },
  4834. { name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner" },
  4835. { name: "LEFTTOP_SYM", text: "@left-top" },
  4836. { name: "LEFTMIDDLE_SYM", text: "@left-middle" },
  4837. { name: "LEFTBOTTOM_SYM", text: "@left-bottom" },
  4838. { name: "RIGHTTOP_SYM", text: "@right-top" },
  4839. { name: "RIGHTMIDDLE_SYM", text: "@right-middle" },
  4840. { name: "RIGHTBOTTOM_SYM", text: "@right-bottom" },
  4841. /*
  4842. * The following token names are defined in CSS3 Media Queries: https://www.w3.org/TR/css3-mediaqueries/#syntax
  4843. */
  4844. /*{ name: "MEDIA_ONLY", state: "media"},
  4845. { name: "MEDIA_NOT", state: "media"},
  4846. { name: "MEDIA_AND", state: "media"},*/
  4847. { name: "RESOLUTION", state: "media" },
  4848. /*
  4849. * The following token names are not defined in any CSS specification but are used by the lexer.
  4850. */
  4851. // not a real token, but useful for stupid IE filters
  4852. { name: "IE_FUNCTION" },
  4853. // part of CSS3 grammar but not the Flex code
  4854. { name: "CHAR" },
  4855. // TODO: Needed?
  4856. // Not defined as tokens, but might as well be
  4857. {
  4858. name: "PIPE",
  4859. text: "|"
  4860. },
  4861. {
  4862. name: "SLASH",
  4863. text: "/"
  4864. },
  4865. {
  4866. name: "MINUS",
  4867. text: "-"
  4868. },
  4869. {
  4870. name: "STAR",
  4871. text: "*"
  4872. },
  4873. {
  4874. name: "LBRACE",
  4875. endChar: "}",
  4876. text: "{"
  4877. },
  4878. {
  4879. name: "RBRACE",
  4880. text: "}"
  4881. },
  4882. {
  4883. name: "LBRACKET",
  4884. endChar: "]",
  4885. text: "["
  4886. },
  4887. {
  4888. name: "RBRACKET",
  4889. text: "]"
  4890. },
  4891. {
  4892. name: "EQUALS",
  4893. text: "="
  4894. },
  4895. {
  4896. name: "COLON",
  4897. text: ":"
  4898. },
  4899. {
  4900. name: "SEMICOLON",
  4901. text: ";"
  4902. },
  4903. {
  4904. name: "LPAREN",
  4905. endChar: ")",
  4906. text: "("
  4907. },
  4908. {
  4909. name: "RPAREN",
  4910. text: ")"
  4911. },
  4912. {
  4913. name: "DOT",
  4914. text: "."
  4915. }
  4916. ];
  4917. (function() {
  4918. var nameMap = [],
  4919. typeMap = Object.create(null);
  4920. Tokens.UNKNOWN = -1;
  4921. Tokens.unshift({ name:"EOF" });
  4922. for (var i=0, len = Tokens.length; i < len; i++) {
  4923. nameMap.push(Tokens[i].name);
  4924. Tokens[Tokens[i].name] = i;
  4925. if (Tokens[i].text) {
  4926. if (Tokens[i].text instanceof Array) {
  4927. for (var j=0; j < Tokens[i].text.length; j++) {
  4928. typeMap[Tokens[i].text[j]] = i;
  4929. }
  4930. } else {
  4931. typeMap[Tokens[i].text] = i;
  4932. }
  4933. }
  4934. }
  4935. Tokens.name = function(tt) {
  4936. return nameMap[tt];
  4937. };
  4938. Tokens.type = function(c) {
  4939. return typeMap[c] || -1;
  4940. };
  4941. })();
  4942. },{}],19:[function(require,module,exports){
  4943. "use strict";
  4944. /* exported Validation */
  4945. var Matcher = require("./Matcher");
  4946. var Properties = require("./Properties");
  4947. var ValidationTypes = require("./ValidationTypes");
  4948. var ValidationError = require("./ValidationError");
  4949. var PropertyValueIterator = require("./PropertyValueIterator");
  4950. var Validation = module.exports = {
  4951. validate: function(property, value) {
  4952. //normalize name
  4953. var name = property.toString().toLowerCase(),
  4954. expression = new PropertyValueIterator(value),
  4955. spec = Properties[name],
  4956. part;
  4957. if (!spec) {
  4958. if (name.indexOf("-") !== 0) { //vendor prefixed are ok
  4959. throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
  4960. }
  4961. } else if (typeof spec !== "number") {
  4962. // All properties accept some CSS-wide values.
  4963. // https://drafts.csswg.org/css-values-3/#common-keywords
  4964. if (ValidationTypes.isAny(expression, "inherit | initial | unset")) {
  4965. if (expression.hasNext()) {
  4966. part = expression.next();
  4967. throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
  4968. }
  4969. return;
  4970. }
  4971. // Property-specific validation.
  4972. this.singleProperty(spec, expression);
  4973. }
  4974. },
  4975. singleProperty: function(types, expression) {
  4976. var result = false,
  4977. value = expression.value,
  4978. part;
  4979. result = Matcher.parse(types).match(expression);
  4980. if (!result) {
  4981. if (expression.hasNext() && !expression.isFirst()) {
  4982. part = expression.peek();
  4983. throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
  4984. } else {
  4985. throw new ValidationError("Expected (" + ValidationTypes.describe(types) + ") but found '" + value + "'.", value.line, value.col);
  4986. }
  4987. } else if (expression.hasNext()) {
  4988. part = expression.next();
  4989. throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
  4990. }
  4991. }
  4992. };
  4993. },{"./Matcher":3,"./Properties":7,"./PropertyValueIterator":10,"./ValidationError":20,"./ValidationTypes":21}],20:[function(require,module,exports){
  4994. "use strict";
  4995. module.exports = ValidationError;
  4996. /**
  4997. * Type to use when a validation error occurs.
  4998. * @class ValidationError
  4999. * @namespace parserlib.util
  5000. * @constructor
  5001. * @param {String} message The error message.
  5002. * @param {int} line The line at which the error occurred.
  5003. * @param {int} col The column at which the error occurred.
  5004. */
  5005. function ValidationError(message, line, col) {
  5006. /**
  5007. * The column at which the error occurred.
  5008. * @type int
  5009. * @property col
  5010. */
  5011. this.col = col;
  5012. /**
  5013. * The line at which the error occurred.
  5014. * @type int
  5015. * @property line
  5016. */
  5017. this.line = line;
  5018. /**
  5019. * The text representation of the unit.
  5020. * @type String
  5021. * @property text
  5022. */
  5023. this.message = message;
  5024. }
  5025. //inherit from Error
  5026. ValidationError.prototype = new Error();
  5027. },{}],21:[function(require,module,exports){
  5028. "use strict";
  5029. var ValidationTypes = module.exports;
  5030. var Matcher = require("./Matcher");
  5031. function copy(to, from) {
  5032. Object.keys(from).forEach(function(prop) {
  5033. to[prop] = from[prop];
  5034. });
  5035. }
  5036. copy(ValidationTypes, {
  5037. isLiteral: function (part, literals) {
  5038. var text = part.text.toString().toLowerCase(),
  5039. args = literals.split(" | "),
  5040. i, len, found = false;
  5041. for (i=0, len=args.length; i < len && !found; i++) {
  5042. if (args[i].charAt(0) === "<") {
  5043. found = this.simple[args[i]](part);
  5044. } else if (args[i].slice(-2) === "()") {
  5045. found = (part.type === "function" &&
  5046. part.name === args[i].slice(0, -2));
  5047. } else if (text === args[i].toLowerCase()) {
  5048. found = true;
  5049. }
  5050. }
  5051. return found;
  5052. },
  5053. isSimple: function(type) {
  5054. return Boolean(this.simple[type]);
  5055. },
  5056. isComplex: function(type) {
  5057. return Boolean(this.complex[type]);
  5058. },
  5059. describe: function(type) {
  5060. if (this.complex[type] instanceof Matcher) {
  5061. return this.complex[type].toString(0);
  5062. }
  5063. return type;
  5064. },
  5065. /**
  5066. * Determines if the next part(s) of the given expression
  5067. * are any of the given types.
  5068. */
  5069. isAny: function (expression, types) {
  5070. var args = types.split(" | "),
  5071. i, len, found = false;
  5072. for (i=0, len=args.length; i < len && !found && expression.hasNext(); i++) {
  5073. found = this.isType(expression, args[i]);
  5074. }
  5075. return found;
  5076. },
  5077. /**
  5078. * Determines if the next part(s) of the given expression
  5079. * are one of a group.
  5080. */
  5081. isAnyOfGroup: function(expression, types) {
  5082. var args = types.split(" || "),
  5083. i, len, found = false;
  5084. for (i=0, len=args.length; i < len && !found; i++) {
  5085. found = this.isType(expression, args[i]);
  5086. }
  5087. return found ? args[i-1] : false;
  5088. },
  5089. /**
  5090. * Determines if the next part(s) of the given expression
  5091. * are of a given type.
  5092. */
  5093. isType: function (expression, type) {
  5094. var part = expression.peek(),
  5095. result = false;
  5096. if (type.charAt(0) !== "<") {
  5097. result = this.isLiteral(part, type);
  5098. if (result) {
  5099. expression.next();
  5100. }
  5101. } else if (this.simple[type]) {
  5102. result = this.simple[type](part);
  5103. if (result) {
  5104. expression.next();
  5105. }
  5106. } else if (this.complex[type] instanceof Matcher) {
  5107. result = this.complex[type].match(expression);
  5108. } else {
  5109. result = this.complex[type](expression);
  5110. }
  5111. return result;
  5112. },
  5113. simple: {
  5114. __proto__: null,
  5115. "<absolute-size>":
  5116. "xx-small | x-small | small | medium | large | x-large | xx-large",
  5117. "<animateable-feature>":
  5118. "scroll-position | contents | <animateable-feature-name>",
  5119. "<animateable-feature-name>": function(part) {
  5120. return this["<ident>"](part) &&
  5121. !/^(unset|initial|inherit|will-change|auto|scroll-position|contents)$/i.test(part);
  5122. },
  5123. "<angle>": function(part) {
  5124. return part.type === "angle";
  5125. },
  5126. "<attachment>": "scroll | fixed | local",
  5127. "<attr>": "attr()",
  5128. // inset() = inset( <shape-arg>{1,4} [round <border-radius>]? )
  5129. // circle() = circle( [<shape-radius>]? [at <position>]? )
  5130. // ellipse() = ellipse( [<shape-radius>{2}]? [at <position>]? )
  5131. // polygon() = polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# )
  5132. "<basic-shape>": "inset() | circle() | ellipse() | polygon()",
  5133. "<bg-image>": "<image> | <gradient> | none",
  5134. "<border-style>":
  5135. "none | hidden | dotted | dashed | solid | double | groove | " +
  5136. "ridge | inset | outset",
  5137. "<border-width>": "<length> | thin | medium | thick",
  5138. "<box>": "padding-box | border-box | content-box",
  5139. "<clip-source>": "<uri>",
  5140. "<color>": function(part) {
  5141. return part.type === "color" || String(part) === "transparent" || String(part) === "currentColor";
  5142. },
  5143. // The SVG <color> spec doesn't include "currentColor" or "transparent" as a color.
  5144. "<color-svg>": function(part) {
  5145. return part.type === "color";
  5146. },
  5147. "<content>": "content()",
  5148. // https://www.w3.org/TR/css3-sizing/#width-height-keywords
  5149. "<content-sizing>":
  5150. "fill-available | -moz-available | -webkit-fill-available | " +
  5151. "max-content | -moz-max-content | -webkit-max-content | " +
  5152. "min-content | -moz-min-content | -webkit-min-content | " +
  5153. "fit-content | -moz-fit-content | -webkit-fit-content",
  5154. "<feature-tag-value>": function(part) {
  5155. return part.type === "function" && /^[A-Z0-9]{4}$/i.test(part);
  5156. },
  5157. // custom() isn't actually in the spec
  5158. "<filter-function>":
  5159. "blur() | brightness() | contrast() | custom() | " +
  5160. "drop-shadow() | grayscale() | hue-rotate() | invert() | " +
  5161. "opacity() | saturate() | sepia()",
  5162. "<flex-basis>": "<width>",
  5163. "<flex-direction>": "row | row-reverse | column | column-reverse",
  5164. "<flex-grow>": "<number>",
  5165. "<flex-shrink>": "<number>",
  5166. "<flex-wrap>": "nowrap | wrap | wrap-reverse",
  5167. "<font-size>":
  5168. "<absolute-size> | <relative-size> | <length> | <percentage>",
  5169. "<font-stretch>":
  5170. "normal | ultra-condensed | extra-condensed | condensed | " +
  5171. "semi-condensed | semi-expanded | expanded | extra-expanded | " +
  5172. "ultra-expanded",
  5173. "<font-style>": "normal | italic | oblique",
  5174. "<font-variant-caps>":
  5175. "small-caps | all-small-caps | petite-caps | all-petite-caps | " +
  5176. "unicase | titling-caps",
  5177. "<font-variant-css21>": "normal | small-caps",
  5178. "<font-weight>":
  5179. "normal | bold | bolder | lighter | " +
  5180. "100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900",
  5181. "<generic-family>":
  5182. "serif | sans-serif | cursive | fantasy | monospace",
  5183. "<geometry-box>": "<shape-box> | fill-box | stroke-box | view-box",
  5184. "<glyph-angle>": function(part) {
  5185. return part.type === "angle" && part.units === "deg";
  5186. },
  5187. "<gradient>": function(part) {
  5188. return part.type === "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(part);
  5189. },
  5190. "<icccolor>":
  5191. "cielab() | cielch() | cielchab() | " +
  5192. "icc-color() | icc-named-color()",
  5193. //any identifier
  5194. "<ident>": function(part) {
  5195. return part.type === "identifier" || part.wasIdent;
  5196. },
  5197. "<ident-not-generic-family>": function(part) {
  5198. return this["<ident>"](part) && !this["<generic-family>"](part);
  5199. },
  5200. "<image>": "<uri>",
  5201. "<integer>": function(part) {
  5202. return part.type === "integer";
  5203. },
  5204. "<length>": function(part) {
  5205. if (part.type === "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?calc/i.test(part)) {
  5206. return true;
  5207. } else {
  5208. return part.type === "length" || part.type === "number" || part.type === "integer" || String(part) === "0";
  5209. }
  5210. },
  5211. "<line>": function(part) {
  5212. return part.type === "integer";
  5213. },
  5214. "<line-height>": "<number> | <length> | <percentage> | normal",
  5215. "<margin-width>": "<length> | <percentage> | auto",
  5216. "<miterlimit>": function(part) {
  5217. return this["<number>"](part) && part.value >= 1;
  5218. },
  5219. "<nonnegative-length-or-percentage>": function(part) {
  5220. return (this["<length>"](part) || this["<percentage>"](part)) &&
  5221. (String(part) === "0" || part.type === "function" || (part.value) >= 0);
  5222. },
  5223. "<nonnegative-number-or-percentage>": function(part) {
  5224. return (this["<number>"](part) || this["<percentage>"](part)) &&
  5225. (String(part) === "0" || part.type === "function" || (part.value) >= 0);
  5226. },
  5227. "<number>": function(part) {
  5228. return part.type === "number" || this["<integer>"](part);
  5229. },
  5230. "<opacity-value>": function(part) {
  5231. return this["<number>"](part) && part.value >= 0 && part.value <= 1;
  5232. },
  5233. "<padding-width>": "<nonnegative-length-or-percentage>",
  5234. "<percentage>": function(part) {
  5235. return part.type === "percentage" || String(part) === "0";
  5236. },
  5237. "<relative-size>": "smaller | larger",
  5238. "<shape>": "rect() | inset-rect()",
  5239. "<shape-box>": "<box> | margin-box",
  5240. "<single-animation-direction>":
  5241. "normal | reverse | alternate | alternate-reverse",
  5242. "<single-animation-name>": function(part) {
  5243. return this["<ident>"](part) &&
  5244. /^-?[a-z_][-a-z0-9_]+$/i.test(part) &&
  5245. !/^(none|unset|initial|inherit)$/i.test(part);
  5246. },
  5247. "<string>": function(part) {
  5248. return part.type === "string";
  5249. },
  5250. "<time>": function(part) {
  5251. return part.type === "time";
  5252. },
  5253. "<uri>": function(part) {
  5254. return part.type === "uri";
  5255. },
  5256. "<width>": "<margin-width>"
  5257. },
  5258. complex: {
  5259. __proto__: null,
  5260. "<azimuth>":
  5261. "<angle>" +
  5262. " | " +
  5263. "[ [ left-side | far-left | left | center-left | center | " +
  5264. "center-right | right | far-right | right-side ] || behind ]" +
  5265. " | "+
  5266. "leftwards | rightwards",
  5267. "<bg-position>": "<position>#",
  5268. "<bg-size>":
  5269. "[ <length> | <percentage> | auto ]{1,2} | cover | contain",
  5270. "<border-image-slice>":
  5271. // [<number> | <percentage>]{1,4} && fill?
  5272. // *but* fill can appear between any of the numbers
  5273. Matcher.many([true /* first element is required */],
  5274. Matcher.cast("<nonnegative-number-or-percentage>"),
  5275. Matcher.cast("<nonnegative-number-or-percentage>"),
  5276. Matcher.cast("<nonnegative-number-or-percentage>"),
  5277. Matcher.cast("<nonnegative-number-or-percentage>"),
  5278. "fill"),
  5279. "<border-radius>":
  5280. "<nonnegative-length-or-percentage>{1,4} " +
  5281. "[ / <nonnegative-length-or-percentage>{1,4} ]?",
  5282. "<box-shadow>": "none | <shadow>#",
  5283. "<clip-path>": "<basic-shape> || <geometry-box>",
  5284. "<dasharray>":
  5285. // "list of comma and/or white space separated <length>s and
  5286. // <percentage>s". There is a non-negative constraint.
  5287. Matcher.cast("<nonnegative-length-or-percentage>")
  5288. .braces(1, Infinity, "#", Matcher.cast(",").question()),
  5289. "<family-name>":
  5290. // <string> | <IDENT>+
  5291. "<string> | <ident-not-generic-family> <ident>*",
  5292. "<filter-function-list>": "[ <filter-function> | <uri> ]+",
  5293. // https://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#flex-property
  5294. "<flex>":
  5295. "none | [ <flex-grow> <flex-shrink>? || <flex-basis> ]",
  5296. "<font-family>": "[ <generic-family> | <family-name> ]#",
  5297. "<font-shorthand>":
  5298. "[ <font-style> || <font-variant-css21> || " +
  5299. "<font-weight> || <font-stretch> ]? <font-size> " +
  5300. "[ / <line-height> ]? <font-family>",
  5301. "<font-variant-alternates>":
  5302. // stylistic(<feature-value-name>)
  5303. "stylistic() || " +
  5304. "historical-forms || " +
  5305. // styleset(<feature-value-name> #)
  5306. "styleset() || " +
  5307. // character-variant(<feature-value-name> #)
  5308. "character-variant() || " +
  5309. // swash(<feature-value-name>)
  5310. "swash() || " +
  5311. // ornaments(<feature-value-name>)
  5312. "ornaments() || " +
  5313. // annotation(<feature-value-name>)
  5314. "annotation()",
  5315. "<font-variant-ligatures>":
  5316. // <common-lig-values>
  5317. "[ common-ligatures | no-common-ligatures ] || " +
  5318. // <discretionary-lig-values>
  5319. "[ discretionary-ligatures | no-discretionary-ligatures ] || " +
  5320. // <historical-lig-values>
  5321. "[ historical-ligatures | no-historical-ligatures ] || " +
  5322. // <contextual-alt-values>
  5323. "[ contextual | no-contextual ]",
  5324. "<font-variant-numeric>":
  5325. // <numeric-figure-values>
  5326. "[ lining-nums | oldstyle-nums ] || " +
  5327. // <numeric-spacing-values>
  5328. "[ proportional-nums | tabular-nums ] || " +
  5329. // <numeric-fraction-values>
  5330. "[ diagonal-fractions | stacked-fractions ] || " +
  5331. "ordinal || slashed-zero",
  5332. "<font-variant-east-asian>":
  5333. // <east-asian-variant-values>
  5334. "[ jis78 | jis83 | jis90 | jis04 | simplified | traditional ] || " +
  5335. // <east-asian-width-values>
  5336. "[ full-width | proportional-width ] || " +
  5337. "ruby",
  5338. // Note that <color> here is "as defined in the SVG spec", which
  5339. // is more restrictive that the <color> defined in the CSS spec.
  5340. // none | currentColor | <color> [<icccolor>]? |
  5341. // <funciri> [ none | currentColor | <color> [<icccolor>]? ]?
  5342. "<paint>": "<paint-basic> | <uri> <paint-basic>?",
  5343. // Helper definition for <paint> above.
  5344. "<paint-basic>": "none | currentColor | <color-svg> <icccolor>?",
  5345. "<position>":
  5346. // Because our `alt` combinator is ordered, we need to test these
  5347. // in order from longest possible match to shortest.
  5348. "[ center | [ left | right ] [ <percentage> | <length> ]? ] && " +
  5349. "[ center | [ top | bottom ] [ <percentage> | <length> ]? ]" +
  5350. " | " +
  5351. "[ left | center | right | <percentage> | <length> ] " +
  5352. "[ top | center | bottom | <percentage> | <length> ]" +
  5353. " | " +
  5354. "[ left | center | right | top | bottom | <percentage> | <length> ]",
  5355. "<repeat-style>":
  5356. "repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}",
  5357. "<shadow>":
  5358. //inset? && [ <length>{2,4} && <color>? ]
  5359. Matcher.many([true /* length is required */],
  5360. Matcher.cast("<length>").braces(2, 4), "inset", "<color>"),
  5361. "<text-decoration-color>":
  5362. "<color>",
  5363. "<text-decoration-line>":
  5364. "none | [ underline || overline || line-through || blink ]",
  5365. "<text-decoration-style>":
  5366. "solid | double | dotted | dashed | wavy",
  5367. "<will-change>":
  5368. "auto | <animateable-feature>#",
  5369. "<x-one-radius>":
  5370. //[ <length> | <percentage> ] [ <length> | <percentage> ]?
  5371. "[ <length> | <percentage> ]{1,2}"
  5372. }
  5373. });
  5374. Object.keys(ValidationTypes.simple).forEach(function(nt) {
  5375. var rule = ValidationTypes.simple[nt];
  5376. if (typeof rule === "string") {
  5377. ValidationTypes.simple[nt] = function(part) {
  5378. return ValidationTypes.isLiteral(part, rule);
  5379. };
  5380. }
  5381. });
  5382. Object.keys(ValidationTypes.complex).forEach(function(nt) {
  5383. var rule = ValidationTypes.complex[nt];
  5384. if (typeof rule === "string") {
  5385. ValidationTypes.complex[nt] = Matcher.parse(rule);
  5386. }
  5387. });
  5388. // Because this is defined relative to other complex validation types,
  5389. // we need to define it *after* the rest of the types are initialized.
  5390. ValidationTypes.complex["<font-variant>"] =
  5391. Matcher.oror({ expand: "<font-variant-ligatures>" },
  5392. { expand: "<font-variant-alternates>" },
  5393. "<font-variant-caps>",
  5394. { expand: "<font-variant-numeric>" },
  5395. { expand: "<font-variant-east-asian>" });
  5396. },{"./Matcher":3}],22:[function(require,module,exports){
  5397. "use strict";
  5398. module.exports = {
  5399. Colors : require("./Colors"),
  5400. Combinator : require("./Combinator"),
  5401. Parser : require("./Parser"),
  5402. PropertyName : require("./PropertyName"),
  5403. PropertyValue : require("./PropertyValue"),
  5404. PropertyValuePart : require("./PropertyValuePart"),
  5405. Matcher : require("./Matcher"),
  5406. MediaFeature : require("./MediaFeature"),
  5407. MediaQuery : require("./MediaQuery"),
  5408. Selector : require("./Selector"),
  5409. SelectorPart : require("./SelectorPart"),
  5410. SelectorSubPart : require("./SelectorSubPart"),
  5411. Specificity : require("./Specificity"),
  5412. TokenStream : require("./TokenStream"),
  5413. Tokens : require("./Tokens"),
  5414. ValidationError : require("./ValidationError")
  5415. };
  5416. },{"./Colors":1,"./Combinator":2,"./Matcher":3,"./MediaFeature":4,"./MediaQuery":5,"./Parser":6,"./PropertyName":8,"./PropertyValue":9,"./PropertyValuePart":11,"./Selector":13,"./SelectorPart":14,"./SelectorSubPart":15,"./Specificity":16,"./TokenStream":17,"./Tokens":18,"./ValidationError":20}],23:[function(require,module,exports){
  5417. "use strict";
  5418. module.exports = EventTarget;
  5419. /**
  5420. * A generic base to inherit from for any object
  5421. * that needs event handling.
  5422. * @class EventTarget
  5423. * @constructor
  5424. */
  5425. function EventTarget() {
  5426. /**
  5427. * The array of listeners for various events.
  5428. * @type Object
  5429. * @property _listeners
  5430. * @private
  5431. */
  5432. this._listeners = Object.create(null);
  5433. }
  5434. EventTarget.prototype = {
  5435. //restore constructor
  5436. constructor: EventTarget,
  5437. /**
  5438. * Adds a listener for a given event type.
  5439. * @param {String} type The type of event to add a listener for.
  5440. * @param {Function} listener The function to call when the event occurs.
  5441. * @return {void}
  5442. * @method addListener
  5443. */
  5444. addListener: function(type, listener) {
  5445. if (!this._listeners[type]) {
  5446. this._listeners[type] = [];
  5447. }
  5448. this._listeners[type].push(listener);
  5449. },
  5450. /**
  5451. * Fires an event based on the passed-in object.
  5452. * @param {Object|String} event An object with at least a 'type' attribute
  5453. * or a string indicating the event name.
  5454. * @return {void}
  5455. * @method fire
  5456. */
  5457. fire: function(event) {
  5458. if (typeof event === "string") {
  5459. event = { type: event };
  5460. }
  5461. if (typeof event.target !== "undefined") {
  5462. event.target = this;
  5463. }
  5464. if (typeof event.type === "undefined") {
  5465. throw new Error("Event object missing 'type' property.");
  5466. }
  5467. if (this._listeners[event.type]) {
  5468. //create a copy of the array and use that so listeners can't chane
  5469. var listeners = this._listeners[event.type].concat();
  5470. for (var i=0, len=listeners.length; i < len; i++) {
  5471. listeners[i].call(this, event);
  5472. }
  5473. }
  5474. },
  5475. /**
  5476. * Removes a listener for a given event type.
  5477. * @param {String} type The type of event to remove a listener from.
  5478. * @param {Function} listener The function to remove from the event.
  5479. * @return {void}
  5480. * @method removeListener
  5481. */
  5482. removeListener: function(type, listener) {
  5483. if (this._listeners[type]) {
  5484. var listeners = this._listeners[type];
  5485. for (var i=0, len=listeners.length; i < len; i++) {
  5486. if (listeners[i] === listener) {
  5487. listeners.splice(i, 1);
  5488. break;
  5489. }
  5490. }
  5491. }
  5492. }
  5493. };
  5494. },{}],24:[function(require,module,exports){
  5495. "use strict";
  5496. module.exports = StringReader;
  5497. /**
  5498. * Convenient way to read through strings.
  5499. * @namespace parserlib.util
  5500. * @class StringReader
  5501. * @constructor
  5502. * @param {String} text The text to read.
  5503. */
  5504. function StringReader(text) {
  5505. /**
  5506. * The input text with line endings normalized.
  5507. * @property _input
  5508. * @type String
  5509. * @private
  5510. */
  5511. this._input = text.replace(/(\r\n?|\n)/g, "\n");
  5512. /**
  5513. * The row for the character to be read next.
  5514. * @property _line
  5515. * @type int
  5516. * @private
  5517. */
  5518. this._line = 1;
  5519. /**
  5520. * The column for the character to be read next.
  5521. * @property _col
  5522. * @type int
  5523. * @private
  5524. */
  5525. this._col = 1;
  5526. /**
  5527. * The index of the character in the input to be read next.
  5528. * @property _cursor
  5529. * @type int
  5530. * @private
  5531. */
  5532. this._cursor = 0;
  5533. }
  5534. StringReader.prototype = {
  5535. // restore constructor
  5536. constructor: StringReader,
  5537. //-------------------------------------------------------------------------
  5538. // Position info
  5539. //-------------------------------------------------------------------------
  5540. /**
  5541. * Returns the column of the character to be read next.
  5542. * @return {int} The column of the character to be read next.
  5543. * @method getCol
  5544. */
  5545. getCol: function() {
  5546. return this._col;
  5547. },
  5548. /**
  5549. * Returns the row of the character to be read next.
  5550. * @return {int} The row of the character to be read next.
  5551. * @method getLine
  5552. */
  5553. getLine: function() {
  5554. return this._line;
  5555. },
  5556. /**
  5557. * Determines if you're at the end of the input.
  5558. * @return {Boolean} True if there's no more input, false otherwise.
  5559. * @method eof
  5560. */
  5561. eof: function() {
  5562. return this._cursor === this._input.length;
  5563. },
  5564. //-------------------------------------------------------------------------
  5565. // Basic reading
  5566. //-------------------------------------------------------------------------
  5567. /**
  5568. * Reads the next character without advancing the cursor.
  5569. * @param {int} count How many characters to look ahead (default is 1).
  5570. * @return {String} The next character or null if there is no next character.
  5571. * @method peek
  5572. */
  5573. peek: function(count) {
  5574. var c = null;
  5575. count = typeof count === "undefined" ? 1 : count;
  5576. // if we're not at the end of the input...
  5577. if (this._cursor < this._input.length) {
  5578. // get character and increment cursor and column
  5579. c = this._input.charAt(this._cursor + count - 1);
  5580. }
  5581. return c;
  5582. },
  5583. /**
  5584. * Reads the next character from the input and adjusts the row and column
  5585. * accordingly.
  5586. * @return {String} The next character or null if there is no next character.
  5587. * @method read
  5588. */
  5589. read: function() {
  5590. var c = null;
  5591. // if we're not at the end of the input...
  5592. if (this._cursor < this._input.length) {
  5593. // if the last character was a newline, increment row count
  5594. // and reset column count
  5595. if (this._input.charAt(this._cursor) === "\n") {
  5596. this._line++;
  5597. this._col=1;
  5598. } else {
  5599. this._col++;
  5600. }
  5601. // get character and increment cursor and column
  5602. c = this._input.charAt(this._cursor++);
  5603. }
  5604. return c;
  5605. },
  5606. //-------------------------------------------------------------------------
  5607. // Misc
  5608. //-------------------------------------------------------------------------
  5609. /**
  5610. * Saves the current location so it can be returned to later.
  5611. * @method mark
  5612. * @return {void}
  5613. */
  5614. mark: function() {
  5615. this._bookmark = {
  5616. cursor: this._cursor,
  5617. line: this._line,
  5618. col: this._col
  5619. };
  5620. },
  5621. reset: function() {
  5622. if (this._bookmark) {
  5623. this._cursor = this._bookmark.cursor;
  5624. this._line = this._bookmark.line;
  5625. this._col = this._bookmark.col;
  5626. delete this._bookmark;
  5627. }
  5628. },
  5629. //-------------------------------------------------------------------------
  5630. // Advanced reading
  5631. //-------------------------------------------------------------------------
  5632. /**
  5633. * Reads up to and including the given string. Throws an error if that
  5634. * string is not found.
  5635. * @param {String} pattern The string to read.
  5636. * @return {String} The string when it is found.
  5637. * @throws Error when the string pattern is not found.
  5638. * @method readTo
  5639. */
  5640. readTo: function(pattern) {
  5641. var buffer = "",
  5642. c;
  5643. /*
  5644. * First, buffer must be the same length as the pattern.
  5645. * Then, buffer must end with the pattern or else reach the
  5646. * end of the input.
  5647. */
  5648. while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) !== buffer.length - pattern.length) {
  5649. c = this.read();
  5650. if (c) {
  5651. buffer += c;
  5652. } else {
  5653. throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + ".");
  5654. }
  5655. }
  5656. return buffer;
  5657. },
  5658. /**
  5659. * Reads characters while each character causes the given
  5660. * filter function to return true. The function is passed
  5661. * in each character and either returns true to continue
  5662. * reading or false to stop.
  5663. * @param {Function} filter The function to read on each character.
  5664. * @return {String} The string made up of all characters that passed the
  5665. * filter check.
  5666. * @method readWhile
  5667. */
  5668. readWhile: function(filter) {
  5669. var buffer = "",
  5670. c = this.peek();
  5671. while (c !== null && filter(c)) {
  5672. buffer += this.read();
  5673. c = this.peek();
  5674. }
  5675. return buffer;
  5676. },
  5677. /**
  5678. * Reads characters that match either text or a regular expression and
  5679. * returns those characters. If a match is found, the row and column
  5680. * are adjusted; if no match is found, the reader's state is unchanged.
  5681. * reading or false to stop.
  5682. * @param {String|RegExp} matcher If a string, then the literal string
  5683. * value is searched for. If a regular expression, then any string
  5684. * matching the pattern is search for.
  5685. * @return {String} The string made up of all characters that matched or
  5686. * null if there was no match.
  5687. * @method readMatch
  5688. */
  5689. readMatch: function(matcher) {
  5690. var source = this._input.substring(this._cursor),
  5691. value = null;
  5692. // if it's a string, just do a straight match
  5693. if (typeof matcher === "string") {
  5694. if (source.slice(0, matcher.length) === matcher) {
  5695. value = this.readCount(matcher.length);
  5696. }
  5697. } else if (matcher instanceof RegExp) {
  5698. if (matcher.test(source)) {
  5699. value = this.readCount(RegExp.lastMatch.length);
  5700. }
  5701. }
  5702. return value;
  5703. },
  5704. /**
  5705. * Reads a given number of characters. If the end of the input is reached,
  5706. * it reads only the remaining characters and does not throw an error.
  5707. * @param {int} count The number of characters to read.
  5708. * @return {String} The string made up the read characters.
  5709. * @method readCount
  5710. */
  5711. readCount: function(count) {
  5712. var buffer = "";
  5713. while (count--) {
  5714. buffer += this.read();
  5715. }
  5716. return buffer;
  5717. }
  5718. };
  5719. },{}],25:[function(require,module,exports){
  5720. "use strict";
  5721. module.exports = SyntaxError;
  5722. /**
  5723. * Type to use when a syntax error occurs.
  5724. * @class SyntaxError
  5725. * @namespace parserlib.util
  5726. * @constructor
  5727. * @param {String} message The error message.
  5728. * @param {int} line The line at which the error occurred.
  5729. * @param {int} col The column at which the error occurred.
  5730. */
  5731. function SyntaxError(message, line, col) {
  5732. Error.call(this);
  5733. this.name = this.constructor.name;
  5734. /**
  5735. * The column at which the error occurred.
  5736. * @type int
  5737. * @property col
  5738. */
  5739. this.col = col;
  5740. /**
  5741. * The line at which the error occurred.
  5742. * @type int
  5743. * @property line
  5744. */
  5745. this.line = line;
  5746. /**
  5747. * The text representation of the unit.
  5748. * @type String
  5749. * @property text
  5750. */
  5751. this.message = message;
  5752. }
  5753. //inherit from Error
  5754. SyntaxError.prototype = Object.create(Error.prototype); // jshint ignore:line
  5755. SyntaxError.prototype.constructor = SyntaxError; // jshint ignore:line
  5756. },{}],26:[function(require,module,exports){
  5757. "use strict";
  5758. module.exports = SyntaxUnit;
  5759. /**
  5760. * Base type to represent a single syntactic unit.
  5761. * @class SyntaxUnit
  5762. * @namespace parserlib.util
  5763. * @constructor
  5764. * @param {String} text The text of the unit.
  5765. * @param {int} line The line of text on which the unit resides.
  5766. * @param {int} col The column of text on which the unit resides.
  5767. */
  5768. function SyntaxUnit(text, line, col, type) {
  5769. /**
  5770. * The column of text on which the unit resides.
  5771. * @type int
  5772. * @property col
  5773. */
  5774. this.col = col;
  5775. /**
  5776. * The line of text on which the unit resides.
  5777. * @type int
  5778. * @property line
  5779. */
  5780. this.line = line;
  5781. /**
  5782. * The text representation of the unit.
  5783. * @type String
  5784. * @property text
  5785. */
  5786. this.text = text;
  5787. /**
  5788. * The type of syntax unit.
  5789. * @type int
  5790. * @property type
  5791. */
  5792. this.type = type;
  5793. }
  5794. /**
  5795. * Create a new syntax unit based solely on the given token.
  5796. * Convenience method for creating a new syntax unit when
  5797. * it represents a single token instead of multiple.
  5798. * @param {Object} token The token object to represent.
  5799. * @return {parserlib.util.SyntaxUnit} The object representing the token.
  5800. * @static
  5801. * @method fromToken
  5802. */
  5803. SyntaxUnit.fromToken = function(token) {
  5804. return new SyntaxUnit(token.value, token.startLine, token.startCol);
  5805. };
  5806. SyntaxUnit.prototype = {
  5807. //restore constructor
  5808. constructor: SyntaxUnit,
  5809. /**
  5810. * Returns the text representation of the unit.
  5811. * @return {String} The text representation of the unit.
  5812. * @method valueOf
  5813. */
  5814. valueOf: function() {
  5815. return this.toString();
  5816. },
  5817. /**
  5818. * Returns the text representation of the unit.
  5819. * @return {String} The text representation of the unit.
  5820. * @method toString
  5821. */
  5822. toString: function() {
  5823. return this.text;
  5824. }
  5825. };
  5826. },{}],27:[function(require,module,exports){
  5827. "use strict";
  5828. module.exports = TokenStreamBase;
  5829. var StringReader = require("./StringReader");
  5830. var SyntaxError = require("./SyntaxError");
  5831. /**
  5832. * Generic TokenStream providing base functionality.
  5833. * @class TokenStreamBase
  5834. * @namespace parserlib.util
  5835. * @constructor
  5836. * @param {String|StringReader} input The text to tokenize or a reader from
  5837. * which to read the input.
  5838. */
  5839. function TokenStreamBase(input, tokenData) {
  5840. /**
  5841. * The string reader for easy access to the text.
  5842. * @type StringReader
  5843. * @property _reader
  5844. * @private
  5845. */
  5846. this._reader = new StringReader(input ? input.toString() : "");
  5847. /**
  5848. * Token object for the last consumed token.
  5849. * @type Token
  5850. * @property _token
  5851. * @private
  5852. */
  5853. this._token = null;
  5854. /**
  5855. * The array of token information.
  5856. * @type Array
  5857. * @property _tokenData
  5858. * @private
  5859. */
  5860. this._tokenData = tokenData;
  5861. /**
  5862. * Lookahead token buffer.
  5863. * @type Array
  5864. * @property _lt
  5865. * @private
  5866. */
  5867. this._lt = [];
  5868. /**
  5869. * Lookahead token buffer index.
  5870. * @type int
  5871. * @property _ltIndex
  5872. * @private
  5873. */
  5874. this._ltIndex = 0;
  5875. this._ltIndexCache = [];
  5876. }
  5877. /**
  5878. * Accepts an array of token information and outputs
  5879. * an array of token data containing key-value mappings
  5880. * and matching functions that the TokenStream needs.
  5881. * @param {Array} tokens An array of token descriptors.
  5882. * @return {Array} An array of processed token data.
  5883. * @method createTokenData
  5884. * @static
  5885. */
  5886. TokenStreamBase.createTokenData = function(tokens) {
  5887. var nameMap = [],
  5888. typeMap = Object.create(null),
  5889. tokenData = tokens.concat([]),
  5890. i = 0,
  5891. len = tokenData.length+1;
  5892. tokenData.UNKNOWN = -1;
  5893. tokenData.unshift({ name:"EOF" });
  5894. for (; i < len; i++) {
  5895. nameMap.push(tokenData[i].name);
  5896. tokenData[tokenData[i].name] = i;
  5897. if (tokenData[i].text) {
  5898. typeMap[tokenData[i].text] = i;
  5899. }
  5900. }
  5901. tokenData.name = function(tt) {
  5902. return nameMap[tt];
  5903. };
  5904. tokenData.type = function(c) {
  5905. return typeMap[c];
  5906. };
  5907. return tokenData;
  5908. };
  5909. TokenStreamBase.prototype = {
  5910. //restore constructor
  5911. constructor: TokenStreamBase,
  5912. //-------------------------------------------------------------------------
  5913. // Matching methods
  5914. //-------------------------------------------------------------------------
  5915. /**
  5916. * Determines if the next token matches the given token type.
  5917. * If so, that token is consumed; if not, the token is placed
  5918. * back onto the token stream. You can pass in any number of
  5919. * token types and this will return true if any of the token
  5920. * types is found.
  5921. * @param {int|int[]} tokenTypes Either a single token type or an array of
  5922. * token types that the next token might be. If an array is passed,
  5923. * it's assumed that the token can be any of these.
  5924. * @param {variant} channel (Optional) The channel to read from. If not
  5925. * provided, reads from the default (unnamed) channel.
  5926. * @return {Boolean} True if the token type matches, false if not.
  5927. * @method match
  5928. */
  5929. match: function(tokenTypes, channel) {
  5930. //always convert to an array, makes things easier
  5931. if (!(tokenTypes instanceof Array)) {
  5932. tokenTypes = [tokenTypes];
  5933. }
  5934. var tt = this.get(channel),
  5935. i = 0,
  5936. len = tokenTypes.length;
  5937. while (i < len) {
  5938. if (tt === tokenTypes[i++]) {
  5939. return true;
  5940. }
  5941. }
  5942. //no match found, put the token back
  5943. this.unget();
  5944. return false;
  5945. },
  5946. /**
  5947. * Determines if the next token matches the given token type.
  5948. * If so, that token is consumed; if not, an error is thrown.
  5949. * @param {int|int[]} tokenTypes Either a single token type or an array of
  5950. * token types that the next token should be. If an array is passed,
  5951. * it's assumed that the token must be one of these.
  5952. * @return {void}
  5953. * @method mustMatch
  5954. */
  5955. mustMatch: function(tokenTypes) {
  5956. var token;
  5957. //always convert to an array, makes things easier
  5958. if (!(tokenTypes instanceof Array)) {
  5959. tokenTypes = [tokenTypes];
  5960. }
  5961. if (!this.match.apply(this, arguments)) {
  5962. token = this.LT(1);
  5963. throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name +
  5964. " at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
  5965. }
  5966. },
  5967. //-------------------------------------------------------------------------
  5968. // Consuming methods
  5969. //-------------------------------------------------------------------------
  5970. /**
  5971. * Keeps reading from the token stream until either one of the specified
  5972. * token types is found or until the end of the input is reached.
  5973. * @param {int|int[]} tokenTypes Either a single token type or an array of
  5974. * token types that the next token should be. If an array is passed,
  5975. * it's assumed that the token must be one of these.
  5976. * @param {variant} channel (Optional) The channel to read from. If not
  5977. * provided, reads from the default (unnamed) channel.
  5978. * @return {void}
  5979. * @method advance
  5980. */
  5981. advance: function(tokenTypes, channel) {
  5982. while (this.LA(0) !== 0 && !this.match(tokenTypes, channel)) {
  5983. this.get();
  5984. }
  5985. return this.LA(0);
  5986. },
  5987. /**
  5988. * Consumes the next token from the token stream.
  5989. * @return {int} The token type of the token that was just consumed.
  5990. * @method get
  5991. */
  5992. get: function(channel) {
  5993. var tokenInfo = this._tokenData,
  5994. i =0,
  5995. token,
  5996. info;
  5997. //check the lookahead buffer first
  5998. if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length) {
  5999. i++;
  6000. this._token = this._lt[this._ltIndex++];
  6001. info = tokenInfo[this._token.type];
  6002. //obey channels logic
  6003. while ((info.channel !== undefined && channel !== info.channel) &&
  6004. this._ltIndex < this._lt.length) {
  6005. this._token = this._lt[this._ltIndex++];
  6006. info = tokenInfo[this._token.type];
  6007. i++;
  6008. }
  6009. //here be dragons
  6010. if ((info.channel === undefined || channel === info.channel) &&
  6011. this._ltIndex <= this._lt.length) {
  6012. this._ltIndexCache.push(i);
  6013. return this._token.type;
  6014. }
  6015. }
  6016. //call token retriever method
  6017. token = this._getToken();
  6018. //if it should be hidden, don't save a token
  6019. if (token.type > -1 && !tokenInfo[token.type].hide) {
  6020. //apply token channel
  6021. token.channel = tokenInfo[token.type].channel;
  6022. //save for later
  6023. this._token = token;
  6024. this._lt.push(token);
  6025. //save space that will be moved (must be done before array is truncated)
  6026. this._ltIndexCache.push(this._lt.length - this._ltIndex + i);
  6027. //keep the buffer under 5 items
  6028. if (this._lt.length > 5) {
  6029. this._lt.shift();
  6030. }
  6031. //also keep the shift buffer under 5 items
  6032. if (this._ltIndexCache.length > 5) {
  6033. this._ltIndexCache.shift();
  6034. }
  6035. //update lookahead index
  6036. this._ltIndex = this._lt.length;
  6037. }
  6038. /*
  6039. * Skip to the next token if:
  6040. * 1. The token type is marked as hidden.
  6041. * 2. The token type has a channel specified and it isn't the current channel.
  6042. */
  6043. info = tokenInfo[token.type];
  6044. if (info &&
  6045. (info.hide ||
  6046. (info.channel !== undefined && channel !== info.channel))) {
  6047. return this.get(channel);
  6048. } else {
  6049. //return just the type
  6050. return token.type;
  6051. }
  6052. },
  6053. /**
  6054. * Looks ahead a certain number of tokens and returns the token type at
  6055. * that position. This will throw an error if you lookahead past the
  6056. * end of input, past the size of the lookahead buffer, or back past
  6057. * the first token in the lookahead buffer.
  6058. * @param {int} The index of the token type to retrieve. 0 for the
  6059. * current token, 1 for the next, -1 for the previous, etc.
  6060. * @return {int} The token type of the token in the given position.
  6061. * @method LA
  6062. */
  6063. LA: function(index) {
  6064. var total = index,
  6065. tt;
  6066. if (index > 0) {
  6067. //TODO: Store 5 somewhere
  6068. if (index > 5) {
  6069. throw new Error("Too much lookahead.");
  6070. }
  6071. //get all those tokens
  6072. while (total) {
  6073. tt = this.get();
  6074. total--;
  6075. }
  6076. //unget all those tokens
  6077. while (total < index) {
  6078. this.unget();
  6079. total++;
  6080. }
  6081. } else if (index < 0) {
  6082. if (this._lt[this._ltIndex+index]) {
  6083. tt = this._lt[this._ltIndex+index].type;
  6084. } else {
  6085. throw new Error("Too much lookbehind.");
  6086. }
  6087. } else {
  6088. tt = this._token.type;
  6089. }
  6090. return tt;
  6091. },
  6092. /**
  6093. * Looks ahead a certain number of tokens and returns the token at
  6094. * that position. This will throw an error if you lookahead past the
  6095. * end of input, past the size of the lookahead buffer, or back past
  6096. * the first token in the lookahead buffer.
  6097. * @param {int} The index of the token type to retrieve. 0 for the
  6098. * current token, 1 for the next, -1 for the previous, etc.
  6099. * @return {Object} The token of the token in the given position.
  6100. * @method LA
  6101. */
  6102. LT: function(index) {
  6103. //lookahead first to prime the token buffer
  6104. this.LA(index);
  6105. //now find the token, subtract one because _ltIndex is already at the next index
  6106. return this._lt[this._ltIndex+index-1];
  6107. },
  6108. /**
  6109. * Returns the token type for the next token in the stream without
  6110. * consuming it.
  6111. * @return {int} The token type of the next token in the stream.
  6112. * @method peek
  6113. */
  6114. peek: function() {
  6115. return this.LA(1);
  6116. },
  6117. /**
  6118. * Returns the actual token object for the last consumed token.
  6119. * @return {Token} The token object for the last consumed token.
  6120. * @method token
  6121. */
  6122. token: function() {
  6123. return this._token;
  6124. },
  6125. /**
  6126. * Returns the name of the token for the given token type.
  6127. * @param {int} tokenType The type of token to get the name of.
  6128. * @return {String} The name of the token or "UNKNOWN_TOKEN" for any
  6129. * invalid token type.
  6130. * @method tokenName
  6131. */
  6132. tokenName: function(tokenType) {
  6133. if (tokenType < 0 || tokenType > this._tokenData.length) {
  6134. return "UNKNOWN_TOKEN";
  6135. } else {
  6136. return this._tokenData[tokenType].name;
  6137. }
  6138. },
  6139. /**
  6140. * Returns the token type value for the given token name.
  6141. * @param {String} tokenName The name of the token whose value should be returned.
  6142. * @return {int} The token type value for the given token name or -1
  6143. * for an unknown token.
  6144. * @method tokenName
  6145. */
  6146. tokenType: function(tokenName) {
  6147. return this._tokenData[tokenName] || -1;
  6148. },
  6149. /**
  6150. * Returns the last consumed token to the token stream.
  6151. * @method unget
  6152. */
  6153. unget: function() {
  6154. //if (this._ltIndex > -1) {
  6155. if (this._ltIndexCache.length) {
  6156. this._ltIndex -= this._ltIndexCache.pop();//--;
  6157. this._token = this._lt[this._ltIndex - 1];
  6158. } else {
  6159. throw new Error("Too much lookahead.");
  6160. }
  6161. }
  6162. };
  6163. },{"./StringReader":24,"./SyntaxError":25}],28:[function(require,module,exports){
  6164. "use strict";
  6165. module.exports = {
  6166. StringReader : require("./StringReader"),
  6167. SyntaxError : require("./SyntaxError"),
  6168. SyntaxUnit : require("./SyntaxUnit"),
  6169. EventTarget : require("./EventTarget"),
  6170. TokenStreamBase : require("./TokenStreamBase")
  6171. };
  6172. },{"./EventTarget":23,"./StringReader":24,"./SyntaxError":25,"./SyntaxUnit":26,"./TokenStreamBase":27}],"parserlib":[function(require,module,exports){
  6173. "use strict";
  6174. module.exports = {
  6175. css : require("./css"),
  6176. util : require("./util")
  6177. };
  6178. },{"./css":22,"./util":28}]},{},[]);
  6179. return require('parserlib');
  6180. })();
  6181. var clone = (function() {
  6182. 'use strict';
  6183. var nativeMap;
  6184. try {
  6185. nativeMap = Map;
  6186. } catch(_) {
  6187. // maybe a reference error because no `Map`. Give it a dummy value that no
  6188. // value will ever be an instanceof.
  6189. nativeMap = function() {};
  6190. }
  6191. var nativeSet;
  6192. try {
  6193. nativeSet = Set;
  6194. } catch(_) {
  6195. nativeSet = function() {};
  6196. }
  6197. var nativePromise;
  6198. try {
  6199. nativePromise = Promise;
  6200. } catch(_) {
  6201. nativePromise = function() {};
  6202. }
  6203. /**
  6204. * Clones (copies) an Object using deep copying.
  6205. *
  6206. * This function supports circular references by default, but if you are certain
  6207. * there are no circular references in your object, you can save some CPU time
  6208. * by calling clone(obj, false).
  6209. *
  6210. * Caution: if `circular` is false and `parent` contains circular references,
  6211. * your program may enter an infinite loop and crash.
  6212. *
  6213. * @param `parent` - the object to be cloned
  6214. * @param `circular` - set to true if the object to be cloned may contain
  6215. * circular references. (optional - true by default)
  6216. * @param `depth` - set to a number if the object is only to be cloned to
  6217. * a particular depth. (optional - defaults to Infinity)
  6218. * @param `prototype` - sets the prototype to be used when cloning an object.
  6219. * (optional - defaults to parent prototype).
  6220. * @param `includeNonEnumerable` - set to true if the non-enumerable properties
  6221. * should be cloned as well. Non-enumerable properties on the prototype
  6222. * chain will be ignored. (optional - false by default)
  6223. */
  6224. function clone(parent, circular, depth, prototype, includeNonEnumerable) {
  6225. if (typeof circular === 'object') {
  6226. depth = circular.depth;
  6227. prototype = circular.prototype;
  6228. includeNonEnumerable = circular.includeNonEnumerable;
  6229. circular = circular.circular;
  6230. }
  6231. // maintain two arrays for circular references, where corresponding parents
  6232. // and children have the same index
  6233. var allParents = [];
  6234. var allChildren = [];
  6235. var useBuffer = typeof Buffer != 'undefined';
  6236. if (typeof circular == 'undefined')
  6237. circular = true;
  6238. if (typeof depth == 'undefined')
  6239. depth = Infinity;
  6240. // recurse this function so we don't reset allParents and allChildren
  6241. function _clone(parent, depth) {
  6242. // cloning null always returns null
  6243. if (parent === null)
  6244. return null;
  6245. if (depth === 0)
  6246. return parent;
  6247. var child;
  6248. var proto;
  6249. if (typeof parent != 'object') {
  6250. return parent;
  6251. }
  6252. if (parent instanceof nativeMap) {
  6253. child = new nativeMap();
  6254. } else if (parent instanceof nativeSet) {
  6255. child = new nativeSet();
  6256. } else if (parent instanceof nativePromise) {
  6257. child = new nativePromise(function (resolve, reject) {
  6258. parent.then(function(value) {
  6259. resolve(_clone(value, depth - 1));
  6260. }, function(err) {
  6261. reject(_clone(err, depth - 1));
  6262. });
  6263. });
  6264. } else if (clone.__isArray(parent)) {
  6265. child = [];
  6266. } else if (clone.__isRegExp(parent)) {
  6267. child = new RegExp(parent.source, __getRegExpFlags(parent));
  6268. if (parent.lastIndex) child.lastIndex = parent.lastIndex;
  6269. } else if (clone.__isDate(parent)) {
  6270. child = new Date(parent.getTime());
  6271. } else if (useBuffer && Buffer.isBuffer(parent)) {
  6272. child = new Buffer(parent.length);
  6273. parent.copy(child);
  6274. return child;
  6275. } else if (parent instanceof Error) {
  6276. child = Object.create(parent);
  6277. } else {
  6278. if (typeof prototype == 'undefined') {
  6279. proto = Object.getPrototypeOf(parent);
  6280. child = Object.create(proto);
  6281. }
  6282. else {
  6283. child = Object.create(prototype);
  6284. proto = prototype;
  6285. }
  6286. }
  6287. if (circular) {
  6288. var index = allParents.indexOf(parent);
  6289. if (index != -1) {
  6290. return allChildren[index];
  6291. }
  6292. allParents.push(parent);
  6293. allChildren.push(child);
  6294. }
  6295. if (parent instanceof nativeMap) {
  6296. var keyIterator = parent.keys();
  6297. while(true) {
  6298. var next = keyIterator.next();
  6299. if (next.done) {
  6300. break;
  6301. }
  6302. var keyChild = _clone(next.value, depth - 1);
  6303. var valueChild = _clone(parent.get(next.value), depth - 1);
  6304. child.set(keyChild, valueChild);
  6305. }
  6306. }
  6307. if (parent instanceof nativeSet) {
  6308. var iterator = parent.keys();
  6309. while(true) {
  6310. var next = iterator.next();
  6311. if (next.done) {
  6312. break;
  6313. }
  6314. var entryChild = _clone(next.value, depth - 1);
  6315. child.add(entryChild);
  6316. }
  6317. }
  6318. for (var i in parent) {
  6319. var attrs;
  6320. if (proto) {
  6321. attrs = Object.getOwnPropertyDescriptor(proto, i);
  6322. }
  6323. if (attrs && attrs.set == null) {
  6324. continue;
  6325. }
  6326. child[i] = _clone(parent[i], depth - 1);
  6327. }
  6328. if (Object.getOwnPropertySymbols) {
  6329. var symbols = Object.getOwnPropertySymbols(parent);
  6330. for (var i = 0; i < symbols.length; i++) {
  6331. // Don't need to worry about cloning a symbol because it is a primitive,
  6332. // like a number or string.
  6333. var symbol = symbols[i];
  6334. var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
  6335. if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
  6336. continue;
  6337. }
  6338. child[symbol] = _clone(parent[symbol], depth - 1);
  6339. if (!descriptor.enumerable) {
  6340. Object.defineProperty(child, symbol, {
  6341. enumerable: false
  6342. });
  6343. }
  6344. }
  6345. }
  6346. if (includeNonEnumerable) {
  6347. var allPropertyNames = Object.getOwnPropertyNames(parent);
  6348. for (var i = 0; i < allPropertyNames.length; i++) {
  6349. var propertyName = allPropertyNames[i];
  6350. var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
  6351. if (descriptor && descriptor.enumerable) {
  6352. continue;
  6353. }
  6354. child[propertyName] = _clone(parent[propertyName], depth - 1);
  6355. Object.defineProperty(child, propertyName, {
  6356. enumerable: false
  6357. });
  6358. }
  6359. }
  6360. return child;
  6361. }
  6362. return _clone(parent, depth);
  6363. }
  6364. /**
  6365. * Simple flat clone using prototype, accepts only objects, usefull for property
  6366. * override on FLAT configuration object (no nested props).
  6367. *
  6368. * USE WITH CAUTION! This may not behave as you wish if you do not know how this
  6369. * works.
  6370. */
  6371. clone.clonePrototype = function clonePrototype(parent) {
  6372. if (parent === null)
  6373. return null;
  6374. var c = function () {};
  6375. c.prototype = parent;
  6376. return new c();
  6377. };
  6378. // private utility functions
  6379. function __objToStr(o) {
  6380. return Object.prototype.toString.call(o);
  6381. }
  6382. clone.__objToStr = __objToStr;
  6383. function __isDate(o) {
  6384. return typeof o === 'object' && __objToStr(o) === '[object Date]';
  6385. }
  6386. clone.__isDate = __isDate;
  6387. function __isArray(o) {
  6388. return typeof o === 'object' && __objToStr(o) === '[object Array]';
  6389. }
  6390. clone.__isArray = __isArray;
  6391. function __isRegExp(o) {
  6392. return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
  6393. }
  6394. clone.__isRegExp = __isRegExp;
  6395. function __getRegExpFlags(re) {
  6396. var flags = '';
  6397. if (re.global) flags += 'g';
  6398. if (re.ignoreCase) flags += 'i';
  6399. if (re.multiline) flags += 'm';
  6400. return flags;
  6401. }
  6402. clone.__getRegExpFlags = __getRegExpFlags;
  6403. return clone;
  6404. })();
  6405. if (typeof module === 'object' && module.exports) {
  6406. module.exports = clone;
  6407. }
  6408. /**
  6409. * Main CSSLint object.
  6410. * @class CSSLint
  6411. * @static
  6412. * @extends parserlib.util.EventTarget
  6413. */
  6414. /* global parserlib, clone, Reporter */
  6415. /* exported CSSLint */
  6416. var CSSLint = (function() {
  6417. "use strict";
  6418. var rules = [],
  6419. formatters = [],
  6420. embeddedRuleset = /\/\*\s*csslint([^\*]*)\*\//,
  6421. api = new parserlib.util.EventTarget();
  6422. api.version = "1.0.4";
  6423. //-------------------------------------------------------------------------
  6424. // Rule Management
  6425. //-------------------------------------------------------------------------
  6426. /**
  6427. * Adds a new rule to the engine.
  6428. * @param {Object} rule The rule to add.
  6429. * @method addRule
  6430. */
  6431. api.addRule = function(rule) {
  6432. rules.push(rule);
  6433. rules[rule.id] = rule;
  6434. };
  6435. /**
  6436. * Clears all rule from the engine.
  6437. * @method clearRules
  6438. */
  6439. api.clearRules = function() {
  6440. rules = [];
  6441. };
  6442. /**
  6443. * Returns the rule objects.
  6444. * @return An array of rule objects.
  6445. * @method getRules
  6446. */
  6447. api.getRules = function() {
  6448. return [].concat(rules).sort(function(a, b) {
  6449. return a.id > b.id ? 1 : 0;
  6450. });
  6451. };
  6452. /**
  6453. * Returns a ruleset configuration object with all current rules.
  6454. * @return A ruleset object.
  6455. * @method getRuleset
  6456. */
  6457. api.getRuleset = function() {
  6458. var ruleset = {},
  6459. i = 0,
  6460. len = rules.length;
  6461. while (i < len) {
  6462. ruleset[rules[i++].id] = 1; // by default, everything is a warning
  6463. }
  6464. return ruleset;
  6465. };
  6466. /**
  6467. * Returns a ruleset object based on embedded rules.
  6468. * @param {String} text A string of css containing embedded rules.
  6469. * @param {Object} ruleset A ruleset object to modify.
  6470. * @return {Object} A ruleset object.
  6471. * @method getEmbeddedRuleset
  6472. */
  6473. function applyEmbeddedRuleset(text, ruleset) {
  6474. var valueMap,
  6475. embedded = text && text.match(embeddedRuleset),
  6476. rules = embedded && embedded[1];
  6477. if (rules) {
  6478. valueMap = {
  6479. "true": 2, // true is error
  6480. "": 1, // blank is warning
  6481. "false": 0, // false is ignore
  6482. "2": 2, // explicit error
  6483. "1": 1, // explicit warning
  6484. "0": 0 // explicit ignore
  6485. };
  6486. rules.toLowerCase().split(",").forEach(function(rule) {
  6487. var pair = rule.split(":"),
  6488. property = pair[0] || "",
  6489. value = pair[1] || "";
  6490. ruleset[property.trim()] = valueMap[value.trim()];
  6491. });
  6492. }
  6493. return ruleset;
  6494. }
  6495. //-------------------------------------------------------------------------
  6496. // Formatters
  6497. //-------------------------------------------------------------------------
  6498. /**
  6499. * Adds a new formatter to the engine.
  6500. * @param {Object} formatter The formatter to add.
  6501. * @method addFormatter
  6502. */
  6503. api.addFormatter = function(formatter) {
  6504. // formatters.push(formatter);
  6505. formatters[formatter.id] = formatter;
  6506. };
  6507. /**
  6508. * Retrieves a formatter for use.
  6509. * @param {String} formatId The name of the format to retrieve.
  6510. * @return {Object} The formatter or undefined.
  6511. * @method getFormatter
  6512. */
  6513. api.getFormatter = function(formatId) {
  6514. return formatters[formatId];
  6515. };
  6516. /**
  6517. * Formats the results in a particular format for a single file.
  6518. * @param {Object} result The results returned from CSSLint.verify().
  6519. * @param {String} filename The filename for which the results apply.
  6520. * @param {String} formatId The name of the formatter to use.
  6521. * @param {Object} options (Optional) for special output handling.
  6522. * @return {String} A formatted string for the results.
  6523. * @method format
  6524. */
  6525. api.format = function(results, filename, formatId, options) {
  6526. var formatter = this.getFormatter(formatId),
  6527. result = null;
  6528. if (formatter) {
  6529. result = formatter.startFormat();
  6530. result += formatter.formatResults(results, filename, options || {});
  6531. result += formatter.endFormat();
  6532. }
  6533. return result;
  6534. };
  6535. /**
  6536. * Indicates if the given format is supported.
  6537. * @param {String} formatId The ID of the format to check.
  6538. * @return {Boolean} True if the format exists, false if not.
  6539. * @method hasFormat
  6540. */
  6541. api.hasFormat = function(formatId) {
  6542. return formatters.hasOwnProperty(formatId);
  6543. };
  6544. //-------------------------------------------------------------------------
  6545. // Verification
  6546. //-------------------------------------------------------------------------
  6547. /**
  6548. * Starts the verification process for the given CSS text.
  6549. * @param {String} text The CSS text to verify.
  6550. * @param {Object} ruleset (Optional) List of rules to apply. If null, then
  6551. * all rules are used. If a rule has a value of 1 then it's a warning,
  6552. * a value of 2 means it's an error.
  6553. * @return {Object} Results of the verification.
  6554. * @method verify
  6555. */
  6556. api.verify = function(text, ruleset) {
  6557. var i = 0,
  6558. reporter,
  6559. lines,
  6560. allow = {},
  6561. ignore = [],
  6562. report,
  6563. parser = new parserlib.css.Parser({
  6564. starHack: true,
  6565. ieFilters: true,
  6566. underscoreHack: true,
  6567. strict: false
  6568. });
  6569. // normalize line endings
  6570. lines = text.replace(/\n\r?/g, "$split$").split("$split$");
  6571. // find 'allow' comments
  6572. CSSLint.Util.forEach(lines, function (line, lineno) {
  6573. var allowLine = line && line.match(/\/\*[ \t]*csslint[ \t]+allow:[ \t]*([^\*]*)\*\//i),
  6574. allowRules = allowLine && allowLine[1],
  6575. allowRuleset = {};
  6576. if (allowRules) {
  6577. allowRules.toLowerCase().split(",").forEach(function(allowRule) {
  6578. allowRuleset[allowRule.trim()] = true;
  6579. });
  6580. if (Object.keys(allowRuleset).length > 0) {
  6581. allow[lineno + 1] = allowRuleset;
  6582. }
  6583. }
  6584. });
  6585. var ignoreStart = null,
  6586. ignoreEnd = null;
  6587. CSSLint.Util.forEach(lines, function (line, lineno) {
  6588. // Keep oldest, "unclosest" ignore:start
  6589. if (ignoreStart === null && line.match(/\/\*[ \t]*csslint[ \t]+ignore:start[ \t]*\*\//i)) {
  6590. ignoreStart = lineno;
  6591. }
  6592. if (line.match(/\/\*[ \t]*csslint[ \t]+ignore:end[ \t]*\*\//i)) {
  6593. ignoreEnd = lineno;
  6594. }
  6595. if (ignoreStart !== null && ignoreEnd !== null) {
  6596. ignore.push([ignoreStart, ignoreEnd]);
  6597. ignoreStart = ignoreEnd = null;
  6598. }
  6599. });
  6600. // Close remaining ignore block, if any
  6601. if (ignoreStart !== null) {
  6602. ignore.push([ignoreStart, lines.length]);
  6603. }
  6604. if (!ruleset) {
  6605. ruleset = this.getRuleset();
  6606. }
  6607. if (embeddedRuleset.test(text)) {
  6608. // defensively copy so that caller's version does not get modified
  6609. ruleset = clone(ruleset);
  6610. ruleset = applyEmbeddedRuleset(text, ruleset);
  6611. }
  6612. reporter = new Reporter(lines, ruleset, allow, ignore);
  6613. ruleset.errors = 2; // always report parsing errors as errors
  6614. for (i in ruleset) {
  6615. if (ruleset.hasOwnProperty(i) && ruleset[i]) {
  6616. if (rules[i]) {
  6617. rules[i].init(parser, reporter);
  6618. }
  6619. }
  6620. }
  6621. // capture most horrible error type
  6622. try {
  6623. parser.parse(text);
  6624. } catch (ex) {
  6625. reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
  6626. }
  6627. report = {
  6628. messages : reporter.messages,
  6629. stats : reporter.stats,
  6630. ruleset : reporter.ruleset,
  6631. allow : reporter.allow,
  6632. ignore : reporter.ignore
  6633. };
  6634. // sort by line numbers, rollups at the bottom
  6635. report.messages.sort(function (a, b) {
  6636. if (a.rollup && !b.rollup) {
  6637. return 1;
  6638. } else if (!a.rollup && b.rollup) {
  6639. return -1;
  6640. } else {
  6641. return a.line - b.line;
  6642. }
  6643. });
  6644. return report;
  6645. };
  6646. //-------------------------------------------------------------------------
  6647. // Publish the API
  6648. //-------------------------------------------------------------------------
  6649. return api;
  6650. })();
  6651. /**
  6652. * An instance of Report is used to report results of the
  6653. * verification back to the main API.
  6654. * @class Reporter
  6655. * @constructor
  6656. * @param {String[]} lines The text lines of the source.
  6657. * @param {Object} ruleset The set of rules to work with, including if
  6658. * they are errors or warnings.
  6659. * @param {Object} explicitly allowed lines
  6660. * @param {[][]} ingore list of line ranges to be ignored
  6661. */
  6662. function Reporter(lines, ruleset, allow, ignore) {
  6663. "use strict";
  6664. /**
  6665. * List of messages being reported.
  6666. * @property messages
  6667. * @type String[]
  6668. */
  6669. this.messages = [];
  6670. /**
  6671. * List of statistics being reported.
  6672. * @property stats
  6673. * @type String[]
  6674. */
  6675. this.stats = [];
  6676. /**
  6677. * Lines of code being reported on. Used to provide contextual information
  6678. * for messages.
  6679. * @property lines
  6680. * @type String[]
  6681. */
  6682. this.lines = lines;
  6683. /**
  6684. * Information about the rules. Used to determine whether an issue is an
  6685. * error or warning.
  6686. * @property ruleset
  6687. * @type Object
  6688. */
  6689. this.ruleset = ruleset;
  6690. /**
  6691. * Lines with specific rule messages to leave out of the report.
  6692. * @property allow
  6693. * @type Object
  6694. */
  6695. this.allow = allow;
  6696. if (!this.allow) {
  6697. this.allow = {};
  6698. }
  6699. /**
  6700. * Linesets not to include in the report.
  6701. * @property ignore
  6702. * @type [][]
  6703. */
  6704. this.ignore = ignore;
  6705. if (!this.ignore) {
  6706. this.ignore = [];
  6707. }
  6708. }
  6709. Reporter.prototype = {
  6710. // restore constructor
  6711. constructor: Reporter,
  6712. /**
  6713. * Report an error.
  6714. * @param {String} message The message to store.
  6715. * @param {int} line The line number.
  6716. * @param {int} col The column number.
  6717. * @param {Object} rule The rule this message relates to.
  6718. * @method error
  6719. */
  6720. error: function(message, line, col, rule) {
  6721. "use strict";
  6722. this.messages.push({
  6723. type : "error",
  6724. line : line,
  6725. col : col,
  6726. message : message,
  6727. evidence: this.lines[line-1],
  6728. rule : rule || {}
  6729. });
  6730. },
  6731. /**
  6732. * Report an warning.
  6733. * @param {String} message The message to store.
  6734. * @param {int} line The line number.
  6735. * @param {int} col The column number.
  6736. * @param {Object} rule The rule this message relates to.
  6737. * @method warn
  6738. * @deprecated Use report instead.
  6739. */
  6740. warn: function(message, line, col, rule) {
  6741. "use strict";
  6742. this.report(message, line, col, rule);
  6743. },
  6744. /**
  6745. * Report an issue.
  6746. * @param {String} message The message to store.
  6747. * @param {int} line The line number.
  6748. * @param {int} col The column number.
  6749. * @param {Object} rule The rule this message relates to.
  6750. * @method report
  6751. */
  6752. report: function(message, line, col, rule) {
  6753. "use strict";
  6754. // Check if rule violation should be allowed
  6755. if (this.allow.hasOwnProperty(line) && this.allow[line].hasOwnProperty(rule.id)) {
  6756. return;
  6757. }
  6758. var ignore = false;
  6759. CSSLint.Util.forEach(this.ignore, function (range) {
  6760. if (range[0] <= line && line <= range[1]) {
  6761. ignore = true;
  6762. }
  6763. });
  6764. if (ignore) {
  6765. return;
  6766. }
  6767. this.messages.push({
  6768. type : this.ruleset[rule.id] === 2 ? "error" : "warning",
  6769. line : line,
  6770. col : col,
  6771. message : message,
  6772. evidence: this.lines[line-1],
  6773. rule : rule
  6774. });
  6775. },
  6776. /**
  6777. * Report some informational text.
  6778. * @param {String} message The message to store.
  6779. * @param {int} line The line number.
  6780. * @param {int} col The column number.
  6781. * @param {Object} rule The rule this message relates to.
  6782. * @method info
  6783. */
  6784. info: function(message, line, col, rule) {
  6785. "use strict";
  6786. this.messages.push({
  6787. type : "info",
  6788. line : line,
  6789. col : col,
  6790. message : message,
  6791. evidence: this.lines[line-1],
  6792. rule : rule
  6793. });
  6794. },
  6795. /**
  6796. * Report some rollup error information.
  6797. * @param {String} message The message to store.
  6798. * @param {Object} rule The rule this message relates to.
  6799. * @method rollupError
  6800. */
  6801. rollupError: function(message, rule) {
  6802. "use strict";
  6803. this.messages.push({
  6804. type : "error",
  6805. rollup : true,
  6806. message : message,
  6807. rule : rule
  6808. });
  6809. },
  6810. /**
  6811. * Report some rollup warning information.
  6812. * @param {String} message The message to store.
  6813. * @param {Object} rule The rule this message relates to.
  6814. * @method rollupWarn
  6815. */
  6816. rollupWarn: function(message, rule) {
  6817. "use strict";
  6818. this.messages.push({
  6819. type : "warning",
  6820. rollup : true,
  6821. message : message,
  6822. rule : rule
  6823. });
  6824. },
  6825. /**
  6826. * Report a statistic.
  6827. * @param {String} name The name of the stat to store.
  6828. * @param {Variant} value The value of the stat.
  6829. * @method stat
  6830. */
  6831. stat: function(name, value) {
  6832. "use strict";
  6833. this.stats[name] = value;
  6834. }
  6835. };
  6836. // expose for testing purposes
  6837. CSSLint._Reporter = Reporter;
  6838. /*
  6839. * Utility functions that make life easier.
  6840. */
  6841. CSSLint.Util = {
  6842. /*
  6843. * Adds all properties from supplier onto receiver,
  6844. * overwriting if the same name already exists on
  6845. * receiver.
  6846. * @param {Object} The object to receive the properties.
  6847. * @param {Object} The object to provide the properties.
  6848. * @return {Object} The receiver
  6849. */
  6850. mix: function(receiver, supplier) {
  6851. "use strict";
  6852. var prop;
  6853. for (prop in supplier) {
  6854. if (supplier.hasOwnProperty(prop)) {
  6855. receiver[prop] = supplier[prop];
  6856. }
  6857. }
  6858. return prop;
  6859. },
  6860. /*
  6861. * Polyfill for array indexOf() method.
  6862. * @param {Array} values The array to search.
  6863. * @param {Variant} value The value to search for.
  6864. * @return {int} The index of the value if found, -1 if not.
  6865. */
  6866. indexOf: function(values, value) {
  6867. "use strict";
  6868. if (values.indexOf) {
  6869. return values.indexOf(value);
  6870. } else {
  6871. for (var i=0, len=values.length; i < len; i++) {
  6872. if (values[i] === value) {
  6873. return i;
  6874. }
  6875. }
  6876. return -1;
  6877. }
  6878. },
  6879. /*
  6880. * Polyfill for array forEach() method.
  6881. * @param {Array} values The array to operate on.
  6882. * @param {Function} func The function to call on each item.
  6883. * @return {void}
  6884. */
  6885. forEach: function(values, func) {
  6886. "use strict";
  6887. if (values.forEach) {
  6888. return values.forEach(func);
  6889. } else {
  6890. for (var i=0, len=values.length; i < len; i++) {
  6891. func(values[i], i, values);
  6892. }
  6893. }
  6894. }
  6895. };
  6896. /*
  6897. * Rule: Don't use adjoining classes (.foo.bar).
  6898. */
  6899. CSSLint.addRule({
  6900. // rule information
  6901. id: "adjoining-classes",
  6902. name: "Disallow adjoining classes",
  6903. desc: "Don't use adjoining classes.",
  6904. url: "https://github.com/CSSLint/csslint/wiki/Disallow-adjoining-classes",
  6905. browsers: "IE6",
  6906. // initialization
  6907. init: function(parser, reporter) {
  6908. "use strict";
  6909. var rule = this;
  6910. parser.addListener("startrule", function(event) {
  6911. var selectors = event.selectors,
  6912. selector,
  6913. part,
  6914. modifier,
  6915. classCount,
  6916. i, j, k;
  6917. for (i=0; i < selectors.length; i++) {
  6918. selector = selectors[i];
  6919. for (j=0; j < selector.parts.length; j++) {
  6920. part = selector.parts[j];
  6921. if (part.type === parser.SELECTOR_PART_TYPE) {
  6922. classCount = 0;
  6923. for (k=0; k < part.modifiers.length; k++) {
  6924. modifier = part.modifiers[k];
  6925. if (modifier.type === "class") {
  6926. classCount++;
  6927. }
  6928. if (classCount > 1){
  6929. reporter.report("Adjoining classes: "+selectors[i].text, part.line, part.col, rule);
  6930. }
  6931. }
  6932. }
  6933. }
  6934. }
  6935. });
  6936. }
  6937. });
  6938. /*
  6939. * Rule: Don't use width or height when using padding or border.
  6940. */
  6941. CSSLint.addRule({
  6942. // rule information
  6943. id: "box-model",
  6944. name: "Beware of broken box size",
  6945. desc: "Don't use width or height when using padding or border.",
  6946. url: "https://github.com/CSSLint/csslint/wiki/Beware-of-box-model-size",
  6947. browsers: "All",
  6948. // initialization
  6949. init: function(parser, reporter) {
  6950. "use strict";
  6951. var rule = this,
  6952. widthProperties = {
  6953. border: 1,
  6954. "border-left": 1,
  6955. "border-right": 1,
  6956. padding: 1,
  6957. "padding-left": 1,
  6958. "padding-right": 1
  6959. },
  6960. heightProperties = {
  6961. border: 1,
  6962. "border-bottom": 1,
  6963. "border-top": 1,
  6964. padding: 1,
  6965. "padding-bottom": 1,
  6966. "padding-top": 1
  6967. },
  6968. properties,
  6969. boxSizing = false;
  6970. function startRule() {
  6971. properties = {};
  6972. boxSizing = false;
  6973. }
  6974. function endRule() {
  6975. var prop, value;
  6976. if (!boxSizing) {
  6977. if (properties.height) {
  6978. for (prop in heightProperties) {
  6979. if (heightProperties.hasOwnProperty(prop) && properties[prop]) {
  6980. value = properties[prop].value;
  6981. // special case for padding
  6982. if (!(prop === "padding" && value.parts.length === 2 && value.parts[0].value === 0)) {
  6983. reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
  6984. }
  6985. }
  6986. }
  6987. }
  6988. if (properties.width) {
  6989. for (prop in widthProperties) {
  6990. if (widthProperties.hasOwnProperty(prop) && properties[prop]) {
  6991. value = properties[prop].value;
  6992. if (!(prop === "padding" && value.parts.length === 2 && value.parts[1].value === 0)) {
  6993. reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
  6994. }
  6995. }
  6996. }
  6997. }
  6998. }
  6999. }
  7000. parser.addListener("startrule", startRule);
  7001. parser.addListener("startfontface", startRule);
  7002. parser.addListener("startpage", startRule);
  7003. parser.addListener("startpagemargin", startRule);
  7004. parser.addListener("startkeyframerule", startRule);
  7005. parser.addListener("startviewport", startRule);
  7006. parser.addListener("property", function(event) {
  7007. var name = event.property.text.toLowerCase();
  7008. if (heightProperties[name] || widthProperties[name]) {
  7009. if (!/^0\S*$/.test(event.value) && !(name === "border" && event.value.toString() === "none")) {
  7010. properties[name] = {
  7011. line: event.property.line,
  7012. col: event.property.col,
  7013. value: event.value
  7014. };
  7015. }
  7016. } else {
  7017. if (/^(width|height)/i.test(name) && /^(length|percentage)/.test(event.value.parts[0].type)) {
  7018. properties[name] = 1;
  7019. } else if (name === "box-sizing") {
  7020. boxSizing = true;
  7021. }
  7022. }
  7023. });
  7024. parser.addListener("endrule", endRule);
  7025. parser.addListener("endfontface", endRule);
  7026. parser.addListener("endpage", endRule);
  7027. parser.addListener("endpagemargin", endRule);
  7028. parser.addListener("endkeyframerule", endRule);
  7029. parser.addListener("endviewport", endRule);
  7030. }
  7031. });
  7032. /*
  7033. * Rule: box-sizing doesn't work in IE6 and IE7.
  7034. */
  7035. CSSLint.addRule({
  7036. // rule information
  7037. id: "box-sizing",
  7038. name: "Disallow use of box-sizing",
  7039. desc: "The box-sizing properties isn't supported in IE6 and IE7.",
  7040. url: "https://github.com/CSSLint/csslint/wiki/Disallow-box-sizing",
  7041. browsers: "IE6, IE7",
  7042. tags: ["Compatibility"],
  7043. // initialization
  7044. init: function(parser, reporter) {
  7045. "use strict";
  7046. var rule = this;
  7047. parser.addListener("property", function(event) {
  7048. var name = event.property.text.toLowerCase();
  7049. if (name === "box-sizing") {
  7050. reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule);
  7051. }
  7052. });
  7053. }
  7054. });
  7055. /*
  7056. * Rule: Use the bulletproof @font-face syntax to avoid 404's in old IE
  7057. * (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax)
  7058. */
  7059. CSSLint.addRule({
  7060. // rule information
  7061. id: "bulletproof-font-face",
  7062. name: "Use the bulletproof @font-face syntax",
  7063. desc: "Use the bulletproof @font-face syntax to avoid 404's in old IE (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax).",
  7064. url: "https://github.com/CSSLint/csslint/wiki/Bulletproof-font-face",
  7065. browsers: "All",
  7066. // initialization
  7067. init: function(parser, reporter) {
  7068. "use strict";
  7069. var rule = this,
  7070. fontFaceRule = false,
  7071. firstSrc = true,
  7072. ruleFailed = false,
  7073. line, col;
  7074. // Mark the start of a @font-face declaration so we only test properties inside it
  7075. parser.addListener("startfontface", function() {
  7076. fontFaceRule = true;
  7077. });
  7078. parser.addListener("property", function(event) {
  7079. // If we aren't inside an @font-face declaration then just return
  7080. if (!fontFaceRule) {
  7081. return;
  7082. }
  7083. var propertyName = event.property.toString().toLowerCase(),
  7084. value = event.value.toString();
  7085. // Set the line and col numbers for use in the endfontface listener
  7086. line = event.line;
  7087. col = event.col;
  7088. // This is the property that we care about, we can ignore the rest
  7089. if (propertyName === "src") {
  7090. var regex = /^\s?url\(['"].+\.eot\?.*['"]\)\s*format\(['"]embedded-opentype['"]\).*$/i;
  7091. // We need to handle the advanced syntax with two src properties
  7092. if (!value.match(regex) && firstSrc) {
  7093. ruleFailed = true;
  7094. firstSrc = false;
  7095. } else if (value.match(regex) && !firstSrc) {
  7096. ruleFailed = false;
  7097. }
  7098. }
  7099. });
  7100. // Back to normal rules that we don't need to test
  7101. parser.addListener("endfontface", function() {
  7102. fontFaceRule = false;
  7103. if (ruleFailed) {
  7104. reporter.report("@font-face declaration doesn't follow the fontspring bulletproof syntax.", line, col, rule);
  7105. }
  7106. });
  7107. }
  7108. });
  7109. /*
  7110. * Rule: Include all compatible vendor prefixes to reach a wider
  7111. * range of users.
  7112. */
  7113. CSSLint.addRule({
  7114. // rule information
  7115. id: "compatible-vendor-prefixes",
  7116. name: "Require compatible vendor prefixes",
  7117. desc: "Include all compatible vendor prefixes to reach a wider range of users.",
  7118. url: "https://github.com/CSSLint/csslint/wiki/Require-compatible-vendor-prefixes",
  7119. browsers: "All",
  7120. // initialization
  7121. init: function (parser, reporter) {
  7122. "use strict";
  7123. var rule = this,
  7124. compatiblePrefixes,
  7125. properties,
  7126. prop,
  7127. variations,
  7128. prefixed,
  7129. i,
  7130. len,
  7131. inKeyFrame = false,
  7132. arrayPush = Array.prototype.push,
  7133. applyTo = [];
  7134. // See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details
  7135. compatiblePrefixes = {
  7136. "animation" : "webkit",
  7137. "animation-delay" : "webkit",
  7138. "animation-direction" : "webkit",
  7139. "animation-duration" : "webkit",
  7140. "animation-fill-mode" : "webkit",
  7141. "animation-iteration-count" : "webkit",
  7142. "animation-name" : "webkit",
  7143. "animation-play-state" : "webkit",
  7144. "animation-timing-function" : "webkit",
  7145. "appearance" : "webkit moz",
  7146. "border-end" : "webkit moz",
  7147. "border-end-color" : "webkit moz",
  7148. "border-end-style" : "webkit moz",
  7149. "border-end-width" : "webkit moz",
  7150. "border-image" : "webkit moz o",
  7151. "border-radius" : "webkit",
  7152. "border-start" : "webkit moz",
  7153. "border-start-color" : "webkit moz",
  7154. "border-start-style" : "webkit moz",
  7155. "border-start-width" : "webkit moz",
  7156. "box-align" : "webkit moz ms",
  7157. "box-direction" : "webkit moz ms",
  7158. "box-flex" : "webkit moz ms",
  7159. "box-lines" : "webkit ms",
  7160. "box-ordinal-group" : "webkit moz ms",
  7161. "box-orient" : "webkit moz ms",
  7162. "box-pack" : "webkit moz ms",
  7163. "box-sizing" : "",
  7164. "box-shadow" : "",
  7165. "column-count" : "webkit moz ms",
  7166. "column-gap" : "webkit moz ms",
  7167. "column-rule" : "webkit moz ms",
  7168. "column-rule-color" : "webkit moz ms",
  7169. "column-rule-style" : "webkit moz ms",
  7170. "column-rule-width" : "webkit moz ms",
  7171. "column-width" : "webkit moz ms",
  7172. "hyphens" : "epub moz",
  7173. "line-break" : "webkit ms",
  7174. "margin-end" : "webkit moz",
  7175. "margin-start" : "webkit moz",
  7176. "marquee-speed" : "webkit wap",
  7177. "marquee-style" : "webkit wap",
  7178. "padding-end" : "webkit moz",
  7179. "padding-start" : "webkit moz",
  7180. "tab-size" : "moz o",
  7181. "text-size-adjust" : "webkit ms",
  7182. "transform" : "webkit ms",
  7183. "transform-origin" : "webkit ms",
  7184. "transition" : "",
  7185. "transition-delay" : "",
  7186. "transition-duration" : "",
  7187. "transition-property" : "",
  7188. "transition-timing-function" : "",
  7189. "user-modify" : "webkit moz",
  7190. "user-select" : "webkit moz ms",
  7191. "word-break" : "epub ms",
  7192. "writing-mode" : "epub ms"
  7193. };
  7194. for (prop in compatiblePrefixes) {
  7195. if (compatiblePrefixes.hasOwnProperty(prop)) {
  7196. variations = [];
  7197. prefixed = compatiblePrefixes[prop].split(" ");
  7198. for (i = 0, len = prefixed.length; i < len; i++) {
  7199. variations.push("-" + prefixed[i] + "-" + prop);
  7200. }
  7201. compatiblePrefixes[prop] = variations;
  7202. arrayPush.apply(applyTo, variations);
  7203. }
  7204. }
  7205. parser.addListener("startrule", function () {
  7206. properties = [];
  7207. });
  7208. parser.addListener("startkeyframes", function (event) {
  7209. inKeyFrame = event.prefix || true;
  7210. });
  7211. parser.addListener("endkeyframes", function () {
  7212. inKeyFrame = false;
  7213. });
  7214. parser.addListener("property", function (event) {
  7215. var name = event.property;
  7216. if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {
  7217. // e.g., -moz-transform is okay to be alone in @-moz-keyframes
  7218. if (!inKeyFrame || typeof inKeyFrame !== "string" ||
  7219. name.text.indexOf("-" + inKeyFrame + "-") !== 0) {
  7220. properties.push(name);
  7221. }
  7222. }
  7223. });
  7224. parser.addListener("endrule", function () {
  7225. if (!properties.length) {
  7226. return;
  7227. }
  7228. var propertyGroups = {},
  7229. i,
  7230. len,
  7231. name,
  7232. prop,
  7233. variations,
  7234. value,
  7235. full,
  7236. actual,
  7237. item,
  7238. propertiesSpecified;
  7239. for (i = 0, len = properties.length; i < len; i++) {
  7240. name = properties[i];
  7241. for (prop in compatiblePrefixes) {
  7242. if (compatiblePrefixes.hasOwnProperty(prop)) {
  7243. variations = compatiblePrefixes[prop];
  7244. if (CSSLint.Util.indexOf(variations, name.text) > -1) {
  7245. if (!propertyGroups[prop]) {
  7246. propertyGroups[prop] = {
  7247. full: variations.slice(0),
  7248. actual: [],
  7249. actualNodes: []
  7250. };
  7251. }
  7252. if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
  7253. propertyGroups[prop].actual.push(name.text);
  7254. propertyGroups[prop].actualNodes.push(name);
  7255. }
  7256. }
  7257. }
  7258. }
  7259. }
  7260. for (prop in propertyGroups) {
  7261. if (propertyGroups.hasOwnProperty(prop)) {
  7262. value = propertyGroups[prop];
  7263. full = value.full;
  7264. actual = value.actual;
  7265. if (full.length > actual.length) {
  7266. for (i = 0, len = full.length; i < len; i++) {
  7267. item = full[i];
  7268. if (CSSLint.Util.indexOf(actual, item) === -1) {
  7269. propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length === 2) ? actual.join(" and ") : actual.join(", ");
  7270. reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
  7271. }
  7272. }
  7273. }
  7274. }
  7275. }
  7276. });
  7277. }
  7278. });
  7279. /*
  7280. * Rule: Certain properties don't play well with certain display values.
  7281. * - float should not be used with inline-block
  7282. * - height, width, margin-top, margin-bottom, float should not be used with inline
  7283. * - vertical-align should not be used with block
  7284. * - margin, float should not be used with table-*
  7285. */
  7286. CSSLint.addRule({
  7287. // rule information
  7288. id: "display-property-grouping",
  7289. name: "Require properties appropriate for display",
  7290. desc: "Certain properties shouldn't be used with certain display property values.",
  7291. url: "https://github.com/CSSLint/csslint/wiki/Require-properties-appropriate-for-display",
  7292. browsers: "All",
  7293. // initialization
  7294. init: function(parser, reporter) {
  7295. "use strict";
  7296. var rule = this;
  7297. var propertiesToCheck = {
  7298. display: 1,
  7299. "float": "none",
  7300. height: 1,
  7301. width: 1,
  7302. margin: 1,
  7303. "margin-left": 1,
  7304. "margin-right": 1,
  7305. "margin-bottom": 1,
  7306. "margin-top": 1,
  7307. padding: 1,
  7308. "padding-left": 1,
  7309. "padding-right": 1,
  7310. "padding-bottom": 1,
  7311. "padding-top": 1,
  7312. "vertical-align": 1
  7313. },
  7314. properties;
  7315. function reportProperty(name, display, msg) {
  7316. if (properties[name]) {
  7317. if (typeof propertiesToCheck[name] !== "string" || properties[name].value.toLowerCase() !== propertiesToCheck[name]) {
  7318. reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule);
  7319. }
  7320. }
  7321. }
  7322. function startRule() {
  7323. properties = {};
  7324. }
  7325. function endRule() {
  7326. var display = properties.display ? properties.display.value : null;
  7327. if (display) {
  7328. switch (display) {
  7329. case "inline":
  7330. // height, width, margin-top, margin-bottom, float should not be used with inline
  7331. reportProperty("height", display);
  7332. reportProperty("width", display);
  7333. reportProperty("margin", display);
  7334. reportProperty("margin-top", display);
  7335. reportProperty("margin-bottom", display);
  7336. reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");
  7337. break;
  7338. case "block":
  7339. // vertical-align should not be used with block
  7340. reportProperty("vertical-align", display);
  7341. break;
  7342. case "inline-block":
  7343. // float should not be used with inline-block
  7344. reportProperty("float", display);
  7345. break;
  7346. default:
  7347. // margin, float should not be used with table
  7348. if (display.indexOf("table-") === 0) {
  7349. reportProperty("margin", display);
  7350. reportProperty("margin-left", display);
  7351. reportProperty("margin-right", display);
  7352. reportProperty("margin-top", display);
  7353. reportProperty("margin-bottom", display);
  7354. reportProperty("float", display);
  7355. }
  7356. // otherwise do nothing
  7357. }
  7358. }
  7359. }
  7360. parser.addListener("startrule", startRule);
  7361. parser.addListener("startfontface", startRule);
  7362. parser.addListener("startkeyframerule", startRule);
  7363. parser.addListener("startpagemargin", startRule);
  7364. parser.addListener("startpage", startRule);
  7365. parser.addListener("startviewport", startRule);
  7366. parser.addListener("property", function(event) {
  7367. var name = event.property.text.toLowerCase();
  7368. if (propertiesToCheck[name]) {
  7369. properties[name] = {
  7370. value: event.value.text,
  7371. line: event.property.line,
  7372. col: event.property.col
  7373. };
  7374. }
  7375. });
  7376. parser.addListener("endrule", endRule);
  7377. parser.addListener("endfontface", endRule);
  7378. parser.addListener("endkeyframerule", endRule);
  7379. parser.addListener("endpagemargin", endRule);
  7380. parser.addListener("endpage", endRule);
  7381. parser.addListener("endviewport", endRule);
  7382. }
  7383. });
  7384. /*
  7385. * Rule: Disallow duplicate background-images (using url).
  7386. */
  7387. CSSLint.addRule({
  7388. // rule information
  7389. id: "duplicate-background-images",
  7390. name: "Disallow duplicate background images",
  7391. desc: "Every background-image should be unique. Use a common class for e.g. sprites.",
  7392. url: "https://github.com/CSSLint/csslint/wiki/Disallow-duplicate-background-images",
  7393. browsers: "All",
  7394. // initialization
  7395. init: function(parser, reporter) {
  7396. "use strict";
  7397. var rule = this,
  7398. stack = {};
  7399. parser.addListener("property", function(event) {
  7400. var name = event.property.text,
  7401. value = event.value,
  7402. i, len;
  7403. if (name.match(/background/i)) {
  7404. for (i=0, len=value.parts.length; i < len; i++) {
  7405. if (value.parts[i].type === "uri") {
  7406. if (typeof stack[value.parts[i].uri] === "undefined") {
  7407. stack[value.parts[i].uri] = event;
  7408. } else {
  7409. reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule);
  7410. }
  7411. }
  7412. }
  7413. }
  7414. });
  7415. }
  7416. });
  7417. /*
  7418. * Rule: Duplicate properties must appear one after the other. If an already-defined
  7419. * property appears somewhere else in the rule, then it's likely an error.
  7420. */
  7421. CSSLint.addRule({
  7422. // rule information
  7423. id: "duplicate-properties",
  7424. name: "Disallow duplicate properties",
  7425. desc: "Duplicate properties must appear one after the other.",
  7426. url: "https://github.com/CSSLint/csslint/wiki/Disallow-duplicate-properties",
  7427. browsers: "All",
  7428. // initialization
  7429. init: function(parser, reporter) {
  7430. "use strict";
  7431. var rule = this,
  7432. properties,
  7433. lastProperty;
  7434. function startRule() {
  7435. properties = {};
  7436. }
  7437. parser.addListener("startrule", startRule);
  7438. parser.addListener("startfontface", startRule);
  7439. parser.addListener("startpage", startRule);
  7440. parser.addListener("startpagemargin", startRule);
  7441. parser.addListener("startkeyframerule", startRule);
  7442. parser.addListener("startviewport", startRule);
  7443. parser.addListener("property", function(event) {
  7444. var property = event.property,
  7445. name = property.text.toLowerCase();
  7446. if (properties[name] && (lastProperty !== name || properties[name] === event.value.text)) {
  7447. reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule);
  7448. }
  7449. properties[name] = event.value.text;
  7450. lastProperty = name;
  7451. });
  7452. }
  7453. });
  7454. /*
  7455. * Rule: Style rules without any properties defined should be removed.
  7456. */
  7457. CSSLint.addRule({
  7458. // rule information
  7459. id: "empty-rules",
  7460. name: "Disallow empty rules",
  7461. desc: "Rules without any properties specified should be removed.",
  7462. url: "https://github.com/CSSLint/csslint/wiki/Disallow-empty-rules",
  7463. browsers: "All",
  7464. // initialization
  7465. init: function(parser, reporter) {
  7466. "use strict";
  7467. var rule = this,
  7468. count = 0;
  7469. parser.addListener("startrule", function() {
  7470. count=0;
  7471. });
  7472. parser.addListener("property", function() {
  7473. count++;
  7474. });
  7475. parser.addListener("endrule", function(event) {
  7476. var selectors = event.selectors;
  7477. if (count === 0) {
  7478. reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule);
  7479. }
  7480. });
  7481. }
  7482. });
  7483. /*
  7484. * Rule: There should be no syntax errors. (Duh.)
  7485. */
  7486. CSSLint.addRule({
  7487. // rule information
  7488. id: "errors",
  7489. name: "Parsing Errors",
  7490. desc: "This rule looks for recoverable syntax errors.",
  7491. browsers: "All",
  7492. // initialization
  7493. init: function(parser, reporter) {
  7494. "use strict";
  7495. var rule = this;
  7496. parser.addListener("error", function(event) {
  7497. reporter.error(event.message, event.line, event.col, rule);
  7498. });
  7499. }
  7500. });
  7501. CSSLint.addRule({
  7502. // rule information
  7503. id: "fallback-colors",
  7504. name: "Require fallback colors",
  7505. desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",
  7506. url: "https://github.com/CSSLint/csslint/wiki/Require-fallback-colors",
  7507. browsers: "IE6,IE7,IE8",
  7508. // initialization
  7509. init: function(parser, reporter) {
  7510. "use strict";
  7511. var rule = this,
  7512. lastProperty,
  7513. propertiesToCheck = {
  7514. color: 1,
  7515. background: 1,
  7516. "border-color": 1,
  7517. "border-top-color": 1,
  7518. "border-right-color": 1,
  7519. "border-bottom-color": 1,
  7520. "border-left-color": 1,
  7521. border: 1,
  7522. "border-top": 1,
  7523. "border-right": 1,
  7524. "border-bottom": 1,
  7525. "border-left": 1,
  7526. "background-color": 1
  7527. };
  7528. function startRule() {
  7529. lastProperty = null;
  7530. }
  7531. parser.addListener("startrule", startRule);
  7532. parser.addListener("startfontface", startRule);
  7533. parser.addListener("startpage", startRule);
  7534. parser.addListener("startpagemargin", startRule);
  7535. parser.addListener("startkeyframerule", startRule);
  7536. parser.addListener("startviewport", startRule);
  7537. parser.addListener("property", function(event) {
  7538. var property = event.property,
  7539. name = property.text.toLowerCase(),
  7540. parts = event.value.parts,
  7541. i = 0,
  7542. colorType = "",
  7543. len = parts.length;
  7544. if (propertiesToCheck[name]) {
  7545. while (i < len) {
  7546. if (parts[i].type === "color") {
  7547. if ("alpha" in parts[i] || "hue" in parts[i]) {
  7548. if (/([^\)]+)\(/.test(parts[i])) {
  7549. colorType = RegExp.$1.toUpperCase();
  7550. }
  7551. if (!lastProperty || (lastProperty.property.text.toLowerCase() !== name || lastProperty.colorType !== "compat")) {
  7552. reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule);
  7553. }
  7554. } else {
  7555. event.colorType = "compat";
  7556. }
  7557. }
  7558. i++;
  7559. }
  7560. }
  7561. lastProperty = event;
  7562. });
  7563. }
  7564. });
  7565. /*
  7566. * Rule: You shouldn't use more than 10 floats. If you do, there's probably
  7567. * room for some abstraction.
  7568. */
  7569. CSSLint.addRule({
  7570. // rule information
  7571. id: "floats",
  7572. name: "Disallow too many floats",
  7573. desc: "This rule tests if the float property is used too many times",
  7574. url: "https://github.com/CSSLint/csslint/wiki/Disallow-too-many-floats",
  7575. browsers: "All",
  7576. // initialization
  7577. init: function(parser, reporter) {
  7578. "use strict";
  7579. var rule = this;
  7580. var count = 0;
  7581. // count how many times "float" is used
  7582. parser.addListener("property", function(event) {
  7583. if (event.property.text.toLowerCase() === "float" &&
  7584. event.value.text.toLowerCase() !== "none") {
  7585. count++;
  7586. }
  7587. });
  7588. // report the results
  7589. parser.addListener("endstylesheet", function() {
  7590. reporter.stat("floats", count);
  7591. if (count >= 10) {
  7592. reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule);
  7593. }
  7594. });
  7595. }
  7596. });
  7597. /*
  7598. * Rule: Avoid too many @font-face declarations in the same stylesheet.
  7599. */
  7600. CSSLint.addRule({
  7601. // rule information
  7602. id: "font-faces",
  7603. name: "Don't use too many web fonts",
  7604. desc: "Too many different web fonts in the same stylesheet.",
  7605. url: "https://github.com/CSSLint/csslint/wiki/Don%27t-use-too-many-web-fonts",
  7606. browsers: "All",
  7607. // initialization
  7608. init: function(parser, reporter) {
  7609. "use strict";
  7610. var rule = this,
  7611. count = 0;
  7612. parser.addListener("startfontface", function() {
  7613. count++;
  7614. });
  7615. parser.addListener("endstylesheet", function() {
  7616. if (count > 5) {
  7617. reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule);
  7618. }
  7619. });
  7620. }
  7621. });
  7622. /*
  7623. * Rule: You shouldn't need more than 9 font-size declarations.
  7624. */
  7625. CSSLint.addRule({
  7626. // rule information
  7627. id: "font-sizes",
  7628. name: "Disallow too many font sizes",
  7629. desc: "Checks the number of font-size declarations.",
  7630. url: "https://github.com/CSSLint/csslint/wiki/Don%27t-use-too-many-font-size-declarations",
  7631. browsers: "All",
  7632. // initialization
  7633. init: function(parser, reporter) {
  7634. "use strict";
  7635. var rule = this,
  7636. count = 0;
  7637. // check for use of "font-size"
  7638. parser.addListener("property", function(event) {
  7639. if (event.property.toString() === "font-size") {
  7640. count++;
  7641. }
  7642. });
  7643. // report the results
  7644. parser.addListener("endstylesheet", function() {
  7645. reporter.stat("font-sizes", count);
  7646. if (count >= 10) {
  7647. reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule);
  7648. }
  7649. });
  7650. }
  7651. });
  7652. /*
  7653. * Rule: When using a vendor-prefixed gradient, make sure to use them all.
  7654. */
  7655. CSSLint.addRule({
  7656. // rule information
  7657. id: "gradients",
  7658. name: "Require all gradient definitions",
  7659. desc: "When using a vendor-prefixed gradient, make sure to use them all.",
  7660. url: "https://github.com/CSSLint/csslint/wiki/Require-all-gradient-definitions",
  7661. browsers: "All",
  7662. // initialization
  7663. init: function(parser, reporter) {
  7664. "use strict";
  7665. var rule = this,
  7666. gradients;
  7667. parser.addListener("startrule", function() {
  7668. gradients = {
  7669. moz: 0,
  7670. webkit: 0,
  7671. oldWebkit: 0,
  7672. o: 0
  7673. };
  7674. });
  7675. parser.addListener("property", function(event) {
  7676. if (/\-(moz|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)) {
  7677. gradients[RegExp.$1] = 1;
  7678. } else if (/\-webkit\-gradient/i.test(event.value)) {
  7679. gradients.oldWebkit = 1;
  7680. }
  7681. });
  7682. parser.addListener("endrule", function(event) {
  7683. var missing = [];
  7684. if (!gradients.moz) {
  7685. missing.push("Firefox 3.6+");
  7686. }
  7687. if (!gradients.webkit) {
  7688. missing.push("Webkit (Safari 5+, Chrome)");
  7689. }
  7690. if (!gradients.oldWebkit) {
  7691. missing.push("Old Webkit (Safari 4+, Chrome)");
  7692. }
  7693. if (!gradients.o) {
  7694. missing.push("Opera 11.1+");
  7695. }
  7696. if (missing.length && missing.length < 4) {
  7697. reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule);
  7698. }
  7699. });
  7700. }
  7701. });
  7702. /*
  7703. * Rule: Don't use IDs for selectors.
  7704. */
  7705. CSSLint.addRule({
  7706. // rule information
  7707. id: "ids",
  7708. name: "Disallow IDs in selectors",
  7709. desc: "Selectors should not contain IDs.",
  7710. url: "https://github.com/CSSLint/csslint/wiki/Disallow-IDs-in-selectors",
  7711. browsers: "All",
  7712. // initialization
  7713. init: function(parser, reporter) {
  7714. "use strict";
  7715. var rule = this;
  7716. parser.addListener("startrule", function(event) {
  7717. var selectors = event.selectors,
  7718. selector,
  7719. part,
  7720. modifier,
  7721. idCount,
  7722. i, j, k;
  7723. for (i=0; i < selectors.length; i++) {
  7724. selector = selectors[i];
  7725. idCount = 0;
  7726. for (j=0; j < selector.parts.length; j++) {
  7727. part = selector.parts[j];
  7728. if (part.type === parser.SELECTOR_PART_TYPE) {
  7729. for (k=0; k < part.modifiers.length; k++) {
  7730. modifier = part.modifiers[k];
  7731. if (modifier.type === "id") {
  7732. idCount++;
  7733. }
  7734. }
  7735. }
  7736. }
  7737. if (idCount === 1) {
  7738. reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule);
  7739. } else if (idCount > 1) {
  7740. reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule);
  7741. }
  7742. }
  7743. });
  7744. }
  7745. });
  7746. /*
  7747. * Rule: IE6-9 supports up to 31 stylesheet import.
  7748. * Reference:
  7749. * http://blogs.msdn.com/b/ieinternals/archive/2011/05/14/internet-explorer-stylesheet-rule-selector-import-sheet-limit-maximum.aspx
  7750. */
  7751. CSSLint.addRule({
  7752. // rule information
  7753. id: "import-ie-limit",
  7754. name: "@import limit on IE6-IE9",
  7755. desc: "IE6-9 supports up to 31 @import per stylesheet",
  7756. browsers: "IE6, IE7, IE8, IE9",
  7757. // initialization
  7758. init: function(parser, reporter) {
  7759. "use strict";
  7760. var rule = this,
  7761. MAX_IMPORT_COUNT = 31,
  7762. count = 0;
  7763. function startPage() {
  7764. count = 0;
  7765. }
  7766. parser.addListener("startpage", startPage);
  7767. parser.addListener("import", function() {
  7768. count++;
  7769. });
  7770. parser.addListener("endstylesheet", function() {
  7771. if (count > MAX_IMPORT_COUNT) {
  7772. reporter.rollupError(
  7773. "Too many @import rules (" + count + "). IE6-9 supports up to 31 import per stylesheet.",
  7774. rule
  7775. );
  7776. }
  7777. });
  7778. }
  7779. });
  7780. /*
  7781. * Rule: Don't use @import, use <link> instead.
  7782. */
  7783. CSSLint.addRule({
  7784. // rule information
  7785. id: "import",
  7786. name: "Disallow @import",
  7787. desc: "Don't use @import, use <link> instead.",
  7788. url: "https://github.com/CSSLint/csslint/wiki/Disallow-%40import",
  7789. browsers: "All",
  7790. // initialization
  7791. init: function(parser, reporter) {
  7792. "use strict";
  7793. var rule = this;
  7794. parser.addListener("import", function(event) {
  7795. reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule);
  7796. });
  7797. }
  7798. });
  7799. /*
  7800. * Rule: Make sure !important is not overused, this could lead to specificity
  7801. * war. Display a warning on !important declarations, an error if it's
  7802. * used more at least 10 times.
  7803. */
  7804. CSSLint.addRule({
  7805. // rule information
  7806. id: "important",
  7807. name: "Disallow !important",
  7808. desc: "Be careful when using !important declaration",
  7809. url: "https://github.com/CSSLint/csslint/wiki/Disallow-%21important",
  7810. browsers: "All",
  7811. // initialization
  7812. init: function(parser, reporter) {
  7813. "use strict";
  7814. var rule = this,
  7815. count = 0;
  7816. // warn that important is used and increment the declaration counter
  7817. parser.addListener("property", function(event) {
  7818. if (event.important === true) {
  7819. count++;
  7820. reporter.report("Use of !important", event.line, event.col, rule);
  7821. }
  7822. });
  7823. // if there are more than 10, show an error
  7824. parser.addListener("endstylesheet", function() {
  7825. reporter.stat("important", count);
  7826. if (count >= 10) {
  7827. reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specificity issues.", rule);
  7828. }
  7829. });
  7830. }
  7831. });
  7832. /*
  7833. * Rule: Properties should be known (listed in CSS3 specification) or
  7834. * be a vendor-prefixed property.
  7835. */
  7836. CSSLint.addRule({
  7837. // rule information
  7838. id: "known-properties",
  7839. name: "Require use of known properties",
  7840. desc: "Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",
  7841. url: "https://github.com/CSSLint/csslint/wiki/Require-use-of-known-properties",
  7842. browsers: "All",
  7843. // initialization
  7844. init: function(parser, reporter) {
  7845. "use strict";
  7846. var rule = this;
  7847. parser.addListener("property", function(event) {
  7848. // the check is handled entirely by the parser-lib (https://github.com/nzakas/parser-lib)
  7849. if (event.invalid) {
  7850. reporter.report(event.invalid.message, event.line, event.col, rule);
  7851. }
  7852. });
  7853. }
  7854. });
  7855. /*
  7856. * Rule: All properties should be in alphabetical order.
  7857. */
  7858. CSSLint.addRule({
  7859. // rule information
  7860. id: "order-alphabetical",
  7861. name: "Alphabetical order",
  7862. desc: "Assure properties are in alphabetical order",
  7863. browsers: "All",
  7864. // initialization
  7865. init: function(parser, reporter) {
  7866. "use strict";
  7867. var rule = this,
  7868. properties;
  7869. var startRule = function () {
  7870. properties = [];
  7871. };
  7872. var endRule = function(event) {
  7873. var currentProperties = properties.join(","),
  7874. expectedProperties = properties.sort().join(",");
  7875. if (currentProperties !== expectedProperties) {
  7876. reporter.report("Rule doesn't have all its properties in alphabetical order.", event.line, event.col, rule);
  7877. }
  7878. };
  7879. parser.addListener("startrule", startRule);
  7880. parser.addListener("startfontface", startRule);
  7881. parser.addListener("startpage", startRule);
  7882. parser.addListener("startpagemargin", startRule);
  7883. parser.addListener("startkeyframerule", startRule);
  7884. parser.addListener("startviewport", startRule);
  7885. parser.addListener("property", function(event) {
  7886. var name = event.property.text,
  7887. lowerCasePrefixLessName = name.toLowerCase().replace(/^-.*?-/, "");
  7888. properties.push(lowerCasePrefixLessName);
  7889. });
  7890. parser.addListener("endrule", endRule);
  7891. parser.addListener("endfontface", endRule);
  7892. parser.addListener("endpage", endRule);
  7893. parser.addListener("endpagemargin", endRule);
  7894. parser.addListener("endkeyframerule", endRule);
  7895. parser.addListener("endviewport", endRule);
  7896. }
  7897. });
  7898. /*
  7899. * Rule: outline: none or outline: 0 should only be used in a :focus rule
  7900. * and only if there are other properties in the same rule.
  7901. */
  7902. CSSLint.addRule({
  7903. // rule information
  7904. id: "outline-none",
  7905. name: "Disallow outline: none",
  7906. desc: "Use of outline: none or outline: 0 should be limited to :focus rules.",
  7907. url: "https://github.com/CSSLint/csslint/wiki/Disallow-outline%3Anone",
  7908. browsers: "All",
  7909. tags: ["Accessibility"],
  7910. // initialization
  7911. init: function(parser, reporter) {
  7912. "use strict";
  7913. var rule = this,
  7914. lastRule;
  7915. function startRule(event) {
  7916. if (event.selectors) {
  7917. lastRule = {
  7918. line: event.line,
  7919. col: event.col,
  7920. selectors: event.selectors,
  7921. propCount: 0,
  7922. outline: false
  7923. };
  7924. } else {
  7925. lastRule = null;
  7926. }
  7927. }
  7928. function endRule() {
  7929. if (lastRule) {
  7930. if (lastRule.outline) {
  7931. if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") === -1) {
  7932. reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule);
  7933. } else if (lastRule.propCount === 1) {
  7934. reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule);
  7935. }
  7936. }
  7937. }
  7938. }
  7939. parser.addListener("startrule", startRule);
  7940. parser.addListener("startfontface", startRule);
  7941. parser.addListener("startpage", startRule);
  7942. parser.addListener("startpagemargin", startRule);
  7943. parser.addListener("startkeyframerule", startRule);
  7944. parser.addListener("startviewport", startRule);
  7945. parser.addListener("property", function(event) {
  7946. var name = event.property.text.toLowerCase(),
  7947. value = event.value;
  7948. if (lastRule) {
  7949. lastRule.propCount++;
  7950. if (name === "outline" && (value.toString() === "none" || value.toString() === "0")) {
  7951. lastRule.outline = true;
  7952. }
  7953. }
  7954. });
  7955. parser.addListener("endrule", endRule);
  7956. parser.addListener("endfontface", endRule);
  7957. parser.addListener("endpage", endRule);
  7958. parser.addListener("endpagemargin", endRule);
  7959. parser.addListener("endkeyframerule", endRule);
  7960. parser.addListener("endviewport", endRule);
  7961. }
  7962. });
  7963. /*
  7964. * Rule: Don't use classes or IDs with elements (a.foo or a#foo).
  7965. */
  7966. CSSLint.addRule({
  7967. // rule information
  7968. id: "overqualified-elements",
  7969. name: "Disallow overqualified elements",
  7970. desc: "Don't use classes or IDs with elements (a.foo or a#foo).",
  7971. url: "https://github.com/CSSLint/csslint/wiki/Disallow-overqualified-elements",
  7972. browsers: "All",
  7973. // initialization
  7974. init: function(parser, reporter) {
  7975. "use strict";
  7976. var rule = this,
  7977. classes = {};
  7978. parser.addListener("startrule", function(event) {
  7979. var selectors = event.selectors,
  7980. selector,
  7981. part,
  7982. modifier,
  7983. i, j, k;
  7984. for (i=0; i < selectors.length; i++) {
  7985. selector = selectors[i];
  7986. for (j=0; j < selector.parts.length; j++) {
  7987. part = selector.parts[j];
  7988. if (part.type === parser.SELECTOR_PART_TYPE) {
  7989. for (k=0; k < part.modifiers.length; k++) {
  7990. modifier = part.modifiers[k];
  7991. if (part.elementName && modifier.type === "id") {
  7992. reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule);
  7993. } else if (modifier.type === "class") {
  7994. if (!classes[modifier]) {
  7995. classes[modifier] = [];
  7996. }
  7997. classes[modifier].push({
  7998. modifier: modifier,
  7999. part: part
  8000. });
  8001. }
  8002. }
  8003. }
  8004. }
  8005. }
  8006. });
  8007. parser.addListener("endstylesheet", function() {
  8008. var prop;
  8009. for (prop in classes) {
  8010. if (classes.hasOwnProperty(prop)) {
  8011. // one use means that this is overqualified
  8012. if (classes[prop].length === 1 && classes[prop][0].part.elementName) {
  8013. reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule);
  8014. }
  8015. }
  8016. }
  8017. });
  8018. }
  8019. });
  8020. /*
  8021. * Rule: Headings (h1-h6) should not be qualified (namespaced).
  8022. */
  8023. CSSLint.addRule({
  8024. // rule information
  8025. id: "qualified-headings",
  8026. name: "Disallow qualified headings",
  8027. desc: "Headings should not be qualified (namespaced).",
  8028. url: "https://github.com/CSSLint/csslint/wiki/Disallow-qualified-headings",
  8029. browsers: "All",
  8030. // initialization
  8031. init: function(parser, reporter) {
  8032. "use strict";
  8033. var rule = this;
  8034. parser.addListener("startrule", function(event) {
  8035. var selectors = event.selectors,
  8036. selector,
  8037. part,
  8038. i, j;
  8039. for (i=0; i < selectors.length; i++) {
  8040. selector = selectors[i];
  8041. for (j=0; j < selector.parts.length; j++) {
  8042. part = selector.parts[j];
  8043. if (part.type === parser.SELECTOR_PART_TYPE) {
  8044. if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0) {
  8045. reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule);
  8046. }
  8047. }
  8048. }
  8049. }
  8050. });
  8051. }
  8052. });
  8053. /*
  8054. * Rule: Selectors that look like regular expressions are slow and should be avoided.
  8055. */
  8056. CSSLint.addRule({
  8057. // rule information
  8058. id: "regex-selectors",
  8059. name: "Disallow selectors that look like regexs",
  8060. desc: "Selectors that look like regular expressions are slow and should be avoided.",
  8061. url: "https://github.com/CSSLint/csslint/wiki/Disallow-selectors-that-look-like-regular-expressions",
  8062. browsers: "All",
  8063. // initialization
  8064. init: function(parser, reporter) {
  8065. "use strict";
  8066. var rule = this;
  8067. parser.addListener("startrule", function(event) {
  8068. var selectors = event.selectors,
  8069. selector,
  8070. part,
  8071. modifier,
  8072. i, j, k;
  8073. for (i=0; i < selectors.length; i++) {
  8074. selector = selectors[i];
  8075. for (j=0; j < selector.parts.length; j++) {
  8076. part = selector.parts[j];
  8077. if (part.type === parser.SELECTOR_PART_TYPE) {
  8078. for (k=0; k < part.modifiers.length; k++) {
  8079. modifier = part.modifiers[k];
  8080. if (modifier.type === "attribute") {
  8081. if (/([~\|\^\$\*]=)/.test(modifier)) {
  8082. reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule);
  8083. }
  8084. }
  8085. }
  8086. }
  8087. }
  8088. }
  8089. });
  8090. }
  8091. });
  8092. /*
  8093. * Rule: Total number of rules should not exceed x.
  8094. */
  8095. CSSLint.addRule({
  8096. // rule information
  8097. id: "rules-count",
  8098. name: "Rules Count",
  8099. desc: "Track how many rules there are.",
  8100. browsers: "All",
  8101. // initialization
  8102. init: function(parser, reporter) {
  8103. "use strict";
  8104. var count = 0;
  8105. // count each rule
  8106. parser.addListener("startrule", function() {
  8107. count++;
  8108. });
  8109. parser.addListener("endstylesheet", function() {
  8110. reporter.stat("rule-count", count);
  8111. });
  8112. }
  8113. });
  8114. /*
  8115. * Rule: Warn people with approaching the IE 4095 limit
  8116. */
  8117. CSSLint.addRule({
  8118. // rule information
  8119. id: "selector-max-approaching",
  8120. name: "Warn when approaching the 4095 selector limit for IE",
  8121. desc: "Will warn when selector count is >= 3800 selectors.",
  8122. browsers: "IE",
  8123. // initialization
  8124. init: function(parser, reporter) {
  8125. "use strict";
  8126. var rule = this, count = 0;
  8127. parser.addListener("startrule", function(event) {
  8128. count += event.selectors.length;
  8129. });
  8130. parser.addListener("endstylesheet", function() {
  8131. if (count >= 3800) {
  8132. reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.", 0, 0, rule);
  8133. }
  8134. });
  8135. }
  8136. });
  8137. /*
  8138. * Rule: Warn people past the IE 4095 limit
  8139. */
  8140. CSSLint.addRule({
  8141. // rule information
  8142. id: "selector-max",
  8143. name: "Error when past the 4095 selector limit for IE",
  8144. desc: "Will error when selector count is > 4095.",
  8145. browsers: "IE",
  8146. // initialization
  8147. init: function(parser, reporter) {
  8148. "use strict";
  8149. var rule = this, count = 0;
  8150. parser.addListener("startrule", function(event) {
  8151. count += event.selectors.length;
  8152. });
  8153. parser.addListener("endstylesheet", function() {
  8154. if (count > 4095) {
  8155. reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.", 0, 0, rule);
  8156. }
  8157. });
  8158. }
  8159. });
  8160. /*
  8161. * Rule: Avoid new-line characters in selectors.
  8162. */
  8163. CSSLint.addRule({
  8164. // rule information
  8165. id: "selector-newline",
  8166. name: "Disallow new-line characters in selectors",
  8167. desc: "New-line characters in selectors are usually a forgotten comma and not a descendant combinator.",
  8168. browsers: "All",
  8169. // initialization
  8170. init: function(parser, reporter) {
  8171. "use strict";
  8172. var rule = this;
  8173. function startRule(event) {
  8174. var i, len, selector, p, n, pLen, part, part2, type, currentLine, nextLine,
  8175. selectors = event.selectors;
  8176. for (i = 0, len = selectors.length; i < len; i++) {
  8177. selector = selectors[i];
  8178. for (p = 0, pLen = selector.parts.length; p < pLen; p++) {
  8179. for (n = p + 1; n < pLen; n++) {
  8180. part = selector.parts[p];
  8181. part2 = selector.parts[n];
  8182. type = part.type;
  8183. currentLine = part.line;
  8184. nextLine = part2.line;
  8185. if (type === "descendant" && nextLine > currentLine) {
  8186. reporter.report("newline character found in selector (forgot a comma?)", currentLine, selectors[i].parts[0].col, rule);
  8187. }
  8188. }
  8189. }
  8190. }
  8191. }
  8192. parser.addListener("startrule", startRule);
  8193. }
  8194. });
  8195. /*
  8196. * Rule: Use shorthand properties where possible.
  8197. *
  8198. */
  8199. CSSLint.addRule({
  8200. // rule information
  8201. id: "shorthand",
  8202. name: "Require shorthand properties",
  8203. desc: "Use shorthand properties where possible.",
  8204. url: "https://github.com/CSSLint/csslint/wiki/Require-shorthand-properties",
  8205. browsers: "All",
  8206. // initialization
  8207. init: function(parser, reporter) {
  8208. "use strict";
  8209. var rule = this,
  8210. prop, i, len,
  8211. propertiesToCheck = {},
  8212. properties,
  8213. mapping = {
  8214. "margin": [
  8215. "margin-top",
  8216. "margin-bottom",
  8217. "margin-left",
  8218. "margin-right"
  8219. ],
  8220. "padding": [
  8221. "padding-top",
  8222. "padding-bottom",
  8223. "padding-left",
  8224. "padding-right"
  8225. ]
  8226. };
  8227. // initialize propertiesToCheck
  8228. for (prop in mapping) {
  8229. if (mapping.hasOwnProperty(prop)) {
  8230. for (i=0, len=mapping[prop].length; i < len; i++) {
  8231. propertiesToCheck[mapping[prop][i]] = prop;
  8232. }
  8233. }
  8234. }
  8235. function startRule() {
  8236. properties = {};
  8237. }
  8238. // event handler for end of rules
  8239. function endRule(event) {
  8240. var prop, i, len, total;
  8241. // check which properties this rule has
  8242. for (prop in mapping) {
  8243. if (mapping.hasOwnProperty(prop)) {
  8244. total=0;
  8245. for (i=0, len=mapping[prop].length; i < len; i++) {
  8246. total += properties[mapping[prop][i]] ? 1 : 0;
  8247. }
  8248. if (total === mapping[prop].length) {
  8249. reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule);
  8250. }
  8251. }
  8252. }
  8253. }
  8254. parser.addListener("startrule", startRule);
  8255. parser.addListener("startfontface", startRule);
  8256. // check for use of "font-size"
  8257. parser.addListener("property", function(event) {
  8258. var name = event.property.toString().toLowerCase();
  8259. if (propertiesToCheck[name]) {
  8260. properties[name] = 1;
  8261. }
  8262. });
  8263. parser.addListener("endrule", endRule);
  8264. parser.addListener("endfontface", endRule);
  8265. }
  8266. });
  8267. /*
  8268. * Rule: Don't use properties with a star prefix.
  8269. *
  8270. */
  8271. CSSLint.addRule({
  8272. // rule information
  8273. id: "star-property-hack",
  8274. name: "Disallow properties with a star prefix",
  8275. desc: "Checks for the star property hack (targets IE6/7)",
  8276. url: "https://github.com/CSSLint/csslint/wiki/Disallow-star-hack",
  8277. browsers: "All",
  8278. // initialization
  8279. init: function(parser, reporter) {
  8280. "use strict";
  8281. var rule = this;
  8282. // check if property name starts with "*"
  8283. parser.addListener("property", function(event) {
  8284. var property = event.property;
  8285. if (property.hack === "*") {
  8286. reporter.report("Property with star prefix found.", event.property.line, event.property.col, rule);
  8287. }
  8288. });
  8289. }
  8290. });
  8291. /*
  8292. * Rule: Don't use text-indent for image replacement if you need to support rtl.
  8293. *
  8294. */
  8295. CSSLint.addRule({
  8296. // rule information
  8297. id: "text-indent",
  8298. name: "Disallow negative text-indent",
  8299. desc: "Checks for text indent less than -99px",
  8300. url: "https://github.com/CSSLint/csslint/wiki/Disallow-negative-text-indent",
  8301. browsers: "All",
  8302. // initialization
  8303. init: function(parser, reporter) {
  8304. "use strict";
  8305. var rule = this,
  8306. textIndent,
  8307. direction;
  8308. function startRule() {
  8309. textIndent = false;
  8310. direction = "inherit";
  8311. }
  8312. // event handler for end of rules
  8313. function endRule() {
  8314. if (textIndent && direction !== "ltr") {
  8315. reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule);
  8316. }
  8317. }
  8318. parser.addListener("startrule", startRule);
  8319. parser.addListener("startfontface", startRule);
  8320. // check for use of "font-size"
  8321. parser.addListener("property", function(event) {
  8322. var name = event.property.toString().toLowerCase(),
  8323. value = event.value;
  8324. if (name === "text-indent" && value.parts[0].value < -99) {
  8325. textIndent = event.property;
  8326. } else if (name === "direction" && value.toString() === "ltr") {
  8327. direction = "ltr";
  8328. }
  8329. });
  8330. parser.addListener("endrule", endRule);
  8331. parser.addListener("endfontface", endRule);
  8332. }
  8333. });
  8334. /*
  8335. * Rule: Don't use properties with a underscore prefix.
  8336. *
  8337. */
  8338. CSSLint.addRule({
  8339. // rule information
  8340. id: "underscore-property-hack",
  8341. name: "Disallow properties with an underscore prefix",
  8342. desc: "Checks for the underscore property hack (targets IE6)",
  8343. url: "https://github.com/CSSLint/csslint/wiki/Disallow-underscore-hack",
  8344. browsers: "All",
  8345. // initialization
  8346. init: function(parser, reporter) {
  8347. "use strict";
  8348. var rule = this;
  8349. // check if property name starts with "_"
  8350. parser.addListener("property", function(event) {
  8351. var property = event.property;
  8352. if (property.hack === "_") {
  8353. reporter.report("Property with underscore prefix found.", event.property.line, event.property.col, rule);
  8354. }
  8355. });
  8356. }
  8357. });
  8358. /*
  8359. * Rule: Headings (h1-h6) should be defined only once.
  8360. */
  8361. CSSLint.addRule({
  8362. // rule information
  8363. id: "unique-headings",
  8364. name: "Headings should only be defined once",
  8365. desc: "Headings should be defined only once.",
  8366. url: "https://github.com/CSSLint/csslint/wiki/Headings-should-only-be-defined-once",
  8367. browsers: "All",
  8368. // initialization
  8369. init: function(parser, reporter) {
  8370. "use strict";
  8371. var rule = this;
  8372. var headings = {
  8373. h1: 0,
  8374. h2: 0,
  8375. h3: 0,
  8376. h4: 0,
  8377. h5: 0,
  8378. h6: 0
  8379. };
  8380. parser.addListener("startrule", function(event) {
  8381. var selectors = event.selectors,
  8382. selector,
  8383. part,
  8384. pseudo,
  8385. i, j;
  8386. for (i=0; i < selectors.length; i++) {
  8387. selector = selectors[i];
  8388. part = selector.parts[selector.parts.length-1];
  8389. if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())) {
  8390. for (j=0; j < part.modifiers.length; j++) {
  8391. if (part.modifiers[j].type === "pseudo") {
  8392. pseudo = true;
  8393. break;
  8394. }
  8395. }
  8396. if (!pseudo) {
  8397. headings[RegExp.$1]++;
  8398. if (headings[RegExp.$1] > 1) {
  8399. reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule);
  8400. }
  8401. }
  8402. }
  8403. }
  8404. });
  8405. parser.addListener("endstylesheet", function() {
  8406. var prop,
  8407. messages = [];
  8408. for (prop in headings) {
  8409. if (headings.hasOwnProperty(prop)) {
  8410. if (headings[prop] > 1) {
  8411. messages.push(headings[prop] + " " + prop + "s");
  8412. }
  8413. }
  8414. }
  8415. if (messages.length) {
  8416. reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule);
  8417. }
  8418. });
  8419. }
  8420. });
  8421. /*
  8422. * Rule: Don't use universal selector because it's slow.
  8423. */
  8424. CSSLint.addRule({
  8425. // rule information
  8426. id: "universal-selector",
  8427. name: "Disallow universal selector",
  8428. desc: "The universal selector (*) is known to be slow.",
  8429. url: "https://github.com/CSSLint/csslint/wiki/Disallow-universal-selector",
  8430. browsers: "All",
  8431. // initialization
  8432. init: function(parser, reporter) {
  8433. "use strict";
  8434. var rule = this;
  8435. parser.addListener("startrule", function(event) {
  8436. var selectors = event.selectors,
  8437. selector,
  8438. part,
  8439. i;
  8440. for (i=0; i < selectors.length; i++) {
  8441. selector = selectors[i];
  8442. part = selector.parts[selector.parts.length-1];
  8443. if (part.elementName === "*") {
  8444. reporter.report(rule.desc, part.line, part.col, rule);
  8445. }
  8446. }
  8447. });
  8448. }
  8449. });
  8450. /*
  8451. * Rule: Don't use unqualified attribute selectors because they're just like universal selectors.
  8452. */
  8453. CSSLint.addRule({
  8454. // rule information
  8455. id: "unqualified-attributes",
  8456. name: "Disallow unqualified attribute selectors",
  8457. desc: "Unqualified attribute selectors are known to be slow.",
  8458. url: "https://github.com/CSSLint/csslint/wiki/Disallow-unqualified-attribute-selectors",
  8459. browsers: "All",
  8460. // initialization
  8461. init: function(parser, reporter) {
  8462. "use strict";
  8463. var rule = this;
  8464. parser.addListener("startrule", function(event) {
  8465. var selectors = event.selectors,
  8466. selectorContainsClassOrId = false,
  8467. selector,
  8468. part,
  8469. modifier,
  8470. i, k;
  8471. for (i=0; i < selectors.length; i++) {
  8472. selector = selectors[i];
  8473. part = selector.parts[selector.parts.length-1];
  8474. if (part.type === parser.SELECTOR_PART_TYPE) {
  8475. for (k=0; k < part.modifiers.length; k++) {
  8476. modifier = part.modifiers[k];
  8477. if (modifier.type === "class" || modifier.type === "id") {
  8478. selectorContainsClassOrId = true;
  8479. break;
  8480. }
  8481. }
  8482. if (!selectorContainsClassOrId) {
  8483. for (k=0; k < part.modifiers.length; k++) {
  8484. modifier = part.modifiers[k];
  8485. if (modifier.type === "attribute" && (!part.elementName || part.elementName === "*")) {
  8486. reporter.report(rule.desc, part.line, part.col, rule);
  8487. }
  8488. }
  8489. }
  8490. }
  8491. }
  8492. });
  8493. }
  8494. });
  8495. /*
  8496. * Rule: When using a vendor-prefixed property, make sure to
  8497. * include the standard one.
  8498. */
  8499. CSSLint.addRule({
  8500. // rule information
  8501. id: "vendor-prefix",
  8502. name: "Require standard property with vendor prefix",
  8503. desc: "When using a vendor-prefixed property, make sure to include the standard one.",
  8504. url: "https://github.com/CSSLint/csslint/wiki/Require-standard-property-with-vendor-prefix",
  8505. browsers: "All",
  8506. // initialization
  8507. init: function(parser, reporter) {
  8508. "use strict";
  8509. var rule = this,
  8510. properties,
  8511. num,
  8512. propertiesToCheck = {
  8513. "-webkit-border-radius": "border-radius",
  8514. "-webkit-border-top-left-radius": "border-top-left-radius",
  8515. "-webkit-border-top-right-radius": "border-top-right-radius",
  8516. "-webkit-border-bottom-left-radius": "border-bottom-left-radius",
  8517. "-webkit-border-bottom-right-radius": "border-bottom-right-radius",
  8518. "-o-border-radius": "border-radius",
  8519. "-o-border-top-left-radius": "border-top-left-radius",
  8520. "-o-border-top-right-radius": "border-top-right-radius",
  8521. "-o-border-bottom-left-radius": "border-bottom-left-radius",
  8522. "-o-border-bottom-right-radius": "border-bottom-right-radius",
  8523. "-moz-border-radius": "border-radius",
  8524. "-moz-border-radius-topleft": "border-top-left-radius",
  8525. "-moz-border-radius-topright": "border-top-right-radius",
  8526. "-moz-border-radius-bottomleft": "border-bottom-left-radius",
  8527. "-moz-border-radius-bottomright": "border-bottom-right-radius",
  8528. "-moz-column-count": "column-count",
  8529. "-webkit-column-count": "column-count",
  8530. "-moz-column-gap": "column-gap",
  8531. "-webkit-column-gap": "column-gap",
  8532. "-moz-column-rule": "column-rule",
  8533. "-webkit-column-rule": "column-rule",
  8534. "-moz-column-rule-style": "column-rule-style",
  8535. "-webkit-column-rule-style": "column-rule-style",
  8536. "-moz-column-rule-color": "column-rule-color",
  8537. "-webkit-column-rule-color": "column-rule-color",
  8538. "-moz-column-rule-width": "column-rule-width",
  8539. "-webkit-column-rule-width": "column-rule-width",
  8540. "-moz-column-width": "column-width",
  8541. "-webkit-column-width": "column-width",
  8542. "-webkit-column-span": "column-span",
  8543. "-webkit-columns": "columns",
  8544. "-moz-box-shadow": "box-shadow",
  8545. "-webkit-box-shadow": "box-shadow",
  8546. "-moz-transform": "transform",
  8547. "-webkit-transform": "transform",
  8548. "-o-transform": "transform",
  8549. "-ms-transform": "transform",
  8550. "-moz-transform-origin": "transform-origin",
  8551. "-webkit-transform-origin": "transform-origin",
  8552. "-o-transform-origin": "transform-origin",
  8553. "-ms-transform-origin": "transform-origin",
  8554. "-moz-box-sizing": "box-sizing",
  8555. "-webkit-box-sizing": "box-sizing"
  8556. };
  8557. // event handler for beginning of rules
  8558. function startRule() {
  8559. properties = {};
  8560. num = 1;
  8561. }
  8562. // event handler for end of rules
  8563. function endRule() {
  8564. var prop,
  8565. i,
  8566. len,
  8567. needed,
  8568. actual,
  8569. needsStandard = [];
  8570. for (prop in properties) {
  8571. if (propertiesToCheck[prop]) {
  8572. needsStandard.push({
  8573. actual: prop,
  8574. needed: propertiesToCheck[prop]
  8575. });
  8576. }
  8577. }
  8578. for (i=0, len=needsStandard.length; i < len; i++) {
  8579. needed = needsStandard[i].needed;
  8580. actual = needsStandard[i].actual;
  8581. if (!properties[needed]) {
  8582. reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
  8583. } else {
  8584. // make sure standard property is last
  8585. if (properties[needed][0].pos < properties[actual][0].pos) {
  8586. reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
  8587. }
  8588. }
  8589. }
  8590. }
  8591. parser.addListener("startrule", startRule);
  8592. parser.addListener("startfontface", startRule);
  8593. parser.addListener("startpage", startRule);
  8594. parser.addListener("startpagemargin", startRule);
  8595. parser.addListener("startkeyframerule", startRule);
  8596. parser.addListener("startviewport", startRule);
  8597. parser.addListener("property", function(event) {
  8598. var name = event.property.text.toLowerCase();
  8599. if (!properties[name]) {
  8600. properties[name] = [];
  8601. }
  8602. properties[name].push({
  8603. name: event.property,
  8604. value: event.value,
  8605. pos: num++
  8606. });
  8607. });
  8608. parser.addListener("endrule", endRule);
  8609. parser.addListener("endfontface", endRule);
  8610. parser.addListener("endpage", endRule);
  8611. parser.addListener("endpagemargin", endRule);
  8612. parser.addListener("endkeyframerule", endRule);
  8613. parser.addListener("endviewport", endRule);
  8614. }
  8615. });
  8616. /*
  8617. * Rule: You don't need to specify units when a value is 0.
  8618. */
  8619. CSSLint.addRule({
  8620. // rule information
  8621. id: "zero-units",
  8622. name: "Disallow units for 0 values",
  8623. desc: "You don't need to specify units when a value is 0.",
  8624. url: "https://github.com/CSSLint/csslint/wiki/Disallow-units-for-zero-values",
  8625. browsers: "All",
  8626. // initialization
  8627. init: function(parser, reporter) {
  8628. "use strict";
  8629. var rule = this;
  8630. // count how many times "float" is used
  8631. parser.addListener("property", function(event) {
  8632. var parts = event.value.parts,
  8633. i = 0,
  8634. len = parts.length;
  8635. while (i < len) {
  8636. if ((parts[i].units || parts[i].type === "percentage") && parts[i].value === 0 && parts[i].type !== "time") {
  8637. reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule);
  8638. }
  8639. i++;
  8640. }
  8641. });
  8642. }
  8643. });
  8644. (function() {
  8645. "use strict";
  8646. /**
  8647. * Replace special characters before write to output.
  8648. *
  8649. * Rules:
  8650. * - single quotes is the escape sequence for double-quotes
  8651. * - &amp; is the escape sequence for &
  8652. * - &lt; is the escape sequence for <
  8653. * - &gt; is the escape sequence for >
  8654. *
  8655. * @param {String} message to escape
  8656. * @return escaped message as {String}
  8657. */
  8658. var xmlEscape = function(str) {
  8659. if (!str || str.constructor !== String) {
  8660. return "";
  8661. }
  8662. return str.replace(/["&><]/g, function(match) {
  8663. switch (match) {
  8664. case "\"":
  8665. return "&quot;";
  8666. case "&":
  8667. return "&amp;";
  8668. case "<":
  8669. return "&lt;";
  8670. case ">":
  8671. return "&gt;";
  8672. }
  8673. });
  8674. };
  8675. CSSLint.addFormatter({
  8676. // format information
  8677. id: "checkstyle-xml",
  8678. name: "Checkstyle XML format",
  8679. /**
  8680. * Return opening root XML tag.
  8681. * @return {String} to prepend before all results
  8682. */
  8683. startFormat: function() {
  8684. return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>";
  8685. },
  8686. /**
  8687. * Return closing root XML tag.
  8688. * @return {String} to append after all results
  8689. */
  8690. endFormat: function() {
  8691. return "</checkstyle>";
  8692. },
  8693. /**
  8694. * Returns message when there is a file read error.
  8695. * @param {String} filename The name of the file that caused the error.
  8696. * @param {String} message The error message
  8697. * @return {String} The error message.
  8698. */
  8699. readError: function(filename, message) {
  8700. return "<file name=\"" + xmlEscape(filename) + "\"><error line=\"0\" column=\"0\" severty=\"error\" message=\"" + xmlEscape(message) + "\"></error></file>";
  8701. },
  8702. /**
  8703. * Given CSS Lint results for a file, return output for this format.
  8704. * @param results {Object} with error and warning messages
  8705. * @param filename {String} relative file path
  8706. * @param options {Object} (UNUSED for now) specifies special handling of output
  8707. * @return {String} output for results
  8708. */
  8709. formatResults: function(results, filename/*, options*/) {
  8710. var messages = results.messages,
  8711. output = [];
  8712. /**
  8713. * Generate a source string for a rule.
  8714. * Checkstyle source strings usually resemble Java class names e.g
  8715. * net.csslint.SomeRuleName
  8716. * @param {Object} rule
  8717. * @return rule source as {String}
  8718. */
  8719. var generateSource = function(rule) {
  8720. if (!rule || !("name" in rule)) {
  8721. return "";
  8722. }
  8723. return "net.csslint." + rule.name.replace(/\s/g, "");
  8724. };
  8725. if (messages.length > 0) {
  8726. output.push("<file name=\""+filename+"\">");
  8727. CSSLint.Util.forEach(messages, function (message) {
  8728. // ignore rollups for now
  8729. if (!message.rollup) {
  8730. output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" +
  8731. " message=\"" + xmlEscape(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>");
  8732. }
  8733. });
  8734. output.push("</file>");
  8735. }
  8736. return output.join("");
  8737. }
  8738. });
  8739. }());
  8740. CSSLint.addFormatter({
  8741. // format information
  8742. id: "compact",
  8743. name: "Compact, 'porcelain' format",
  8744. /**
  8745. * Return content to be printed before all file results.
  8746. * @return {String} to prepend before all results
  8747. */
  8748. startFormat: function() {
  8749. "use strict";
  8750. return "";
  8751. },
  8752. /**
  8753. * Return content to be printed after all file results.
  8754. * @return {String} to append after all results
  8755. */
  8756. endFormat: function() {
  8757. "use strict";
  8758. return "";
  8759. },
  8760. /**
  8761. * Given CSS Lint results for a file, return output for this format.
  8762. * @param results {Object} with error and warning messages
  8763. * @param filename {String} relative file path
  8764. * @param options {Object} (Optional) specifies special handling of output
  8765. * @return {String} output for results
  8766. */
  8767. formatResults: function(results, filename, options) {
  8768. "use strict";
  8769. var messages = results.messages,
  8770. output = "";
  8771. options = options || {};
  8772. /**
  8773. * Capitalize and return given string.
  8774. * @param str {String} to capitalize
  8775. * @return {String} capitalized
  8776. */
  8777. var capitalize = function(str) {
  8778. return str.charAt(0).toUpperCase() + str.slice(1);
  8779. };
  8780. if (messages.length === 0) {
  8781. return options.quiet ? "" : filename + ": Lint Free!";
  8782. }
  8783. CSSLint.Util.forEach(messages, function(message) {
  8784. if (message.rollup) {
  8785. output += filename + ": " + capitalize(message.type) + " - " + message.message + " (" + message.rule.id + ")\n";
  8786. } else {
  8787. output += filename + ": line " + message.line +
  8788. ", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + " (" + message.rule.id + ")\n";
  8789. }
  8790. });
  8791. return output;
  8792. }
  8793. });
  8794. CSSLint.addFormatter({
  8795. // format information
  8796. id: "csslint-xml",
  8797. name: "CSSLint XML format",
  8798. /**
  8799. * Return opening root XML tag.
  8800. * @return {String} to prepend before all results
  8801. */
  8802. startFormat: function() {
  8803. "use strict";
  8804. return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>";
  8805. },
  8806. /**
  8807. * Return closing root XML tag.
  8808. * @return {String} to append after all results
  8809. */
  8810. endFormat: function() {
  8811. "use strict";
  8812. return "</csslint>";
  8813. },
  8814. /**
  8815. * Given CSS Lint results for a file, return output for this format.
  8816. * @param results {Object} with error and warning messages
  8817. * @param filename {String} relative file path
  8818. * @param options {Object} (UNUSED for now) specifies special handling of output
  8819. * @return {String} output for results
  8820. */
  8821. formatResults: function(results, filename/*, options*/) {
  8822. "use strict";
  8823. var messages = results.messages,
  8824. output = [];
  8825. /**
  8826. * Replace special characters before write to output.
  8827. *
  8828. * Rules:
  8829. * - single quotes is the escape sequence for double-quotes
  8830. * - &amp; is the escape sequence for &
  8831. * - &lt; is the escape sequence for <
  8832. * - &gt; is the escape sequence for >
  8833. *
  8834. * @param {String} message to escape
  8835. * @return escaped message as {String}
  8836. */
  8837. var escapeSpecialCharacters = function(str) {
  8838. if (!str || str.constructor !== String) {
  8839. return "";
  8840. }
  8841. return str.replace(/"/g, "'").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  8842. };
  8843. if (messages.length > 0) {
  8844. output.push("<file name=\""+filename+"\">");
  8845. CSSLint.Util.forEach(messages, function (message) {
  8846. if (message.rollup) {
  8847. output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
  8848. } else {
  8849. output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
  8850. " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
  8851. }
  8852. });
  8853. output.push("</file>");
  8854. }
  8855. return output.join("");
  8856. }
  8857. });
  8858. /* globals JSON: true */
  8859. CSSLint.addFormatter({
  8860. // format information
  8861. id: "json",
  8862. name: "JSON",
  8863. /**
  8864. * Return content to be printed before all file results.
  8865. * @return {String} to prepend before all results
  8866. */
  8867. startFormat: function() {
  8868. "use strict";
  8869. this.json = [];
  8870. return "";
  8871. },
  8872. /**
  8873. * Return content to be printed after all file results.
  8874. * @return {String} to append after all results
  8875. */
  8876. endFormat: function() {
  8877. "use strict";
  8878. var ret = "";
  8879. if (this.json.length > 0) {
  8880. if (this.json.length === 1) {
  8881. ret = JSON.stringify(this.json[0]);
  8882. } else {
  8883. ret = JSON.stringify(this.json);
  8884. }
  8885. }
  8886. return ret;
  8887. },
  8888. /**
  8889. * Given CSS Lint results for a file, return output for this format.
  8890. * @param results {Object} with error and warning messages
  8891. * @param filename {String} relative file path (Unused)
  8892. * @return {String} output for results
  8893. */
  8894. formatResults: function(results, filename, options) {
  8895. "use strict";
  8896. if (results.messages.length > 0 || !options.quiet) {
  8897. this.json.push({
  8898. filename: filename,
  8899. messages: results.messages,
  8900. stats: results.stats
  8901. });
  8902. }
  8903. return "";
  8904. }
  8905. });
  8906. CSSLint.addFormatter({
  8907. // format information
  8908. id: "junit-xml",
  8909. name: "JUNIT XML format",
  8910. /**
  8911. * Return opening root XML tag.
  8912. * @return {String} to prepend before all results
  8913. */
  8914. startFormat: function() {
  8915. "use strict";
  8916. return "<?xml version=\"1.0\" encoding=\"utf-8\"?><testsuites>";
  8917. },
  8918. /**
  8919. * Return closing root XML tag.
  8920. * @return {String} to append after all results
  8921. */
  8922. endFormat: function() {
  8923. "use strict";
  8924. return "</testsuites>";
  8925. },
  8926. /**
  8927. * Given CSS Lint results for a file, return output for this format.
  8928. * @param results {Object} with error and warning messages
  8929. * @param filename {String} relative file path
  8930. * @param options {Object} (UNUSED for now) specifies special handling of output
  8931. * @return {String} output for results
  8932. */
  8933. formatResults: function(results, filename/*, options*/) {
  8934. "use strict";
  8935. var messages = results.messages,
  8936. output = [],
  8937. tests = {
  8938. "error": 0,
  8939. "failure": 0
  8940. };
  8941. /**
  8942. * Generate a source string for a rule.
  8943. * JUNIT source strings usually resemble Java class names e.g
  8944. * net.csslint.SomeRuleName
  8945. * @param {Object} rule
  8946. * @return rule source as {String}
  8947. */
  8948. var generateSource = function(rule) {
  8949. if (!rule || !("name" in rule)) {
  8950. return "";
  8951. }
  8952. return "net.csslint." + rule.name.replace(/\s/g, "");
  8953. };
  8954. /**
  8955. * Replace special characters before write to output.
  8956. *
  8957. * Rules:
  8958. * - single quotes is the escape sequence for double-quotes
  8959. * - &lt; is the escape sequence for <
  8960. * - &gt; is the escape sequence for >
  8961. *
  8962. * @param {String} message to escape
  8963. * @return escaped message as {String}
  8964. */
  8965. var escapeSpecialCharacters = function(str) {
  8966. if (!str || str.constructor !== String) {
  8967. return "";
  8968. }
  8969. return str.replace(/"/g, "'").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  8970. };
  8971. if (messages.length > 0) {
  8972. messages.forEach(function (message) {
  8973. // since junit has no warning class
  8974. // all issues as errors
  8975. var type = message.type === "warning" ? "error" : message.type;
  8976. // ignore rollups for now
  8977. if (!message.rollup) {
  8978. // build the test case separately, once joined
  8979. // we'll add it to a custom array filtered by type
  8980. output.push("<testcase time=\"0\" name=\"" + generateSource(message.rule) + "\">");
  8981. output.push("<" + type + " message=\"" + escapeSpecialCharacters(message.message) + "\"><![CDATA[" + message.line + ":" + message.col + ":" + escapeSpecialCharacters(message.evidence) + "]]></" + type + ">");
  8982. output.push("</testcase>");
  8983. tests[type] += 1;
  8984. }
  8985. });
  8986. output.unshift("<testsuite time=\"0\" tests=\"" + messages.length + "\" skipped=\"0\" errors=\"" + tests.error + "\" failures=\"" + tests.failure + "\" package=\"net.csslint\" name=\"" + filename + "\">");
  8987. output.push("</testsuite>");
  8988. }
  8989. return output.join("");
  8990. }
  8991. });
  8992. CSSLint.addFormatter({
  8993. // format information
  8994. id: "lint-xml",
  8995. name: "Lint XML format",
  8996. /**
  8997. * Return opening root XML tag.
  8998. * @return {String} to prepend before all results
  8999. */
  9000. startFormat: function() {
  9001. "use strict";
  9002. return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>";
  9003. },
  9004. /**
  9005. * Return closing root XML tag.
  9006. * @return {String} to append after all results
  9007. */
  9008. endFormat: function() {
  9009. "use strict";
  9010. return "</lint>";
  9011. },
  9012. /**
  9013. * Given CSS Lint results for a file, return output for this format.
  9014. * @param results {Object} with error and warning messages
  9015. * @param filename {String} relative file path
  9016. * @param options {Object} (UNUSED for now) specifies special handling of output
  9017. * @return {String} output for results
  9018. */
  9019. formatResults: function(results, filename/*, options*/) {
  9020. "use strict";
  9021. var messages = results.messages,
  9022. output = [];
  9023. /**
  9024. * Replace special characters before write to output.
  9025. *
  9026. * Rules:
  9027. * - single quotes is the escape sequence for double-quotes
  9028. * - &amp; is the escape sequence for &
  9029. * - &lt; is the escape sequence for <
  9030. * - &gt; is the escape sequence for >
  9031. *
  9032. * @param {String} message to escape
  9033. * @return escaped message as {String}
  9034. */
  9035. var escapeSpecialCharacters = function(str) {
  9036. if (!str || str.constructor !== String) {
  9037. return "";
  9038. }
  9039. return str.replace(/"/g, "'").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  9040. };
  9041. if (messages.length > 0) {
  9042. output.push("<file name=\""+filename+"\">");
  9043. CSSLint.Util.forEach(messages, function (message) {
  9044. if (message.rollup) {
  9045. output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
  9046. } else {
  9047. var rule = "";
  9048. if (message.rule && message.rule.id) {
  9049. rule = "rule=\"" + escapeSpecialCharacters(message.rule.id) + "\" ";
  9050. }
  9051. output.push("<issue " + rule + "line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
  9052. " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
  9053. }
  9054. });
  9055. output.push("</file>");
  9056. }
  9057. return output.join("");
  9058. }
  9059. });
  9060. CSSLint.addFormatter({
  9061. // format information
  9062. id: "text",
  9063. name: "Plain Text",
  9064. /**
  9065. * Return content to be printed before all file results.
  9066. * @return {String} to prepend before all results
  9067. */
  9068. startFormat: function() {
  9069. "use strict";
  9070. return "";
  9071. },
  9072. /**
  9073. * Return content to be printed after all file results.
  9074. * @return {String} to append after all results
  9075. */
  9076. endFormat: function() {
  9077. "use strict";
  9078. return "";
  9079. },
  9080. /**
  9081. * Given CSS Lint results for a file, return output for this format.
  9082. * @param results {Object} with error and warning messages
  9083. * @param filename {String} relative file path
  9084. * @param options {Object} (Optional) specifies special handling of output
  9085. * @return {String} output for results
  9086. */
  9087. formatResults: function(results, filename, options) {
  9088. "use strict";
  9089. var messages = results.messages,
  9090. output = "";
  9091. options = options || {};
  9092. if (messages.length === 0) {
  9093. return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + ".";
  9094. }
  9095. output = "\n\ncsslint: There ";
  9096. if (messages.length === 1) {
  9097. output += "is 1 problem";
  9098. } else {
  9099. output += "are " + messages.length + " problems";
  9100. }
  9101. output += " in " + filename + ".";
  9102. var pos = filename.lastIndexOf("/"),
  9103. shortFilename = filename;
  9104. if (pos === -1) {
  9105. pos = filename.lastIndexOf("\\");
  9106. }
  9107. if (pos > -1) {
  9108. shortFilename = filename.substring(pos+1);
  9109. }
  9110. CSSLint.Util.forEach(messages, function (message, i) {
  9111. output = output + "\n\n" + shortFilename;
  9112. if (message.rollup) {
  9113. output += "\n" + (i+1) + ": " + message.type;
  9114. output += "\n" + message.message;
  9115. } else {
  9116. output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col;
  9117. output += "\n" + message.message;
  9118. output += "\n" + message.evidence;
  9119. }
  9120. });
  9121. return output;
  9122. }
  9123. });
  9124. return CSSLint;
  9125. })();