css-fonts-minifier.js 12 KB

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