css-fonts-minifier.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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.normalizeFontFamily(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.name == "supports") && 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.normalizeFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
  105. if (fontFamily) {
  106. const fontWeight = 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. fontWeight.split(",").forEach(weightValue =>
  110. fontsInfo.declared.push({ fontFamily, fontWeight: singlefile.lib.helper.getFontWeight(singlefile.lib.helper.removeQuotes(weightValue)), fontStyle, fontVariant }));
  111. }
  112. }
  113. }
  114. });
  115. }
  116. function filterUnusedFonts(cssRules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  117. const removedRules = [];
  118. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  119. const ruleData = cssRule.data;
  120. if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports") && ruleData.block && ruleData.block.children) {
  121. filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  122. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  123. const fontFamily = singlefile.lib.helper.normalizeFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
  124. if (fontFamily) {
  125. const unicodeRange = getDeclarationValue(ruleData.block.children, "unicode-range");
  126. if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
  127. removedRules.push(cssRule);
  128. }
  129. }
  130. const removedDeclarations = [];
  131. for (let declaration = ruleData.block.children.head; declaration; declaration = declaration.next) {
  132. if (declaration.data.property == "font-display") {
  133. removedDeclarations.push(declaration);
  134. }
  135. }
  136. if (removedDeclarations.length) {
  137. removedDeclarations.forEach(removedDeclaration => ruleData.block.children.remove(removedDeclaration));
  138. }
  139. }
  140. }
  141. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  142. }
  143. function testUsedFont(ruleData, familyName, declaredFonts, filteredUsedFonts) {
  144. let test;
  145. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  146. if (optionalUsedFonts && optionalUsedFonts.length) {
  147. const fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
  148. const fontWeight = singlefile.lib.helper.getFontWeight(getDeclarationValue(ruleData.block.children, "font-weight") || "400");
  149. const declaredFontsWeights = declaredFonts
  150. .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle)
  151. .map(fontInfo => fontInfo.fontWeight)
  152. .sort((weight1, weight2) => weight1 - weight2);
  153. let usedFontWeights = optionalUsedFonts.map(fontInfo => getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights));
  154. test = testFontweight(fontWeight, usedFontWeights);
  155. if (!test) {
  156. usedFontWeights = optionalUsedFonts.map(fontInfo => {
  157. fontInfo = Array.from(fontInfo);
  158. fontInfo[2] = "normal";
  159. return getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights);
  160. });
  161. }
  162. test = testFontweight(fontWeight, usedFontWeights);
  163. } else {
  164. test = true;
  165. }
  166. return test;
  167. }
  168. function testFontweight(fontWeight, usedFontWeights) {
  169. return fontWeight.split(",").find(weightValue => usedFontWeights.includes(singlefile.lib.helper.getFontWeight(singlefile.lib.helper.removeQuotes(weightValue))));
  170. }
  171. function getDeclarationValue(declarations, propertyName) {
  172. let property;
  173. if (declarations) {
  174. property = declarations.filter(declaration => declaration.property == propertyName).tail;
  175. }
  176. if (property) {
  177. try {
  178. return singlefile.lib.helper.removeQuotes(singlefile.lib.vendor.cssTree.generate(property.data.value));
  179. } catch (error) {
  180. // ignored
  181. }
  182. }
  183. }
  184. function getFontFamilyNames(declarations) {
  185. const cssTree = singlefile.lib.vendor.cssTree;
  186. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  187. let fontFamilyNames = [];
  188. if (fontFamilyName) {
  189. let familyName = "";
  190. if (fontFamilyName.data.value.children) {
  191. fontFamilyName.data.value.children.forEach(node => {
  192. if (node.type == "Operator" && node.value == "," && familyName) {
  193. fontFamilyNames.push(singlefile.lib.helper.normalizeFontFamily(familyName));
  194. familyName = "";
  195. } else {
  196. familyName += cssTree.generate(node);
  197. }
  198. });
  199. } else {
  200. fontFamilyName = cssTree.generate(fontFamilyName.data.value);
  201. }
  202. if (familyName) {
  203. fontFamilyNames.push(singlefile.lib.helper.normalizeFontFamily(familyName));
  204. }
  205. }
  206. const font = declarations.children.filter(node => node.property == "font").tail;
  207. if (font && font.data && font.data.value) {
  208. try {
  209. const parsedFont = singlefile.lib.vendor.fontPropertyParser.parse(cssTree.generate(font.data.value));
  210. parsedFont.family.forEach(familyName => fontFamilyNames.push(singlefile.lib.helper.normalizeFontFamily(familyName)));
  211. } catch (error) {
  212. // ignored
  213. }
  214. }
  215. return fontFamilyNames;
  216. }
  217. function getUsedFontWeight(fontInfo, fontStyle, fontWeights) {
  218. let foundWeight;
  219. if (fontInfo[2] == fontStyle) {
  220. let fontWeight = Number(fontInfo[1]);
  221. if (fontWeights.length > 1) {
  222. if (fontWeight >= 400 && fontWeight <= 500) {
  223. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  224. if (!foundWeight) {
  225. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  226. }
  227. if (!foundWeight) {
  228. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  229. }
  230. }
  231. if (fontWeight < 400) {
  232. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  233. if (!foundWeight) {
  234. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  235. }
  236. }
  237. if (fontWeight > 500) {
  238. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  239. if (!foundWeight) {
  240. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  241. }
  242. }
  243. } else {
  244. foundWeight = fontWeights[0];
  245. }
  246. }
  247. return foundWeight;
  248. }
  249. function findDescendingFontWeight(fontWeight, fontWeights) {
  250. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  251. }
  252. function findAscendingFontWeight(fontWeight, fontWeights) {
  253. return fontWeights.find(weight => weight > fontWeight);
  254. }
  255. function getRulesTextContent(doc, cssRules, workStylesheet, content) {
  256. cssRules.forEach(ruleData => {
  257. if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
  258. if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  259. content = getRulesTextContent(doc, ruleData.block.children, workStylesheet, content);
  260. } else if (ruleData.type == "Rule") {
  261. content = getDeclarationsTextContent(ruleData.block.children, workStylesheet, content);
  262. }
  263. }
  264. });
  265. return content;
  266. }
  267. function getDeclarationsTextContent(declarations, workStylesheet, content) {
  268. const contentText = getDeclarationUnescapedValue(declarations, "content", workStylesheet);
  269. const quotesText = getDeclarationUnescapedValue(declarations, "quotes", workStylesheet);
  270. if (!content.includes(contentText)) {
  271. content += contentText;
  272. }
  273. if (!content.includes(quotesText)) {
  274. content += quotesText;
  275. }
  276. return content;
  277. }
  278. function getDeclarationUnescapedValue(declarations, property, workStylesheet) {
  279. const rawValue = getDeclarationValue(declarations, property) || "";
  280. if (rawValue) {
  281. workStylesheet.textContent = "tmp { content:\"" + rawValue + "\"}";
  282. if (workStylesheet.sheet && workStylesheet.sheet.cssRules) {
  283. return singlefile.lib.helper.removeQuotes(workStylesheet.sheet.cssRules[0].style.getPropertyValue("content"));
  284. } else {
  285. return rawValue;
  286. }
  287. }
  288. return "";
  289. }
  290. function testUnicodeRange(docContent, unicodeRange) {
  291. if (unicodeRange) {
  292. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  293. let invalid;
  294. const result = unicodeRanges.filter(rangeValue => {
  295. const range = rangeValue.split(REGEXP_DASH);
  296. let regExpString;
  297. if (range.length == 2) {
  298. range[0] = transformRange(range[0]);
  299. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  300. }
  301. if (range.length == 1) {
  302. if (range[0].includes("?")) {
  303. const firstRange = transformRange(range[0]);
  304. const secondRange = firstRange;
  305. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  306. } else if (range[0]) {
  307. regExpString = "[" + transformRange(range[0]) + "]";
  308. }
  309. }
  310. if (regExpString) {
  311. try {
  312. return (new RegExp(regExpString, "u")).test(docContent);
  313. } catch (error) {
  314. invalid = true;
  315. return false;
  316. }
  317. }
  318. return true;
  319. });
  320. return !invalid && (!unicodeRanges.length || result.length);
  321. }
  322. return true;
  323. }
  324. function transformRange(range) {
  325. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  326. while (range.length < 6) {
  327. range = "0" + range;
  328. }
  329. return "\\u{" + range + "}";
  330. }
  331. })();