css-fonts-minifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. let usedFontWeights = optionalUsedFonts.map(fontInfo => getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights));
  153. test = usedFontWeights.includes(fontWeight);
  154. if (!test) {
  155. usedFontWeights = optionalUsedFonts.map(fontInfo => {
  156. fontInfo[2] = "normal";
  157. return getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights);
  158. });
  159. }
  160. test = usedFontWeights.includes(fontWeight);
  161. } else {
  162. test = true;
  163. }
  164. return test;
  165. }
  166. function getDeclarationValue(declarations, propertyName) {
  167. let property;
  168. if (declarations) {
  169. property = declarations.filter(declaration => declaration.property == propertyName).tail;
  170. }
  171. if (property) {
  172. try {
  173. return singlefile.lib.helper.removeQuotes(singlefile.lib.vendor.cssTree.generate(property.data.value));
  174. } catch (error) {
  175. // ignored
  176. }
  177. }
  178. }
  179. function getFontFamilyNames(declarations) {
  180. const cssTree = singlefile.lib.vendor.cssTree;
  181. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  182. let fontFamilyNames = [];
  183. if (fontFamilyName) {
  184. let familyName = "";
  185. if (fontFamilyName.data.value.children) {
  186. fontFamilyName.data.value.children.forEach(node => {
  187. if (node.type == "Operator" && node.value == "," && familyName) {
  188. fontFamilyNames.push(singlefile.lib.helper.getFontFamily(familyName));
  189. familyName = "";
  190. } else {
  191. familyName += cssTree.generate(node);
  192. }
  193. });
  194. } else {
  195. fontFamilyName = cssTree.generate(fontFamilyName.data.value);
  196. }
  197. if (familyName) {
  198. fontFamilyNames.push(singlefile.lib.helper.getFontFamily(familyName));
  199. }
  200. }
  201. const font = declarations.children.filter(node => node.property == "font").tail;
  202. if (font && font.data && font.data.value) {
  203. try {
  204. const parsedFont = singlefile.lib.vendor.fontPropertyParser.parse(cssTree.generate(font.data.value));
  205. parsedFont.family.forEach(familyName => fontFamilyNames.push(singlefile.lib.helper.getFontFamily(familyName)));
  206. } catch (error) {
  207. // ignored
  208. }
  209. }
  210. return fontFamilyNames;
  211. }
  212. function getUsedFontWeight(fontInfo, fontStyle, fontWeights) {
  213. let foundWeight;
  214. if (fontInfo[2] == fontStyle) {
  215. let fontWeight = Number(fontInfo[1]);
  216. if (fontWeight >= 400 && fontWeight <= 500) {
  217. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  218. if (!foundWeight) {
  219. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  220. }
  221. if (!foundWeight) {
  222. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  223. }
  224. }
  225. if (fontWeight < 400) {
  226. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  227. if (!foundWeight) {
  228. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  229. }
  230. }
  231. if (fontWeight > 500) {
  232. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  233. if (!foundWeight) {
  234. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  235. }
  236. }
  237. }
  238. return foundWeight;
  239. }
  240. function findDescendingFontWeight(fontWeight, fontWeights) {
  241. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  242. }
  243. function findAscendingFontWeight(fontWeight, fontWeights) {
  244. return fontWeights.find(weight => weight > fontWeight);
  245. }
  246. function getRulesTextContent(doc, cssRules, workStylesheet, content) {
  247. cssRules.forEach(ruleData => {
  248. if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
  249. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  250. content = getRulesTextContent(doc, ruleData.block.children, workStylesheet, content);
  251. } else if (ruleData.type == "Rule") {
  252. content = getDeclarationsTextContent(ruleData.block.children, workStylesheet, content);
  253. }
  254. }
  255. });
  256. return content;
  257. }
  258. function getDeclarationsTextContent(declarations, workStylesheet, content) {
  259. const contentText = getDeclarationUnescapedValue(declarations, "content", workStylesheet);
  260. const quotesText = getDeclarationUnescapedValue(declarations, "quotes", workStylesheet);
  261. if (!content.includes(contentText)) {
  262. content += contentText;
  263. }
  264. if (!content.includes(quotesText)) {
  265. content += quotesText;
  266. }
  267. return content;
  268. }
  269. function getDeclarationUnescapedValue(declarations, property, workStylesheet) {
  270. const rawValue = getDeclarationValue(declarations, property) || "";
  271. if (rawValue) {
  272. workStylesheet.textContent = "tmp { content:\"" + rawValue + "\"}";
  273. if (workStylesheet.sheet && workStylesheet.sheet.cssRules) {
  274. return singlefile.lib.helper.removeQuotes(workStylesheet.sheet.cssRules[0].style.getPropertyValue("content"));
  275. } else {
  276. return rawValue;
  277. }
  278. }
  279. return "";
  280. }
  281. function testUnicodeRange(docContent, unicodeRange) {
  282. if (unicodeRange) {
  283. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  284. let invalid;
  285. const result = unicodeRanges.filter(rangeValue => {
  286. const range = rangeValue.split(REGEXP_DASH);
  287. let regExpString;
  288. if (range.length == 2) {
  289. range[0] = transformRange(range[0]);
  290. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  291. }
  292. if (range.length == 1) {
  293. if (range[0].includes("?")) {
  294. const firstRange = transformRange(range[0]);
  295. const secondRange = firstRange;
  296. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  297. } else if (range[0]) {
  298. regExpString = "[" + transformRange(range[0]) + "]";
  299. }
  300. }
  301. if (regExpString) {
  302. try {
  303. return (new RegExp(regExpString, "u")).test(docContent);
  304. } catch (error) {
  305. invalid = true;
  306. return false;
  307. }
  308. }
  309. return true;
  310. });
  311. return !invalid && (!unicodeRanges.length || result.length);
  312. }
  313. return true;
  314. }
  315. function transformRange(range) {
  316. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  317. while (range.length < 6) {
  318. range = "0" + range;
  319. }
  320. return "\\u{" + range + "}";
  321. }
  322. })();