css-fonts-minifier.js 14 KB

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