css-fonts-minifier.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. normal: "400",
  35. bold: "700",
  36. bolder: "700",
  37. lighter: "100"
  38. };
  39. return {
  40. process: (doc, stylesheets, styles, options) => {
  41. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  42. const fontsInfo = { declared: [], used: [] };
  43. const workStyleElement = doc.createElement("style");
  44. let docContent = "";
  45. doc.body.appendChild(workStyleElement);
  46. stylesheets.forEach(stylesheetInfo => {
  47. const cssRules = stylesheetInfo.stylesheet.children;
  48. if (cssRules) {
  49. stats.processed += cssRules.getSize();
  50. stats.discarded += cssRules.getSize();
  51. getFontsInfo(cssRules, fontsInfo);
  52. docContent = getRulesTextContent(doc, cssRules, workStyleElement, docContent);
  53. }
  54. });
  55. styles.forEach(declarations => {
  56. const fontFamilyNames = getFontFamilyNames(declarations);
  57. if (fontFamilyNames.length) {
  58. fontsInfo.used.push(fontFamilyNames);
  59. }
  60. docContent = getDeclarationsTextContent(declarations.children, workStyleElement, docContent);
  61. });
  62. workStyleElement.remove();
  63. docContent += doc.body.innerText;
  64. if (getComputedStyle) {
  65. fontsInfo.used = fontsInfo.used.map(fontNames => fontNames.map(familyName => {
  66. const matchedVar = familyName.match(/^var\((--.*)\)$/);
  67. if (matchedVar && matchedVar[1]) {
  68. const computedFamilyName = getComputedStyle.call(window, options.doc.body).getPropertyValue(matchedVar[1]);
  69. return (computedFamilyName && computedFamilyName.split(",").map(name => getFontFamily(name))) || familyName;
  70. }
  71. return familyName;
  72. }));
  73. fontsInfo.used = fontsInfo.used.map(fontNames => fontNames.flat());
  74. }
  75. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  76. let unusedFonts, filteredUsedFonts;
  77. if (variableFound) {
  78. unusedFonts = [];
  79. } else {
  80. filteredUsedFonts = new Map();
  81. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  82. if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
  83. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo[0] == familyName);
  84. if (optionalData && optionalData.length) {
  85. filteredUsedFonts.set(familyName, optionalData);
  86. }
  87. }
  88. }));
  89. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
  90. }
  91. stylesheets.forEach(stylesheetInfo => {
  92. const cssRules = stylesheetInfo.stylesheet.children;
  93. if (cssRules) {
  94. filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  95. stats.rules.discarded -= cssRules.getSize();
  96. }
  97. });
  98. return stats;
  99. }
  100. };
  101. function getFontsInfo(cssRules, fontsInfo) {
  102. cssRules.forEach(ruleData => {
  103. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children) {
  104. getFontsInfo(ruleData.block.children, fontsInfo);
  105. } else if (ruleData.type == "Rule") {
  106. const fontFamilyNames = getFontFamilyNames(ruleData.block);
  107. if (fontFamilyNames.length) {
  108. fontsInfo.used.push(fontFamilyNames);
  109. }
  110. } else {
  111. if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  112. const fontFamily = getFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
  113. if (fontFamily) {
  114. const fontWeight = getFontWeight(getDeclarationValue(ruleData.block.children, "font-weight") || "400");
  115. const fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
  116. const fontVariant = getDeclarationValue(ruleData.block.children, "font-variant") || "normal";
  117. fontsInfo.declared.push({ fontFamily, fontWeight, fontStyle, fontVariant });
  118. }
  119. }
  120. }
  121. });
  122. }
  123. function filterUnusedFonts(cssRules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  124. const removedRules = [];
  125. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  126. const ruleData = cssRule.data;
  127. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children) {
  128. filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  129. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  130. const fontFamily = getFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
  131. if (fontFamily) {
  132. const unicodeRange = getDeclarationValue(ruleData.block.children, "unicode-range");
  133. if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
  134. removedRules.push(cssRule);
  135. }
  136. }
  137. const removedDeclarations = [];
  138. for (let declaration = ruleData.block.children.head; declaration; declaration = declaration.next) {
  139. if (declaration.data.property == "font-display") {
  140. removedDeclarations.push(declaration);
  141. }
  142. }
  143. if (removedDeclarations.length) {
  144. removedDeclarations.forEach(removedDeclaration => ruleData.block.children.remove(removedDeclaration));
  145. }
  146. }
  147. }
  148. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  149. }
  150. function testUsedFont(ruleData, familyName, declaredFonts, filteredUsedFonts) {
  151. let test;
  152. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  153. if (optionalUsedFonts && optionalUsedFonts.length) {
  154. const fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
  155. const fontWeight = getFontWeight(getDeclarationValue(ruleData.block.children, "font-weight") || "400");
  156. const fontVariant = getDeclarationValue(ruleData.block.children, "font-variant") || "normal";
  157. const declaredFontsWeights = declaredFonts
  158. .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle && testFontVariant(fontInfo, fontVariant))
  159. .map(fontInfo => fontInfo.fontWeight)
  160. .sort((weight1, weight2) => weight1 - weight2);
  161. const usedFontWeights = optionalUsedFonts.map(fontInfo => getUsedFontWeight(fontInfo, fontStyle, fontVariant, 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.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, fontVariant, fontWeights) {
  215. let foundWeight;
  216. if (fontInfo[2] == fontStyle && fontInfo[3] == fontVariant) {
  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 helper = singlefile.lib.helper;
  273. const rawValue = helper.removeQuotes(getDeclarationValue(declarations, property) || "");
  274. if (rawValue) {
  275. workStylesheet.textContent = "tmp { content:\"" + rawValue + "\"}";
  276. if (workStylesheet.sheet && workStylesheet.sheet.cssRules) {
  277. return helper.removeQuotes(workStylesheet.sheet.cssRules[0].style.getPropertyValue("content"));
  278. } else {
  279. return rawValue;
  280. }
  281. }
  282. return "";
  283. }
  284. function testFontVariant(fontInfo, fontVariant) {
  285. return fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures";
  286. }
  287. function testUnicodeRange(docContent, unicodeRange) {
  288. if (unicodeRange) {
  289. unicodeRange = singlefile.lib.helper.removeQuotes(unicodeRange);
  290. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  291. let invalid;
  292. const result = unicodeRanges.filter(rangeValue => {
  293. const range = rangeValue.split(REGEXP_DASH);
  294. let regExpString;
  295. if (range.length == 2) {
  296. range[0] = transformRange(range[0]);
  297. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  298. }
  299. if (range.length == 1) {
  300. if (range[0].includes("?")) {
  301. const firstRange = transformRange(range[0]);
  302. const secondRange = firstRange;
  303. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  304. } else if (range[0]) {
  305. regExpString = "[" + transformRange(range[0]) + "]";
  306. }
  307. }
  308. if (regExpString) {
  309. try {
  310. return (new RegExp(regExpString, "u")).test(docContent);
  311. } catch (error) {
  312. invalid = true;
  313. return false;
  314. }
  315. }
  316. return true;
  317. });
  318. return !invalid && (!unicodeRanges.length || result.length);
  319. }
  320. return true;
  321. }
  322. function transformRange(range) {
  323. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  324. while (range.length < 6) {
  325. range = "0" + range;
  326. }
  327. return "\\u{" + range + "}";
  328. }
  329. function getFontFamily(string = "") {
  330. string = string.toLowerCase().trim();
  331. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  332. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  333. } else {
  334. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  335. }
  336. return string.trim().replace(/\\+ +/gi, " ");
  337. }
  338. function getFontWeight(weight) {
  339. return FONT_WEIGHTS[weight] || weight;
  340. }
  341. })();