css-fonts-minifier.js 13 KB

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