css-fonts-minifier.js 12 KB

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