css-minifier.js 5.9 KB

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