css-fonts-minifier.js 13 KB

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