css-fonts-minifier.js 13 KB

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