css-rules-minifier.js 6.3 KB

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