css-fonts-minifier.js 12 KB

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