css-minifier.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 */
  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. const MEDIA_ALL = "all";
  26. const PRIORITY_IMPORTANT = "important";
  27. return {
  28. process: doc => {
  29. const mediaAllInfo = createMediaInfo(MEDIA_ALL);
  30. const stats = { processed: 0, discarded: 0 };
  31. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  32. if (styleElement.sheet) {
  33. stats.processed += styleElement.sheet.cssRules.length;
  34. stats.discarded += styleElement.sheet.cssRules.length;
  35. if (styleElement.media && styleElement.media != MEDIA_ALL) {
  36. const mediaInfo = createMediaInfo(styleElement.media);
  37. mediaAllInfo.medias.set(styleElement.media, mediaInfo);
  38. getMatchedElements(doc, styleElement.sheet.cssRules, mediaInfo, styleIndex);
  39. } else {
  40. getMatchedElements(doc, styleElement.sheet.cssRules, mediaAllInfo, styleIndex);
  41. }
  42. }
  43. });
  44. sortRules(mediaAllInfo);
  45. computeCascade(mediaAllInfo);
  46. doc.querySelectorAll("style").forEach(styleElement => {
  47. if (styleElement.sheet) {
  48. replaceRules(doc, styleElement.sheet.cssRules, mediaAllInfo);
  49. styleElement.textContent = serializeRules(styleElement.sheet.cssRules);
  50. stats.discarded -= styleElement.sheet.cssRules.length;
  51. }
  52. });
  53. doc.querySelectorAll("[style]").forEach(element => {
  54. replaceStyle(doc, element.style, mediaAllInfo);
  55. });
  56. return stats;
  57. }
  58. };
  59. function getMatchedElements(doc, cssRules, mediaInfo, sheetIndex) {
  60. Array.from(cssRules).forEach((cssRule, ruleIndex) => {
  61. if (cssRule.type == CSSRule.MEDIA_RULE) {
  62. const ruleMediaInfo = createMediaInfo(cssRule.media);
  63. mediaInfo.medias.set(cssRule.media, ruleMediaInfo);
  64. getMatchedElements(doc, cssRule.cssRules, ruleMediaInfo, sheetIndex);
  65. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  66. if (cssRule.selectorText) {
  67. const selectors = cssWhat.parse(cssRule.selectorText);
  68. selectors.forEach((selector, selectorIndex) => {
  69. doc.querySelectorAll(cssWhat.stringify([selector])).forEach(element => {
  70. let elementInfo;
  71. if (mediaInfo.elements.has(element)) {
  72. elementInfo = mediaInfo.elements.get(element);
  73. } else {
  74. elementInfo = [];
  75. const elementStyle = element.getAttribute("style");
  76. if (elementStyle) {
  77. elementInfo.push({ cssStyle: element.style });
  78. }
  79. mediaInfo.elements.set(element, elementInfo);
  80. }
  81. elementInfo.push({ cssRule, specificity: computeSpecificity(selector), selectorIndex, ruleIndex, sheetIndex });
  82. });
  83. });
  84. }
  85. }
  86. });
  87. }
  88. function createMediaInfo(media) {
  89. const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map() };
  90. if (media == MEDIA_ALL) {
  91. mediaInfo.styles = new Map();
  92. }
  93. return mediaInfo;
  94. }
  95. function sortRules(media) {
  96. media.elements.forEach(elementRules => elementRules.sort(compareRules));
  97. media.medias.forEach(sortRules);
  98. }
  99. function computeCascade(mediaInfo, parentMediaInfos = []) {
  100. mediaInfo.elements.forEach((elementInfo) => {
  101. const elementStylesInfo = new Map();
  102. elementInfo.forEach(ruleInfo => {
  103. if (ruleInfo.cssStyle) {
  104. const cssStyle = ruleInfo.cssStyle;
  105. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  106. stylesInfo.forEach(styleInfo => {
  107. const important = cssStyle.getPropertyPriority(styleInfo.name) == PRIORITY_IMPORTANT;
  108. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important ? " !" + PRIORITY_IMPORTANT : "");
  109. elementStylesInfo.set(styleInfo.name, { styleValue, cssStyle: ruleInfo.cssStyle, important });
  110. });
  111. } else {
  112. const cssStyle = ruleInfo.cssRule.style;
  113. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  114. stylesInfo.forEach(styleInfo => {
  115. const important = cssStyle.getPropertyPriority(styleInfo.name) == PRIORITY_IMPORTANT;
  116. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important ? " !" + PRIORITY_IMPORTANT : "");
  117. let elementStyleInfo = elementStylesInfo.get(styleInfo.name);
  118. if (!elementStyleInfo || (important && !elementStyleInfo.important)) {
  119. elementStylesInfo.set(styleInfo.name, { styleValue, cssRule: ruleInfo.cssRule, important });
  120. }
  121. });
  122. }
  123. });
  124. elementStylesInfo.forEach((styleInfo, styleName) => {
  125. let ruleInfo, ascendantMedia, allMedia;
  126. if (styleInfo.cssRule) {
  127. ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(styleInfo.cssRule)) || mediaInfo;
  128. ruleInfo = ascendantMedia.rules.get(styleInfo.cssRule);
  129. }
  130. if (styleInfo.cssStyle) {
  131. allMedia = parentMediaInfos[parentMediaInfos.length - 1] || mediaInfo;
  132. ruleInfo = allMedia.styles.get(styleInfo.cssStyle);
  133. }
  134. if (!ruleInfo) {
  135. ruleInfo = new Map();
  136. if (styleInfo.cssRule) {
  137. ascendantMedia.rules.set(styleInfo.cssRule, ruleInfo);
  138. } else {
  139. allMedia.styles.set(styleInfo.cssStyle, ruleInfo);
  140. }
  141. }
  142. ruleInfo.set(styleName, styleInfo.styleValue);
  143. });
  144. });
  145. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos]));
  146. }
  147. function replaceRules(doc, cssRules, ruleMedia) {
  148. Array.from(cssRules).forEach(cssRule => {
  149. if (cssRule.type == CSSRule.MEDIA_RULE) {
  150. replaceRules(doc, cssRule.cssRules, ruleMedia.medias.get(cssRule.media));
  151. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  152. const ruleInfo = ruleMedia.rules.get(cssRule);
  153. if (ruleInfo) {
  154. const stylesInfo = parseCss.parseAListOfDeclarations(cssRule.style.cssText);
  155. const unusedStyles = stylesInfo.filter(style => !ruleInfo.get(style.name));
  156. if (unusedStyles.length) {
  157. unusedStyles.forEach(style => cssRule.style.removeProperty(style.name));
  158. }
  159. } else {
  160. if (!testFilterSelector(cssRule.selectorText) || !doc.querySelector(getFilteredSelector(cssRule.selectorText))) {
  161. const parent = cssRule.parentRule || cssRule.parentStyleSheet;
  162. let indexRule = 0;
  163. while (cssRule != parent.cssRules[indexRule] && indexRule < parent.cssRules.length) {
  164. indexRule++;
  165. }
  166. if (cssRule == parent.cssRules[indexRule]) {
  167. parent.deleteRule(indexRule);
  168. }
  169. }
  170. }
  171. }
  172. });
  173. }
  174. function replaceStyle(doc, cssStyle, ruleMedia) {
  175. const styleInfo = ruleMedia.styles.get(cssStyle);
  176. if (styleInfo) {
  177. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  178. const unusedStyles = stylesInfo.filter(style => !styleInfo.get(style.name));
  179. if (unusedStyles.length) {
  180. unusedStyles.forEach(style => cssStyle.removeProperty(style.name));
  181. }
  182. }
  183. }
  184. function serializeRules(rules) {
  185. let sheetContent = "";
  186. Array.from(rules).forEach(rule => {
  187. if (rule.media) {
  188. sheetContent += "@media " + Array.from(rule.media).join(",") + "{";
  189. sheetContent += serializeRules(rule.cssRules);
  190. sheetContent += "}";
  191. } else {
  192. sheetContent += rule.cssText;
  193. }
  194. });
  195. return sheetContent;
  196. }
  197. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  198. selector.forEach(token => {
  199. if (token.expandedSelector && token.type == "attribute" && token.name === "id" && token.action === "equals") {
  200. specificity.a++;
  201. }
  202. if ((!token.expandedSelector && token.type == "attribute") ||
  203. (token.expandedSelector && token.type == "attribute" && token.name === "class" && token.action === "element") ||
  204. (token.type == "pseudo" && token.name != "not")) {
  205. specificity.b++;
  206. }
  207. if ((token.type == "tag" && token.value != "*") || (token.type == "pseudo-element")) {
  208. specificity.c++;
  209. }
  210. if (token.data) {
  211. if (Array.isArray(token.data)) {
  212. token.data.forEach(selector => computeSpecificity(selector, specificity));
  213. }
  214. }
  215. });
  216. return specificity;
  217. }
  218. function compareRules(ruleInfo1, ruleInfo2) {
  219. if (ruleInfo1.cssStyle && !ruleInfo2.cssStyle) {
  220. return -1;
  221. } else if (!ruleInfo1.cssStyle && ruleInfo2.cssStyle) {
  222. return 1;
  223. } else if (ruleInfo1.specificity.a > ruleInfo2.specificity.a) {
  224. return -1;
  225. } else if (ruleInfo1.specificity.a < ruleInfo2.specificity.a) {
  226. return 1;
  227. } else if (ruleInfo1.specificity.b > ruleInfo2.specificity.b) {
  228. return -1;
  229. } else if (ruleInfo1.specificity.b < ruleInfo2.specificity.b) {
  230. return 1;
  231. } else if (ruleInfo1.specificity.c > ruleInfo2.specificity.c) {
  232. return -1;
  233. } else if (ruleInfo1.specificity.c < ruleInfo2.specificity.c) {
  234. return 1;
  235. } else if (ruleInfo1.sheetIndex > ruleInfo2.sheetIndex) {
  236. return -1;
  237. } else if (ruleInfo1.sheetIndex < ruleInfo2.sheetIndex) {
  238. return 1;
  239. } else if (ruleInfo1.ruleIndex > ruleInfo2.ruleIndex) {
  240. return -1;
  241. } else if (ruleInfo1.ruleIndex < ruleInfo2.ruleIndex) {
  242. return 1;
  243. } else if (ruleInfo1.selectorIndex > ruleInfo2.selectorIndex) {
  244. return -1;
  245. } else if (ruleInfo1.selectorIndex < ruleInfo2.selectorIndex) {
  246. return 1;
  247. } else {
  248. return -1;
  249. }
  250. }
  251. function testFilterSelector(selector) {
  252. return REMOVED_PSEUDO_CLASSES.find(pseudoClass => selector.includes(":" + pseudoClass)) || REMOVED_PSEUDO_ELEMENTS.find(pseudoElement => selector.includes("::" + pseudoElement));
  253. }
  254. function getFilteredSelector(selector) {
  255. const selectors = cssWhat.parse(selector);
  256. return cssWhat.stringify(selectors.map(selector => filterPseudoClasses(selector)));
  257. function filterPseudoClasses(selector) {
  258. const tokens = selector.filter(token => {
  259. if (token.data) {
  260. if (Array.isArray(token.data)) {
  261. token.data = token.data.map(selector => filterPseudoClasses(selector));
  262. }
  263. }
  264. const test = ((token.type != "pseudo" || !REMOVED_PSEUDO_CLASSES.includes(token.name))
  265. && (token.type != "pseudo-element" || !REMOVED_PSEUDO_ELEMENTS.includes(token.name)));
  266. return test;
  267. });
  268. let insertedTokens = 0;
  269. tokens.forEach((token, index) => {
  270. if (SEPARATOR_TYPES.includes(token.type)) {
  271. if (!tokens[index - 1] || SEPARATOR_TYPES.includes(tokens[index - 1].type)) {
  272. tokens.splice(index + insertedTokens, 0, { type: "universal" });
  273. insertedTokens++;
  274. }
  275. }
  276. });
  277. if (!tokens.length || SEPARATOR_TYPES.includes(tokens[tokens.length - 1].type)) {
  278. tokens.push({ type: "universal" });
  279. }
  280. return tokens;
  281. }
  282. }
  283. })();