css-fonts-minifier.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 cssTree, docHelper */
  21. this.fontsMinifier = this.fontsMinifier || (() => {
  22. const REGEXP_COMMA = /\s*,\s*/;
  23. const REGEXP_DASH = /-/;
  24. const REGEXP_QUESTION_MARK = /\?/g;
  25. const REGEXP_STARTS_U_PLUS = /^U\+/i;
  26. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  27. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  28. const PSEUDO_ELEMENTS = ["::after", "::before", "::first-line", "::first-letter", ":before", ":after", ":first-line", ":first-letter", "::placeholder", "::selection", "::marker", "::cue", "::slotted", "::spelling-error", "::grammar-error"];
  29. const FONT_WEIGHTS = {
  30. normal: "400",
  31. bold: "700"
  32. };
  33. return {
  34. process: (doc, stylesheets, styles, options) => {
  35. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  36. const fontsInfo = { declared: [], used: [] };
  37. let pseudoElementsContent = "";
  38. stylesheets.forEach(stylesheetInfo => {
  39. const cssRules = stylesheetInfo.stylesheet.children;
  40. stats.processed += cssRules.getSize();
  41. stats.discarded += cssRules.getSize();
  42. getFontsInfo(cssRules, fontsInfo);
  43. pseudoElementsContent += getPseudoElementsContent(doc, cssRules);
  44. });
  45. styles.forEach(style => {
  46. const fontFamilyNames = getFontFamilyNames(style);
  47. if (fontFamilyNames.length) {
  48. fontsInfo.used.push(fontFamilyNames);
  49. }
  50. });
  51. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  52. let unusedFonts, filteredUsedFonts;
  53. if (variableFound) {
  54. unusedFonts = [];
  55. } else {
  56. filteredUsedFonts = new Map();
  57. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  58. if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
  59. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo.fontFamily == familyName);
  60. filteredUsedFonts.set(familyName, optionalData);
  61. }
  62. }));
  63. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
  64. }
  65. const docContent = doc.body.innerText + pseudoElementsContent;
  66. stylesheets.forEach(stylesheetInfo => {
  67. const cssRules = stylesheetInfo.stylesheet.children;
  68. filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  69. stats.rules.discarded -= cssRules.getSize();
  70. });
  71. return stats;
  72. }
  73. };
  74. function getFontsInfo(cssRules, fontsInfo) {
  75. cssRules.forEach(cssRule => {
  76. if (cssRule.type == "Atrule" && cssRule.name == "media" && cssRule.block) {
  77. getFontsInfo(cssRule.block.children, fontsInfo);
  78. } else if (cssRule.type == "Rule") {
  79. const fontFamilyNames = getFontFamilyNames(cssRule.block);
  80. if (fontFamilyNames.length) {
  81. fontsInfo.used.push(fontFamilyNames);
  82. }
  83. } else {
  84. if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  85. const fontFamily = getFontFamily(getPropertyValue(cssRule, "font-family"));
  86. if (fontFamily) {
  87. const fontWeight = getFontWeight(getPropertyValue(cssRule, "font-weight") || "400");
  88. const fontStyle = getPropertyValue(cssRule, "font-style") || "normal";
  89. const fontVariant = getPropertyValue(cssRule, "font-variant") || "normal";
  90. fontsInfo.declared.push({ fontFamily, fontWeight, fontStyle, fontVariant });
  91. }
  92. }
  93. }
  94. });
  95. }
  96. function filterUnusedFonts(cssRules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  97. const removedRules = [];
  98. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  99. const ruleData = cssRule.data;
  100. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block) {
  101. filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  102. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  103. const fontFamily = getFontFamily(getPropertyValue(ruleData, "font-family"));
  104. if (fontFamily) {
  105. const unicodeRange = getPropertyValue(ruleData, "unicode-range");
  106. if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
  107. removedRules.push(cssRule);
  108. }
  109. }
  110. }
  111. }
  112. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  113. }
  114. function testUsedFont(cssRule, familyName, declaredFonts, filteredUsedFonts) {
  115. let test;
  116. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  117. if (optionalUsedFonts && optionalUsedFonts.length) {
  118. const fontStyle = getPropertyValue(cssRule, "font-style") || "normal";
  119. const fontWeight = getFontWeight(getPropertyValue(cssRule, "font-weight") || "400");
  120. const fontVariant = getPropertyValue(cssRule, "font-variant") || "normal";
  121. const declaredFontsWeights = declaredFonts
  122. .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle && testFontVariant(fontInfo, fontVariant))
  123. .map(fontInfo => fontInfo.fontWeight)
  124. .sort((weight1, weight2) => weight1 - weight2);
  125. const usedFontWeights = optionalUsedFonts.map(fontInfo => findFontWeight(fontInfo.fontWeight, declaredFontsWeights));
  126. test = usedFontWeights.includes(fontWeight);
  127. } else {
  128. test = true;
  129. }
  130. return test;
  131. }
  132. function getPropertyValue(cssRule, propertyName) {
  133. const property = cssRule.block.children.filter(node => node.property == propertyName).tail;
  134. if (property) {
  135. try {
  136. return cssTree.generate(property.data.value);
  137. } catch (error) {
  138. // ignored
  139. }
  140. }
  141. }
  142. function getFontFamilyNames(declarations) {
  143. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  144. let fontFamilyNames = [];
  145. if (fontFamilyName) {
  146. let familyName = "";
  147. if (fontFamilyName.data.value.children) {
  148. fontFamilyName.data.value.children.forEach(node => {
  149. if (node.type == "Operator" && node.value == "," && familyName) {
  150. fontFamilyNames.push(getFontFamily(familyName));
  151. familyName = "";
  152. } else {
  153. familyName += cssTree.generate(node);
  154. }
  155. });
  156. } else {
  157. fontFamilyName = cssTree.generate(fontFamilyName.data.value);
  158. }
  159. if (familyName) {
  160. fontFamilyNames.push(getFontFamily(familyName));
  161. }
  162. }
  163. const font = declarations.children.filter(node => node.property == "font").tail;
  164. if (font) {
  165. let familyName = "";
  166. const findPreviousComma = node => {
  167. for (; node && !(node.data.type == "Operator" && node.data.value == ","); node = node.prev);
  168. return node;
  169. };
  170. for (let node = font.data.value.children.tail; node && (node.data.type != "WhiteSpace" || findPreviousComma(node)); node = node.prev) {
  171. if (node.data.type == "Operator" && node.data.value == "," && familyName) {
  172. fontFamilyNames.push(getFontFamily(familyName));
  173. familyName = "";
  174. } else {
  175. familyName = cssTree.generate(node.data) + familyName;
  176. }
  177. }
  178. if (familyName) {
  179. fontFamilyNames.push(getFontFamily(familyName));
  180. }
  181. }
  182. return fontFamilyNames;
  183. }
  184. function findFontWeight(fontWeight, fontWeights) {
  185. let foundWeight;
  186. if (fontWeight >= 400 && fontWeight <= 500) {
  187. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  188. if (!foundWeight) {
  189. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  190. }
  191. if (!foundWeight) {
  192. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  193. }
  194. }
  195. if (fontWeight < 400) {
  196. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  197. if (!foundWeight) {
  198. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  199. }
  200. }
  201. if (fontWeight > 500) {
  202. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  203. if (!foundWeight) {
  204. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  205. }
  206. }
  207. return foundWeight;
  208. }
  209. function findDescendingFontWeight(fontWeight, fontWeights) {
  210. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  211. }
  212. function findAscendingFontWeight(fontWeight, fontWeights) {
  213. return fontWeights.find(weight => weight > fontWeight);
  214. }
  215. function getPseudoElementsContent(doc, cssRules) {
  216. return cssRules.toArray().map(cssRule => {
  217. if (cssRule.block && cssRule.block.children && cssRule.prelude && cssRule.prelude.children) {
  218. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  219. return getPseudoElementsContent(doc, cssRule.block.children);
  220. } else if (cssRule.type == "Rule") {
  221. const selector = cssTree.generate(cssRule.prelude); // TODO use OM
  222. if (testPseudoElements(selector)) {
  223. const value = docHelper.removeQuotes(getPropertyValue(cssRule, "content") || "");
  224. if (value) {
  225. const styleElement = doc.createElement("style");
  226. styleElement.textContent = "tmp { content:\"" + value + "\"}";
  227. doc.documentElement.appendChild(styleElement);
  228. let content = docHelper.removeQuotes(styleElement.sheet.cssRules[0].style.getPropertyValue("content"));
  229. styleElement.remove();
  230. return content;
  231. }
  232. }
  233. }
  234. }
  235. }).join("");
  236. }
  237. function testFontVariant(fontInfo, fontVariant) {
  238. return fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures";
  239. }
  240. function testUnicodeRange(docContent, unicodeRange) {
  241. if (unicodeRange) {
  242. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  243. let invalid;
  244. const result = unicodeRanges.filter(rangeValue => {
  245. const range = rangeValue.split(REGEXP_DASH);
  246. let regExpString;
  247. if (range.length == 2) {
  248. range[0] = transformRange(range[0]);
  249. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  250. }
  251. if (range.length == 1) {
  252. if (range[0].includes("?")) {
  253. const firstRange = transformRange(range[0]);
  254. const secondRange = firstRange;
  255. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  256. } else {
  257. regExpString = "[" + transformRange(range[0]) + "]";
  258. }
  259. }
  260. if (regExpString) {
  261. try {
  262. return (new RegExp(regExpString, "u")).test(docContent);
  263. } catch (error) {
  264. invalid = true;
  265. return false;
  266. }
  267. }
  268. return true;
  269. });
  270. return !invalid && (!unicodeRanges.length || result.length);
  271. }
  272. return true;
  273. }
  274. function testPseudoElements(selectorText) {
  275. let indexSelector = 0, found;
  276. selectorText = selectorText.toLowerCase();
  277. while (indexSelector < PSEUDO_ELEMENTS.length && !found) {
  278. found = selectorText.includes(PSEUDO_ELEMENTS[indexSelector]);
  279. if (!found) {
  280. indexSelector++;
  281. }
  282. }
  283. return found;
  284. }
  285. function transformRange(range) {
  286. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  287. while (range.length < 6) {
  288. range = "0" + range;
  289. }
  290. return "\\u{" + range + "}";
  291. }
  292. function getFontFamily(string = "") {
  293. string = string.toLowerCase().trim();
  294. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  295. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  296. } else {
  297. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  298. }
  299. return string.trim();
  300. }
  301. function getFontWeight(weight) {
  302. return FONT_WEIGHTS[weight] || weight;
  303. }
  304. })();