css-fonts-minifier.js 13 KB

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