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.

index.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const cssom = require('cssom');
  2. /**
  3. * Returns an array of the selectors.
  4. *
  5. * @license Sizzle CSS Selector Engine - MIT
  6. * @param {String} selectorText from cssom
  7. * @api public
  8. */
  9. function extract(selectorText) {
  10. let attr = 0;
  11. const sels = [];
  12. let sel = '';
  13. let i;
  14. let c;
  15. const l = selectorText.length;
  16. for (i = 0; i < l; i++) {
  17. c = selectorText.charAt(i);
  18. if (attr) {
  19. if (c === '[' || c === '(') {
  20. attr--;
  21. }
  22. sel += c;
  23. } else if (c === ',') {
  24. sels.push(sel);
  25. sel = '';
  26. } else {
  27. if (c === '[' || c === '(') {
  28. attr++;
  29. }
  30. if (sel.length || (c !== ',' && c !== '\n' && c !== ' ')) {
  31. sel += c;
  32. }
  33. }
  34. }
  35. if (sel.length) {
  36. sels.push(sel);
  37. }
  38. return sels;
  39. }
  40. /**
  41. * Returns a parse tree for a CSS source.
  42. * If it encounters multiple selectors separated by a comma, it splits the
  43. * tree.
  44. *
  45. * @param {String} css source
  46. * @api public
  47. */
  48. module.exports = css => {
  49. const rules = cssom.parse(css).cssRules || [];
  50. const ret = [];
  51. let i;
  52. const l = rules.length;
  53. let rule;
  54. let selectors;
  55. let ii;
  56. let ll;
  57. for (i = 0; i < l; i++) {
  58. if (rules[i].selectorText) { // media queries don't have selectorText
  59. rule = rules[i];
  60. selectors = extract(rule.selectorText);
  61. ll = selectors.length;
  62. for (ii = 0; ii < ll; ii++) {
  63. ret.push([ selectors[ii], rule.style ]);
  64. }
  65. }
  66. }
  67. return ret;
  68. };