css-fonts-minifier.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 */
  21. this.fontsMinifier = this.fontsMinifier || (() => {
  22. const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
  23. const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
  24. const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
  25. const REGEXP_URL_FUNCTION = /(url|local)\(.*?\)\s*(,|$)/g;
  26. const REGEXP_COMMA = /\s*,\s*/;
  27. const REGEXP_DASH = /-/;
  28. const REGEXP_QUESTION_MARK = /\?/g;
  29. const REGEXP_STARTS_U_PLUS = /^U\+/i;
  30. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  31. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  32. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  33. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  34. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  35. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  36. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  37. const EMPTY_URL_SOURCE = "url(\"data:base64,\")";
  38. const PSEUDO_ELEMENTS = ["::after", "::before", "::first-line", "::first-letter", ":before", ":after", ":first-line", ":first-letter", "::placeholder", "::selection", "::marker", "::cue", "::slotted", "::spelling-error", "::grammar-error"];
  39. const FONT_WEIGHTS = {
  40. normal: "400",
  41. bold: "700"
  42. };
  43. const FONT_STRETCHES = {
  44. "ultra-condensed": "50%",
  45. "extra-condensed": "62.5%",
  46. "condensed": "75%",
  47. "semi-condensed": "87.5%",
  48. "normal": "100%",
  49. "semi-expanded": "112.5%",
  50. "expanded": "125%",
  51. "extra-expanded": "150%",
  52. "ultra-expanded": "200%"
  53. };
  54. return {
  55. removeUnusedFonts: (doc, stylesheets, styles, options) => {
  56. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  57. const fontsInfo = { declared: [], used: [] };
  58. let pseudoElementsContent = "";
  59. stylesheets.forEach(stylesheetInfo => {
  60. const cssRules = stylesheetInfo.stylesheet.children;
  61. stats.processed += cssRules.getSize();
  62. stats.discarded += cssRules.getSize();
  63. getFontsInfo(cssRules, fontsInfo);
  64. pseudoElementsContent += getPseudoElementsContent(cssRules);
  65. });
  66. styles.forEach(style => {
  67. const fontFamilyNames = getFontFamilyNames(style);
  68. if (fontFamilyNames.length) {
  69. fontsInfo.used.push(fontFamilyNames);
  70. }
  71. });
  72. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  73. let unusedFonts, filteredUsedFonts;
  74. if (variableFound) {
  75. unusedFonts = [];
  76. } else {
  77. filteredUsedFonts = new Map();
  78. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  79. if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
  80. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo.fontFamily == familyName);
  81. filteredUsedFonts.set(familyName, optionalData);
  82. }
  83. }));
  84. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
  85. }
  86. const docContent = doc.body.innerText + pseudoElementsContent;
  87. stylesheets.forEach(stylesheetInfo => {
  88. const cssRules = stylesheetInfo.stylesheet.children;
  89. filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  90. stats.rules.discarded -= cssRules.getSize();
  91. });
  92. return stats;
  93. },
  94. removeAlternativeFonts: (doc, stylesheets) => {
  95. const fontsDetails = new Map();
  96. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  97. stylesheets.forEach(stylesheetInfo => {
  98. const cssRules = stylesheetInfo.stylesheet.children;
  99. stats.rules.processed += cssRules.getSize();
  100. stats.rules.discarded += cssRules.getSize();
  101. getFontsDetails(doc, cssRules, fontsDetails);
  102. });
  103. processFontDetails(fontsDetails);
  104. stylesheets.forEach(stylesheetInfo => {
  105. const cssRules = stylesheetInfo.stylesheet.children;
  106. processFontFaceRules(cssRules, fontsDetails, "all", stats);
  107. stats.rules.discarded -= cssRules.getSize();
  108. });
  109. return stats;
  110. }
  111. };
  112. function processFontDetails(fontsDetails) {
  113. fontsDetails.forEach((fontInfo, fontKey) => {
  114. fontsDetails.set(fontKey, fontInfo.map(fontSource => {
  115. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  116. let fontFormat;
  117. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  118. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  119. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  120. const fontUrl = urlMatch && urlMatch[1];
  121. if (fontFormatMatch && fontFormatMatch[1]) {
  122. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  123. }
  124. if (!fontFormat) {
  125. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  126. if (fontFormatMatch && fontFormatMatch[1]) {
  127. fontFormat = fontFormatMatch[1];
  128. } else {
  129. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  130. if (fontFormatMatch && fontFormatMatch[1]) {
  131. fontFormat = fontFormatMatch[1];
  132. }
  133. }
  134. }
  135. if (!fontFormat && fontUrl) {
  136. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  137. if (fontFormatMatch && fontFormatMatch[1]) {
  138. fontFormat = fontFormatMatch[1];
  139. }
  140. }
  141. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  142. }));
  143. });
  144. }
  145. function getFontsInfo(cssRules, fontsInfo) {
  146. cssRules.forEach(cssRule => {
  147. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  148. getFontsInfo(cssRule.block.children, fontsInfo);
  149. } else if (cssRule.type == "Rule") {
  150. const fontFamilyNames = getFontFamilyNames(cssRule.block);
  151. if (fontFamilyNames.length) {
  152. fontsInfo.used.push(fontFamilyNames);
  153. }
  154. } else {
  155. if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  156. const fontFamily = getFontFamily(getPropertyValue(cssRule, "font-family"));
  157. if (fontFamily) {
  158. const fontWeight = getFontWeight(getPropertyValue(cssRule, "font-weight") || "400");
  159. const fontStyle = getPropertyValue(cssRule, "font-style") || "normal";
  160. const fontVariant = getPropertyValue(cssRule, "font-variant") || "normal";
  161. fontsInfo.declared.push({ fontFamily, fontWeight, fontStyle, fontVariant });
  162. }
  163. }
  164. }
  165. });
  166. }
  167. function getPropertyValue(cssRule, propertyName) {
  168. const property = cssRule.block.children.filter(node => node.property == propertyName).tail;
  169. if (property) {
  170. return cssTree.generate(property.data.value);
  171. }
  172. }
  173. function getFontFamilyNames(declarations) {
  174. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  175. let fontFamilyNames = [];
  176. if (fontFamilyName) {
  177. fontFamilyNames = fontFamilyName.data.value.children.filter(node => node.type == "String" || node.type == "Identifier").toArray().map(property => getFontFamily(cssTree.generate(property)));
  178. }
  179. const font = declarations.children.filter(node => node.property == "font").tail;
  180. if (font) {
  181. for (let node = font.data.value.children.tail; node && node.type != "WhiteSpace"; node = node.prev) {
  182. if (node.data.type == "String" || node.data.type == "Identifier") {
  183. fontFamilyNames.push(getFontFamily(cssTree.generate(node.data)));
  184. }
  185. }
  186. }
  187. return fontFamilyNames;
  188. }
  189. function getFontsDetails(doc, cssRules, fontsDetails) {
  190. cssRules.forEach(cssRule => {
  191. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  192. getFontsDetails(doc, cssRule.block.children, fontsDetails);
  193. } else {
  194. if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  195. const fontKey = getFontKey(cssRule);
  196. let fontInfo = fontsDetails.get(fontKey);
  197. if (!fontInfo) {
  198. fontInfo = [];
  199. fontsDetails.set(fontKey, fontInfo);
  200. }
  201. const src = getPropertyValue(cssRule, "src");
  202. if (src) {
  203. const fontSources = src.match(REGEXP_URL_FUNCTION);
  204. if (fontSources) {
  205. fontSources.forEach(source => fontInfo.unshift(source));
  206. }
  207. }
  208. }
  209. }
  210. });
  211. }
  212. function processFontFaceRules(cssRules, fontsDetails, media, stats) {
  213. cssRules.forEach(cssRule => {
  214. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  215. const mediaText = cssTree.generate(cssRule.prelude);
  216. processFontFaceRules(cssRule.block.children, fontsDetails, mediaText, stats);
  217. } else if (cssRule.type == "Atrule" && cssRule.name == "font-face" && (media.includes("all") || media.includes("screen"))) {
  218. const fontInfo = fontsDetails.get(getFontKey(cssRule));
  219. if (fontInfo) {
  220. fontsDetails.delete(getFontKey(cssRule));
  221. processFontFaceRule(cssRule, fontInfo, stats);
  222. }
  223. }
  224. });
  225. }
  226. function processFontFaceRule(cssRule, fontInfo, stats) {
  227. const fontTest = (fontSource, format) => !fontSource.src.startsWith(EMPTY_URL_SOURCE) && fontSource.format == format;
  228. let woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff2-variations"));
  229. if (!woffFontFound) {
  230. woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff2"));
  231. }
  232. if (!woffFontFound) {
  233. woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff"));
  234. }
  235. stats.fonts.processed += fontInfo.length;
  236. stats.fonts.discarded += fontInfo.length;
  237. if (woffFontFound) {
  238. fontInfo = [woffFontFound];
  239. } else {
  240. let ttfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "truetype-variations"));
  241. if (!ttfFontFound) {
  242. ttfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "truetype"));
  243. }
  244. if (ttfFontFound) {
  245. fontInfo = [ttfFontFound];
  246. } else {
  247. let otfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "opentype"));
  248. if (!otfFontFound) {
  249. otfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "embedded-opentype"));
  250. }
  251. if (otfFontFound) {
  252. fontInfo = [otfFontFound];
  253. }
  254. }
  255. }
  256. stats.fonts.discarded -= fontInfo.length;
  257. const removedNodes = [];
  258. for (let node = cssRule.block.children.head; node; node = node.next) {
  259. if (node.data.property == "src") {
  260. removedNodes.push(node);
  261. }
  262. }
  263. removedNodes.pop();
  264. removedNodes.forEach(node => cssRule.block.children.remove(node));
  265. const srcDeclaration = cssRule.block.children.filter(node => node.property == "src").tail;
  266. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  267. }
  268. function filterUnusedFonts(rules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  269. const removedRules = [];
  270. for (let rule = rules.head; rule; rule = rule.next) {
  271. const ruleData = rule.data;
  272. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  273. filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  274. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  275. const fontFamily = getFontFamily(getPropertyValue(ruleData, "font-family"));
  276. if (fontFamily) {
  277. const unicodeRange = getPropertyValue(ruleData, "unicode-range");
  278. if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
  279. removedRules.push(rule);
  280. }
  281. }
  282. }
  283. }
  284. removedRules.forEach(rule => rules.remove(rule));
  285. }
  286. function testUsedFont(rule, familyName, declaredFonts, filteredUsedFonts) {
  287. let test;
  288. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  289. if (optionalUsedFonts && optionalUsedFonts.length) {
  290. const fontStyle = getPropertyValue(rule, "font-style") || "normal";
  291. const fontWeight = getFontWeight(getPropertyValue(rule, "font-weight") || "400");
  292. const fontVariant = getPropertyValue(rule, "font-variant") || "normal";
  293. const declaredFontsWeights = declaredFonts
  294. .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle && testFontVariant(fontInfo, fontVariant))
  295. .map(fontInfo => fontInfo.fontWeight)
  296. .sort((weight1, weight2) => weight1 - weight2);
  297. const usedFontWeights = optionalUsedFonts.map(fontInfo => findFontWeight(fontInfo.fontWeight, declaredFontsWeights));
  298. test = usedFontWeights.includes(fontWeight);
  299. } else {
  300. test = true;
  301. }
  302. return test;
  303. }
  304. function findFontWeight(fontWeight, fontWeights) {
  305. let foundWeight;
  306. if (fontWeight >= 400 && fontWeight <= 500) {
  307. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  308. if (!foundWeight) {
  309. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  310. }
  311. if (!foundWeight) {
  312. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  313. }
  314. }
  315. if (fontWeight < 400) {
  316. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  317. if (!foundWeight) {
  318. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  319. }
  320. }
  321. if (fontWeight > 500) {
  322. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  323. if (!foundWeight) {
  324. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  325. }
  326. }
  327. return foundWeight;
  328. }
  329. function findDescendingFontWeight(fontWeight, fontWeights) {
  330. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  331. }
  332. function findAscendingFontWeight(fontWeight, fontWeights) {
  333. return fontWeights.find(weight => weight > fontWeight);
  334. }
  335. function getPseudoElementsContent(cssRules) {
  336. return cssRules.toArray().map(cssRule => {
  337. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  338. return getPseudoElementsContent(cssRule.block.children);
  339. } else if (cssRule.type == "Rule") {
  340. const selector = cssTree.generate(cssRule.prelude); // TODO use OM
  341. if (testPseudoElements(selector)) {
  342. return getPropertyValue(cssRule, "content");
  343. }
  344. }
  345. }).join("");
  346. }
  347. function testFontVariant(fontInfo, fontVariant) {
  348. return fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures";
  349. }
  350. function testUnicodeRange(docContent, unicodeRange) {
  351. if (unicodeRange) {
  352. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  353. let invalid;
  354. const result = unicodeRanges.filter(rangeValue => {
  355. const range = rangeValue.split(REGEXP_DASH);
  356. let regExpString;
  357. if (range.length == 2) {
  358. range[0] = transformRange(range[0]);
  359. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  360. }
  361. if (range.length == 1) {
  362. if (range[0].includes("?")) {
  363. const firstRange = transformRange(range[0]);
  364. const secondRange = firstRange;
  365. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  366. } else {
  367. regExpString = "[" + transformRange(range[0]) + "]";
  368. }
  369. }
  370. if (regExpString) {
  371. try {
  372. return (new RegExp(regExpString, "u")).test(docContent);
  373. } catch (error) {
  374. invalid = true;
  375. return false;
  376. }
  377. }
  378. return true;
  379. });
  380. return !invalid && (!unicodeRanges.length || result.length);
  381. }
  382. return true;
  383. }
  384. function testPseudoElements(selectorText) {
  385. let indexSelector = 0, found;
  386. selectorText = selectorText.toLowerCase();
  387. while (indexSelector < PSEUDO_ELEMENTS.length && !found) {
  388. found = selectorText.includes(PSEUDO_ELEMENTS[indexSelector]);
  389. if (!found) {
  390. indexSelector++;
  391. }
  392. }
  393. return found;
  394. }
  395. function transformRange(range) {
  396. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  397. while (range.length < 6) {
  398. range = "0" + range;
  399. }
  400. return "\\u{" + range + "}";
  401. }
  402. function getFontKey(cssRule) {
  403. return JSON.stringify([
  404. getFontFamily(getPropertyValue(cssRule, "font-family")),
  405. getFontWeight(getPropertyValue(cssRule, "font-weight") || "400"),
  406. getPropertyValue(cssRule, "font-style") || "normal",
  407. getPropertyValue(cssRule, "unicode-range"),
  408. getFontStretch(getPropertyValue(cssRule, "font-stretch")),
  409. getPropertyValue(cssRule, "font-variant") || "normal",
  410. getPropertyValue(cssRule, "font-feature-settings"),
  411. getPropertyValue(cssRule, "font-variation-settings")
  412. ]);
  413. }
  414. function getFontFamily(string) {
  415. string = string.toLowerCase().trim();
  416. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  417. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  418. } else {
  419. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  420. }
  421. return string.trim();
  422. }
  423. function getFontWeight(weight) {
  424. return FONT_WEIGHTS[weight] || weight;
  425. }
  426. function getFontStretch(stretch) {
  427. return FONT_STRETCHES[stretch] || stretch;
  428. }
  429. })();