css-fonts-minifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global window */
  24. this.singlefile.lib.modules.fontsMinifier = this.singlefile.lib.modules.fontsMinifier || (() => {
  25. const singlefile = this.singlefile;
  26. const getComputedStyle = window.getComputedStyle;
  27. const REGEXP_COMMA = /\s*,\s*/;
  28. const REGEXP_DASH = /-/;
  29. const REGEXP_QUESTION_MARK = /\?/g;
  30. const REGEXP_STARTS_U_PLUS = /^U\+/i;
  31. return {
  32. process: (doc, stylesheets, styles, options) => {
  33. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  34. const fontsInfo = { declared: [], used: [] };
  35. const workStyleElement = doc.createElement("style");
  36. let docContent = "";
  37. doc.body.appendChild(workStyleElement);
  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. docContent = getRulesTextContent(doc, cssRules, workStyleElement, docContent);
  45. }
  46. });
  47. styles.forEach(declarations => {
  48. const fontFamilyNames = getFontFamilyNames(declarations);
  49. if (fontFamilyNames.length) {
  50. fontsInfo.used.push(fontFamilyNames);
  51. }
  52. docContent = getDeclarationsTextContent(declarations.children, workStyleElement, docContent);
  53. });
  54. workStyleElement.remove();
  55. docContent += doc.body.innerText;
  56. if (getComputedStyle && options.doc) {
  57. fontsInfo.used = fontsInfo.used.map(fontNames => fontNames.map(familyName => {
  58. const matchedVar = familyName.match(/^var\((--.*)\)$/);
  59. if (matchedVar && matchedVar[1]) {
  60. const computedFamilyName = getComputedStyle.call(window, options.doc.body).getPropertyValue(matchedVar[1]);
  61. return (computedFamilyName && computedFamilyName.split(",").map(name => singlefile.lib.helper.getFontFamily(name))) || familyName;
  62. }
  63. return familyName;
  64. }));
  65. fontsInfo.used = fontsInfo.used.map(fontNames => singlefile.lib.helper.flatten(fontNames));
  66. }
  67. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  68. let unusedFonts, filteredUsedFonts;
  69. if (variableFound) {
  70. unusedFonts = [];
  71. } else {
  72. filteredUsedFonts = new Map();
  73. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  74. if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
  75. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo[0] == familyName);
  76. if (optionalData && optionalData.length) {
  77. filteredUsedFonts.set(familyName, optionalData);
  78. }
  79. }
  80. }));
  81. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
  82. }
  83. stylesheets.forEach(stylesheetInfo => {
  84. const cssRules = stylesheetInfo.stylesheet.children;
  85. if (cssRules) {
  86. filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  87. stats.rules.discarded -= cssRules.getSize();
  88. }
  89. });
  90. return stats;
  91. }
  92. };
  93. function getFontsInfo(cssRules, fontsInfo) {
  94. cssRules.forEach(ruleData => {
  95. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children) {
  96. getFontsInfo(ruleData.block.children, fontsInfo);
  97. } else if (ruleData.type == "Rule") {
  98. const fontFamilyNames = getFontFamilyNames(ruleData.block);
  99. if (fontFamilyNames.length) {
  100. fontsInfo.used.push(fontFamilyNames);
  101. }
  102. } else {
  103. if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  104. const fontFamily = singlefile.lib.helper.getFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
  105. if (fontFamily) {
  106. const fontWeight = singlefile.lib.helper.getFontWeight(getDeclarationValue(ruleData.block.children, "font-weight") || "400");
  107. const fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
  108. const fontVariant = getDeclarationValue(ruleData.block.children, "font-variant") || "normal";
  109. fontsInfo.declared.push({ fontFamily, fontWeight, fontStyle, fontVariant });
  110. }
  111. }
  112. }
  113. });
  114. }
  115. function filterUnusedFonts(cssRules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  116. const removedRules = [];
  117. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  118. const ruleData = cssRule.data;
  119. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children) {
  120. filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  121. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  122. const fontFamily = singlefile.lib.helper.getFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
  123. if (fontFamily) {
  124. const unicodeRange = getDeclarationValue(ruleData.block.children, "unicode-range");
  125. if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
  126. removedRules.push(cssRule);
  127. }
  128. }
  129. const removedDeclarations = [];
  130. for (let declaration = ruleData.block.children.head; declaration; declaration = declaration.next) {
  131. if (declaration.data.property == "font-display") {
  132. removedDeclarations.push(declaration);
  133. }
  134. }
  135. if (removedDeclarations.length) {
  136. removedDeclarations.forEach(removedDeclaration => ruleData.block.children.remove(removedDeclaration));
  137. }
  138. }
  139. }
  140. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  141. }
  142. function testUsedFont(ruleData, familyName, declaredFonts, filteredUsedFonts) {
  143. let test;
  144. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  145. if (optionalUsedFonts && optionalUsedFonts.length) {
  146. const fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
  147. const fontWeight = singlefile.lib.helper.getFontWeight(getDeclarationValue(ruleData.block.children, "font-weight") || "400");
  148. const declaredFontsWeights = declaredFonts
  149. .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle)
  150. .map(fontInfo => fontInfo.fontWeight)
  151. .sort((weight1, weight2) => weight1 - weight2);
  152. const usedFontWeights = optionalUsedFonts.map(fontInfo => getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights));
  153. test = usedFontWeights.includes(fontWeight);
  154. } else {
  155. test = true;
  156. }
  157. return test;
  158. }
  159. function getDeclarationValue(declarations, propertyName) {
  160. let property;
  161. if (declarations) {
  162. property = declarations.filter(declaration => declaration.property == propertyName).tail;
  163. }
  164. if (property) {
  165. try {
  166. return singlefile.lib.helper.removeQuotes(singlefile.lib.vendor.cssTree.generate(property.data.value));
  167. } catch (error) {
  168. // ignored
  169. }
  170. }
  171. }
  172. function getFontFamilyNames(declarations) {
  173. const cssTree = singlefile.lib.vendor.cssTree;
  174. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  175. let fontFamilyNames = [];
  176. if (fontFamilyName) {
  177. let familyName = "";
  178. if (fontFamilyName.data.value.children) {
  179. fontFamilyName.data.value.children.forEach(node => {
  180. if (node.type == "Operator" && node.value == "," && familyName) {
  181. fontFamilyNames.push(singlefile.lib.helper.getFontFamily(familyName));
  182. familyName = "";
  183. } else {
  184. familyName += cssTree.generate(node);
  185. }
  186. });
  187. } else {
  188. fontFamilyName = cssTree.generate(fontFamilyName.data.value);
  189. }
  190. if (familyName) {
  191. fontFamilyNames.push(singlefile.lib.helper.getFontFamily(familyName));
  192. }
  193. }
  194. const font = declarations.children.filter(node => node.property == "font").tail;
  195. if (font && font.data && font.data.value) {
  196. try {
  197. const parsedFont = singlefile.lib.vendor.fontPropertyParser.parse(cssTree.generate(font.data.value));
  198. parsedFont.family.forEach(familyName => fontFamilyNames.push(singlefile.lib.helper.getFontFamily(familyName)));
  199. } catch (error) {
  200. // ignored
  201. }
  202. }
  203. return fontFamilyNames;
  204. }
  205. function getUsedFontWeight(fontInfo, fontStyle, fontWeights) {
  206. let foundWeight;
  207. if (fontInfo[2] == fontStyle) {
  208. let fontWeight = Number(fontInfo[1]);
  209. if (fontWeight >= 400 && fontWeight <= 500) {
  210. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  211. if (!foundWeight) {
  212. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  213. }
  214. if (!foundWeight) {
  215. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  216. }
  217. }
  218. if (fontWeight < 400) {
  219. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  220. if (!foundWeight) {
  221. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  222. }
  223. }
  224. if (fontWeight > 500) {
  225. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  226. if (!foundWeight) {
  227. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  228. }
  229. }
  230. }
  231. return foundWeight;
  232. }
  233. function findDescendingFontWeight(fontWeight, fontWeights) {
  234. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  235. }
  236. function findAscendingFontWeight(fontWeight, fontWeights) {
  237. return fontWeights.find(weight => weight > fontWeight);
  238. }
  239. function getRulesTextContent(doc, cssRules, workStylesheet, content) {
  240. cssRules.forEach(ruleData => {
  241. if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
  242. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  243. content = getRulesTextContent(doc, ruleData.block.children, workStylesheet, content);
  244. } else if (ruleData.type == "Rule") {
  245. content = getDeclarationsTextContent(ruleData.block.children, workStylesheet, content);
  246. }
  247. }
  248. });
  249. return content;
  250. }
  251. function getDeclarationsTextContent(declarations, workStylesheet, content) {
  252. const contentText = getDeclarationUnescapedValue(declarations, "content", workStylesheet);
  253. const quotesText = getDeclarationUnescapedValue(declarations, "quotes", workStylesheet);
  254. if (!content.includes(contentText)) {
  255. content += contentText;
  256. }
  257. if (!content.includes(quotesText)) {
  258. content += quotesText;
  259. }
  260. return content;
  261. }
  262. function getDeclarationUnescapedValue(declarations, property, workStylesheet) {
  263. const rawValue = getDeclarationValue(declarations, property) || "";
  264. if (rawValue) {
  265. workStylesheet.textContent = "tmp { content:\"" + rawValue + "\"}";
  266. if (workStylesheet.sheet && workStylesheet.sheet.cssRules) {
  267. return singlefile.lib.helper.removeQuotes(workStylesheet.sheet.cssRules[0].style.getPropertyValue("content"));
  268. } else {
  269. return rawValue;
  270. }
  271. }
  272. return "";
  273. }
  274. function testUnicodeRange(docContent, unicodeRange) {
  275. if (unicodeRange) {
  276. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  277. let invalid;
  278. const result = unicodeRanges.filter(rangeValue => {
  279. const range = rangeValue.split(REGEXP_DASH);
  280. let regExpString;
  281. if (range.length == 2) {
  282. range[0] = transformRange(range[0]);
  283. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  284. }
  285. if (range.length == 1) {
  286. if (range[0].includes("?")) {
  287. const firstRange = transformRange(range[0]);
  288. const secondRange = firstRange;
  289. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  290. } else if (range[0]) {
  291. regExpString = "[" + transformRange(range[0]) + "]";
  292. }
  293. }
  294. if (regExpString) {
  295. try {
  296. return (new RegExp(regExpString, "u")).test(docContent);
  297. } catch (error) {
  298. invalid = true;
  299. return false;
  300. }
  301. }
  302. return true;
  303. });
  304. return !invalid && (!unicodeRanges.length || result.length);
  305. }
  306. return true;
  307. }
  308. function transformRange(range) {
  309. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  310. while (range.length < 6) {
  311. range = "0" + range;
  312. }
  313. return "\\u{" + range + "}";
  314. }
  315. })();