css-fonts-minifier.js 13 KB

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