css-minifier.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 = RulesMatcher.create(doc);
  28. const mediaAllInfo = rulesMatcher.getAllMatchedRules();
  29. const stats = { processed: 0, discarded: 0 };
  30. doc.querySelectorAll("style").forEach(styleElement => {
  31. if (styleElement.sheet) {
  32. let mediaInfo;
  33. if (styleElement.media && styleElement.media != "all") {
  34. mediaInfo = mediaAllInfo.medias.get(styleElement.media);
  35. } else {
  36. mediaInfo = mediaAllInfo;
  37. }
  38. processRules(doc, styleElement.sheet.cssRules, mediaInfo);
  39. styleElement.textContent = serializeRules(styleElement.sheet.cssRules);
  40. stats.discarded -= styleElement.sheet.cssRules.length;
  41. }
  42. });
  43. doc.querySelectorAll("[style]").forEach(element => {
  44. processStyle(doc, element.style, mediaAllInfo);
  45. });
  46. return stats;
  47. }
  48. };
  49. function processRules(doc, cssRules, mediaInfo) {
  50. Array.from(cssRules).forEach(cssRule => {
  51. if (cssRule.type == CSSRule.MEDIA_RULE) {
  52. processRules(doc, cssRule.cssRules, mediaInfo.medias.get(cssRule.media));
  53. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  54. const ruleInfo = mediaInfo.rules.get(cssRule);
  55. if (ruleInfo) {
  56. const stylesInfo = parseCss.parseAListOfDeclarations(cssRule.style.cssText);
  57. const unusedStyles = stylesInfo.filter(style => !ruleInfo.style.get(style.name));
  58. if (unusedStyles.length) {
  59. unusedStyles.forEach(style => cssRule.style.removeProperty(style.name));
  60. }
  61. if (ruleInfo.matchedSelectors.size < ruleInfo.selectorsText.length) {
  62. cssRule.selectorText = ruleInfo.selectorsText.filter(selector => ruleInfo.matchedSelectors.has(selector) || (testFilterSelector(selector) && doc.querySelector(getFilteredSelector(selector)))).join(",");
  63. }
  64. } else {
  65. if (!testFilterSelector(cssRule.selectorText) || !doc.querySelector(getFilteredSelector(cssRule.selectorText))) {
  66. const parent = cssRule.parentRule || cssRule.parentStyleSheet;
  67. let indexRule = 0;
  68. while (cssRule != parent.cssRules[indexRule] && indexRule < parent.cssRules.length) {
  69. indexRule++;
  70. }
  71. if (cssRule == parent.cssRules[indexRule]) {
  72. parent.deleteRule(indexRule);
  73. }
  74. }
  75. }
  76. }
  77. });
  78. }
  79. function processStyle(doc, cssStyle, mediaInfo) {
  80. const styleInfo = mediaInfo.styles.get(cssStyle);
  81. if (styleInfo) {
  82. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  83. const unusedStyles = stylesInfo.filter(style => !styleInfo.style.get(style.name));
  84. if (unusedStyles.length) {
  85. unusedStyles.forEach(style => cssStyle.removeProperty(style.name));
  86. }
  87. }
  88. }
  89. function serializeRules(rules) {
  90. let sheetContent = "";
  91. Array.from(rules).forEach(rule => {
  92. if (rule.media) {
  93. sheetContent += "@media " + Array.from(rule.media).join(",") + "{";
  94. sheetContent += serializeRules(rule.cssRules);
  95. sheetContent += "}";
  96. } else {
  97. sheetContent += rule.cssText;
  98. }
  99. });
  100. return sheetContent;
  101. }
  102. function testFilterSelector(selector) {
  103. return REMOVED_PSEUDO_CLASSES.find(pseudoClass => selector.includes(":" + pseudoClass)) || REMOVED_PSEUDO_ELEMENTS.find(pseudoElement => selector.includes("::" + pseudoElement));
  104. }
  105. function getFilteredSelector(selector) {
  106. const selectors = cssWhat.parse(selector);
  107. return cssWhat.stringify(selectors.map(selector => filterPseudoClasses(selector)));
  108. function filterPseudoClasses(selector) {
  109. const tokens = selector.filter(token => {
  110. if (token.data) {
  111. if (Array.isArray(token.data)) {
  112. token.data = token.data.map(selector => filterPseudoClasses(selector));
  113. }
  114. }
  115. const test = ((token.type != "pseudo" || !REMOVED_PSEUDO_CLASSES.includes(token.name))
  116. && (token.type != "pseudo-element" || !REMOVED_PSEUDO_ELEMENTS.includes(token.name)));
  117. return test;
  118. });
  119. let insertedTokens = 0;
  120. tokens.forEach((token, index) => {
  121. if (SEPARATOR_TYPES.includes(token.type)) {
  122. if (!tokens[index - 1] || SEPARATOR_TYPES.includes(tokens[index - 1].type)) {
  123. tokens.splice(index + insertedTokens, 0, { type: "universal" });
  124. insertedTokens++;
  125. }
  126. }
  127. });
  128. if (!tokens.length || SEPARATOR_TYPES.includes(tokens[tokens.length - 1].type)) {
  129. tokens.push({ type: "universal" });
  130. }
  131. return tokens;
  132. }
  133. }
  134. })();