css-minifier.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global CSSRule, cssWhat, parseCss, RulesMatcher */
  21. this.cssMinifier = this.stylesMinifier || (() => {
  22. const SEPARATOR_TYPES = ["descendant", "child", "sibling", "adjacent"];
  23. const REMOVED_PSEUDO_CLASSES = ["focus", "focus-within", "hover", "link", "visited", "active"];
  24. const REMOVED_PSEUDO_ELEMENTS = ["after", "before", "first-line", "first-letter"];
  25. return {
  26. process: doc => {
  27. const rulesMatcher = new RulesMatcher(doc);
  28. const mediaAllInfo = rulesMatcher.getAllMatchedRules();
  29. const stats = { processed: 0, discarded: 0 };
  30. doc.querySelectorAll("style").forEach(styleElement => {
  31. if (styleElement.sheet) {
  32. processRules(doc, styleElement.sheet.cssRules, mediaAllInfo);
  33. styleElement.textContent = serializeRules(styleElement.sheet.cssRules);
  34. stats.discarded -= styleElement.sheet.cssRules.length;
  35. }
  36. });
  37. doc.querySelectorAll("[style]").forEach(element => {
  38. processStyle(doc, element.style, mediaAllInfo);
  39. });
  40. return stats;
  41. }
  42. };
  43. function processRules(doc, cssRules, mediaInfo) {
  44. Array.from(cssRules).forEach(cssRule => {
  45. if (cssRule.type == CSSRule.MEDIA_RULE) {
  46. processRules(doc, cssRule.cssRules, mediaInfo.medias.get(cssRule.media));
  47. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  48. const ruleInfo = mediaInfo.rules.get(cssRule);
  49. if (ruleInfo) {
  50. const stylesInfo = parseCss.parseAListOfDeclarations(cssRule.style.cssText);
  51. const unusedStyles = stylesInfo.filter(style => !ruleInfo.style.get(style.name));
  52. if (unusedStyles.length) {
  53. unusedStyles.forEach(style => cssRule.style.removeProperty(style.name));
  54. }
  55. if (ruleInfo.matchedSelectors.size < ruleInfo.selectorsText.length) {
  56. cssRule.selectorText = ruleInfo.selectorsText.filter(selector => ruleInfo.matchedSelectors.has(selector)).join(",");
  57. }
  58. } else {
  59. if (!testFilterSelector(cssRule.selectorText) || !doc.querySelector(getFilteredSelector(cssRule.selectorText))) {
  60. const parent = cssRule.parentRule || cssRule.parentStyleSheet;
  61. let indexRule = 0;
  62. while (cssRule != parent.cssRules[indexRule] && indexRule < parent.cssRules.length) {
  63. indexRule++;
  64. }
  65. if (cssRule == parent.cssRules[indexRule]) {
  66. parent.deleteRule(indexRule);
  67. }
  68. }
  69. }
  70. }
  71. });
  72. }
  73. function processStyle(doc, cssStyle, mediaInfo) {
  74. const styleInfo = mediaInfo.styles.get(cssStyle);
  75. if (styleInfo) {
  76. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  77. const unusedStyles = stylesInfo.filter(style => !styleInfo.style.get(style.name));
  78. if (unusedStyles.length) {
  79. unusedStyles.forEach(style => cssStyle.removeProperty(style.name));
  80. }
  81. }
  82. }
  83. function serializeRules(rules) {
  84. let sheetContent = "";
  85. Array.from(rules).forEach(rule => {
  86. if (rule.media) {
  87. sheetContent += "@media " + Array.from(rule.media).join(",") + "{";
  88. sheetContent += serializeRules(rule.cssRules);
  89. sheetContent += "}";
  90. } else {
  91. sheetContent += rule.cssText;
  92. }
  93. });
  94. return sheetContent;
  95. }
  96. function testFilterSelector(selector) {
  97. return REMOVED_PSEUDO_CLASSES.find(pseudoClass => selector.includes(":" + pseudoClass)) || REMOVED_PSEUDO_ELEMENTS.find(pseudoElement => selector.includes("::" + pseudoElement));
  98. }
  99. function getFilteredSelector(selector) {
  100. const selectors = cssWhat.parse(selector);
  101. return cssWhat.stringify(selectors.map(selector => filterPseudoClasses(selector)));
  102. function filterPseudoClasses(selector) {
  103. const tokens = selector.filter(token => {
  104. if (token.data) {
  105. if (Array.isArray(token.data)) {
  106. token.data = token.data.map(selector => filterPseudoClasses(selector));
  107. }
  108. }
  109. const test = ((token.type != "pseudo" || !REMOVED_PSEUDO_CLASSES.includes(token.name))
  110. && (token.type != "pseudo-element" || !REMOVED_PSEUDO_ELEMENTS.includes(token.name)));
  111. return test;
  112. });
  113. let insertedTokens = 0;
  114. tokens.forEach((token, index) => {
  115. if (SEPARATOR_TYPES.includes(token.type)) {
  116. if (!tokens[index - 1] || SEPARATOR_TYPES.includes(tokens[index - 1].type)) {
  117. tokens.splice(index + insertedTokens, 0, { type: "universal" });
  118. insertedTokens++;
  119. }
  120. }
  121. });
  122. if (!tokens.length || SEPARATOR_TYPES.includes(tokens[tokens.length - 1].type)) {
  123. tokens.push({ type: "universal" });
  124. }
  125. return tokens;
  126. }
  127. }
  128. })();