css-fonts-minifier.js 12 KB

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