css-fonts-minifier.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. this.fontsMinifier = this.fontsMinifier || (() => {
  21. const REGEXP_COMMA = /\s*,\s*/;
  22. const REGEXP_DASH = /-/;
  23. const REGEXP_QUESTION_MARK = /\?/g;
  24. const REGEXP_STARTS_U_PLUS = /^U\+/i;
  25. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  26. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  27. const FONT_WEIGHTS = {
  28. normal: "400",
  29. bold: "700"
  30. };
  31. let cssTree, fontPropertyParser, docHelper;
  32. return {
  33. getInstance(...args) {
  34. [cssTree, fontPropertyParser, docHelper] = args;
  35. return {
  36. process: (doc, stylesheets, styles, options) => {
  37. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  38. const fontsInfo = { declared: [], used: [] };
  39. const workStyleElement = doc.createElement("style");
  40. let docContent = "";
  41. doc.body.appendChild(workStyleElement);
  42. stylesheets.forEach(stylesheetInfo => {
  43. const cssRules = stylesheetInfo.stylesheet.children;
  44. if (cssRules) {
  45. stats.processed += cssRules.getSize();
  46. stats.discarded += cssRules.getSize();
  47. getFontsInfo(cssRules, fontsInfo);
  48. docContent = getRulesTextContent(doc, cssRules, workStyleElement, docContent);
  49. }
  50. });
  51. styles.forEach(declarations => {
  52. const fontFamilyNames = getFontFamilyNames(declarations);
  53. if (fontFamilyNames.length) {
  54. fontsInfo.used.push(fontFamilyNames);
  55. }
  56. docContent = getDeclarationsTextContent(declarations.children, workStyleElement, docContent);
  57. });
  58. workStyleElement.remove();
  59. docContent += doc.body.innerText;
  60. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  61. let unusedFonts, filteredUsedFonts;
  62. if (variableFound) {
  63. unusedFonts = [];
  64. } else {
  65. filteredUsedFonts = new Map();
  66. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  67. if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
  68. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo[0] == familyName);
  69. filteredUsedFonts.set(familyName, optionalData);
  70. }
  71. }));
  72. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
  73. }
  74. stylesheets.forEach(stylesheetInfo => {
  75. const cssRules = stylesheetInfo.stylesheet.children;
  76. if (cssRules) {
  77. filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  78. stats.rules.discarded -= cssRules.getSize();
  79. }
  80. });
  81. return stats;
  82. }
  83. };
  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 cssTree.generate(property.data.value);
  161. } catch (error) {
  162. // ignored
  163. }
  164. }
  165. }
  166. function getFontFamilyNames(declarations) {
  167. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  168. let fontFamilyNames = [];
  169. if (fontFamilyName) {
  170. let familyName = "";
  171. if (fontFamilyName.data.value.children) {
  172. fontFamilyName.data.value.children.forEach(node => {
  173. if (node.type == "Operator" && node.value == "," && familyName) {
  174. fontFamilyNames.push(getFontFamily(familyName));
  175. familyName = "";
  176. } else {
  177. familyName += cssTree.generate(node);
  178. }
  179. });
  180. } else {
  181. fontFamilyName = cssTree.generate(fontFamilyName.data.value);
  182. }
  183. if (familyName) {
  184. fontFamilyNames.push(getFontFamily(familyName));
  185. }
  186. }
  187. const font = declarations.children.filter(node => node.property == "font").tail;
  188. if (font && font.data && font.data.value) {
  189. try {
  190. const parsedFont = fontPropertyParser.parse(cssTree.generate(font.data.value));
  191. parsedFont.family.forEach(familyName => fontFamilyNames.push(getFontFamily(familyName)));
  192. } catch (error) {
  193. // ignored
  194. }
  195. }
  196. return fontFamilyNames;
  197. }
  198. function findFontWeight(fontWeight, fontWeights) {
  199. let foundWeight;
  200. if (fontWeight >= 400 && fontWeight <= 500) {
  201. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  202. if (!foundWeight) {
  203. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  204. }
  205. if (!foundWeight) {
  206. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  207. }
  208. }
  209. if (fontWeight < 400) {
  210. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  211. if (!foundWeight) {
  212. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  213. }
  214. }
  215. if (fontWeight > 500) {
  216. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  217. if (!foundWeight) {
  218. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  219. }
  220. }
  221. return foundWeight;
  222. }
  223. function findDescendingFontWeight(fontWeight, fontWeights) {
  224. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  225. }
  226. function findAscendingFontWeight(fontWeight, fontWeights) {
  227. return fontWeights.find(weight => weight > fontWeight);
  228. }
  229. function getRulesTextContent(doc, cssRules, workStylesheet, content) {
  230. cssRules.forEach(ruleData => {
  231. if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
  232. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  233. content = getRulesTextContent(doc, ruleData.block.children, workStylesheet, content);
  234. } else if (ruleData.type == "Rule") {
  235. content = getDeclarationsTextContent(ruleData.block.children, workStylesheet, content);
  236. }
  237. }
  238. });
  239. return content;
  240. }
  241. function getDeclarationsTextContent(declarations, workStylesheet, content) {
  242. const contentText = getDeclarationUnescapedValue(declarations, "content", workStylesheet);
  243. const quotesText = getDeclarationUnescapedValue(declarations, "quotes", workStylesheet);
  244. if (!content.includes(contentText)) {
  245. content += contentText;
  246. }
  247. if (!content.includes(quotesText)) {
  248. content += quotesText;
  249. }
  250. return content;
  251. }
  252. function getDeclarationUnescapedValue(declarations, property, workStylesheet) {
  253. const rawValue = docHelper.removeQuotes(getDeclarationValue(declarations, property) || "");
  254. if (rawValue) {
  255. workStylesheet.textContent = "tmp { content:\"" + rawValue + "\"}";
  256. return docHelper.removeQuotes(workStylesheet.sheet.cssRules[0].style.getPropertyValue("content"));
  257. }
  258. return "";
  259. }
  260. function testFontVariant(fontInfo, fontVariant) {
  261. return fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures";
  262. }
  263. function testUnicodeRange(docContent, unicodeRange) {
  264. if (unicodeRange) {
  265. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  266. let invalid;
  267. const result = unicodeRanges.filter(rangeValue => {
  268. const range = rangeValue.split(REGEXP_DASH);
  269. let regExpString;
  270. if (range.length == 2) {
  271. range[0] = transformRange(range[0]);
  272. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  273. }
  274. if (range.length == 1) {
  275. if (range[0].includes("?")) {
  276. const firstRange = transformRange(range[0]);
  277. const secondRange = firstRange;
  278. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  279. } else {
  280. regExpString = "[" + transformRange(range[0]) + "]";
  281. }
  282. }
  283. if (regExpString) {
  284. try {
  285. return (new RegExp(regExpString, "u")).test(docContent);
  286. } catch (error) {
  287. invalid = true;
  288. return false;
  289. }
  290. }
  291. return true;
  292. });
  293. return !invalid && (!unicodeRanges.length || result.length);
  294. }
  295. return true;
  296. }
  297. function transformRange(range) {
  298. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  299. while (range.length < 6) {
  300. range = "0" + range;
  301. }
  302. return "\\u{" + range + "}";
  303. }
  304. function getFontFamily(string = "") {
  305. string = string.toLowerCase().trim();
  306. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  307. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  308. } else {
  309. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  310. }
  311. return string.trim();
  312. }
  313. function getFontWeight(weight) {
  314. return FONT_WEIGHTS[weight] || weight;
  315. }
  316. })();