css-fonts-minifier.js 12 KB

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