css-fonts-minifier.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 CSSRule */
  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, options) => {
  56. const stats = {
  57. rules: {
  58. processed: 0,
  59. discarded: 0
  60. },
  61. fonts: {
  62. processed: 0,
  63. discarded: 0
  64. }
  65. };
  66. const fontsInfo = { declared: [], used: [] };
  67. let pseudoElementsContent = "";
  68. doc.querySelectorAll("style").forEach(style => {
  69. if (style.sheet) {
  70. stats.rules.processed += style.sheet.cssRules.length;
  71. stats.rules.discarded += style.sheet.cssRules.length;
  72. getFontsInfo(doc, style.sheet.cssRules, fontsInfo);
  73. pseudoElementsContent += getPseudoElementsContent(doc, style.sheet.cssRules);
  74. }
  75. });
  76. doc.querySelectorAll("[style]").forEach(element => {
  77. if (element.style && element.style.fontFamily) {
  78. const fontFamilyNames = element.style.fontFamily.split(",").map(fontFamilyName => removeQuotes(fontFamilyName));
  79. fontsInfo.used.push(fontFamilyNames);
  80. }
  81. });
  82. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  83. let unusedFonts, filteredUsedFonts;
  84. if (variableFound) {
  85. unusedFonts = [];
  86. } else {
  87. filteredUsedFonts = new Map();
  88. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  89. if (fontsInfo.declared.find(fontInfo => fontInfo.familyName == familyName)) {
  90. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo.fontFamily == familyName);
  91. filteredUsedFonts.set(familyName, optionalData);
  92. }
  93. }));
  94. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.familyName));
  95. }
  96. const docContent = doc.body.innerText + pseudoElementsContent;
  97. doc.querySelectorAll("style").forEach(style => {
  98. if (style.sheet) {
  99. style.textContent = filterUnusedFonts(doc, style.sheet.cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  100. stats.rules.discarded -= style.sheet.cssRules.length;
  101. }
  102. });
  103. return stats;
  104. },
  105. removeAlternativeFonts: doc => {
  106. const fontsDetails = new Map();
  107. const stats = {
  108. rules: {
  109. processed: 0,
  110. discarded: 0
  111. },
  112. fonts: {
  113. processed: 0,
  114. discarded: 0
  115. }
  116. };
  117. doc.querySelectorAll("style").forEach(style => {
  118. if (style.sheet) {
  119. stats.rules.processed += style.sheet.cssRules.length;
  120. stats.rules.discarded += style.sheet.cssRules.length;
  121. getFontsDetails(doc, style.sheet.cssRules, fontsDetails);
  122. }
  123. });
  124. processFontDetails(fontsDetails);
  125. doc.querySelectorAll("style").forEach(style => {
  126. if (style.sheet) {
  127. style.textContent = processFontFaceRules(style.sheet.cssRules, fontsDetails, "all", stats);
  128. stats.rules.discarded -= style.sheet.cssRules.length;
  129. }
  130. });
  131. return stats;
  132. }
  133. };
  134. function processFontDetails(fontsDetails) {
  135. fontsDetails.forEach((fontInfo, fontKey) => {
  136. fontsDetails.set(fontKey, fontInfo.map(fontSource => {
  137. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  138. let fontFormat;
  139. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  140. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  141. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  142. const fontUrl = urlMatch && urlMatch[1];
  143. if (fontFormatMatch && fontFormatMatch[1]) {
  144. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  145. }
  146. if (!fontFormat) {
  147. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  148. if (fontFormatMatch && fontFormatMatch[1]) {
  149. fontFormat = fontFormatMatch[1];
  150. } else {
  151. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  152. if (fontFormatMatch && fontFormatMatch[1]) {
  153. fontFormat = fontFormatMatch[1];
  154. }
  155. }
  156. }
  157. if (!fontFormat && fontUrl) {
  158. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  159. if (fontFormatMatch && fontFormatMatch[1]) {
  160. fontFormat = fontFormatMatch[1];
  161. }
  162. }
  163. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  164. }));
  165. });
  166. }
  167. function getFontsInfo(doc, rules, fontsInfo) {
  168. if (rules) {
  169. Array.from(rules).forEach(rule => {
  170. if (rule.type == CSSRule.MEDIA_RULE) {
  171. getFontsInfo(doc, rule.cssRules, fontsInfo);
  172. } else if (rule.type == CSSRule.STYLE_RULE) {
  173. if (rule.style && rule.style.fontFamily) {
  174. const fontFamilyNames = rule.style.fontFamily.split(",").map(fontFamilyName => removeQuotes(fontFamilyName));
  175. fontsInfo.used.push(fontFamilyNames);
  176. }
  177. } else {
  178. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  179. const familyName = removeQuotes(rule.style.getPropertyValue("font-family"));
  180. const fontWeight = getFontWeight(rule.style.getPropertyValue("font-weight")) || "400";
  181. const fontStyle = rule.style.getPropertyValue("font-style") || "normal";
  182. const fontVariant = rule.style.getPropertyValue("font-variant") || "normal";
  183. if (familyName) {
  184. fontsInfo.declared.push({ familyName, fontWeight, fontStyle, fontVariant });
  185. }
  186. }
  187. }
  188. });
  189. }
  190. }
  191. function getFontsDetails(doc, rules, fontsDetails) {
  192. if (rules) {
  193. Array.from(rules).forEach(rule => {
  194. if (rule.type == CSSRule.MEDIA_RULE) {
  195. getFontsDetails(doc, rule.cssRules, fontsDetails);
  196. } else {
  197. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  198. const fontKey = getFontKey(rule.style);
  199. let fontInfo = fontsDetails.get(fontKey);
  200. if (!fontInfo) {
  201. fontInfo = [];
  202. fontsDetails.set(fontKey, fontInfo);
  203. }
  204. const src = rule.style.getPropertyValue("src");
  205. if (src) {
  206. const fontSources = src.match(REGEXP_URL_FUNCTION);
  207. if (fontSources) {
  208. fontSources.forEach(source => fontInfo.unshift(source));
  209. }
  210. }
  211. }
  212. }
  213. });
  214. }
  215. }
  216. function processFontFaceRules(rules, fontsDetails, media, stats) {
  217. let stylesheetContent = "";
  218. Array.from(rules).forEach(rule => {
  219. if (rule.type == CSSRule.MEDIA_RULE) {
  220. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  221. stylesheetContent += processFontFaceRules(rule.cssRules, fontsDetails, rule.media.mediaText, stats);
  222. stylesheetContent += "}";
  223. } else if (rule.type == CSSRule.FONT_FACE_RULE && (media.includes("all") || media.includes("screen"))) {
  224. const fontInfo = fontsDetails.get(getFontKey(rule.style));
  225. if (fontInfo) {
  226. fontsDetails.delete(getFontKey(rule.style));
  227. stylesheetContent += "@font-face {" + processFontFaceRule(rule, fontInfo, stats) + "}";
  228. }
  229. } else {
  230. stylesheetContent += rule.cssText;
  231. }
  232. });
  233. return stylesheetContent;
  234. }
  235. function processFontFaceRule(rule, fontInfo, stats) {
  236. const fontTest = (fontSource, format) => !fontSource.src.startsWith(EMPTY_URL_SOURCE) && fontSource.format == format;
  237. let woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff2-variations"));
  238. if (!woffFontFound) {
  239. woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff2"));
  240. }
  241. if (!woffFontFound) {
  242. woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff"));
  243. }
  244. stats.fonts.processed += fontInfo.length;
  245. stats.fonts.discarded += fontInfo.length;
  246. if (woffFontFound) {
  247. fontInfo = [woffFontFound];
  248. } else {
  249. let ttfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "truetype-variations"));
  250. if (!ttfFontFound) {
  251. ttfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "truetype"));
  252. }
  253. if (ttfFontFound) {
  254. fontInfo = [ttfFontFound];
  255. } else {
  256. let otfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "opentype"));
  257. if (!otfFontFound) {
  258. otfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "embedded-opentype"));
  259. }
  260. if (otfFontFound) {
  261. fontInfo = [otfFontFound];
  262. }
  263. }
  264. }
  265. stats.fonts.discarded -= fontInfo.length;
  266. let cssText = "";
  267. Array.from(rule.style).forEach(propertyName => {
  268. cssText += propertyName + ":";
  269. if (propertyName == "src") {
  270. cssText += fontInfo.map(fontSource => fontSource.src).join(",");
  271. } else {
  272. cssText += rule.style.getPropertyValue(propertyName);
  273. }
  274. cssText += ";";
  275. });
  276. return cssText;
  277. }
  278. function filterUnusedFonts(doc, rules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  279. let stylesheetContent = "";
  280. if (rules) {
  281. Array.from(rules).forEach(rule => {
  282. if (rule.media) {
  283. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  284. stylesheetContent += filterUnusedFonts(doc, rule.cssRules, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  285. stylesheetContent += "}";
  286. } else if (rule.type == CSSRule.FONT_FACE_RULE) {
  287. if (rule.style) {
  288. const familyName = removeQuotes(rule.style.getPropertyValue("font-family"));
  289. if (familyName && !unusedFonts.find(fontInfo => fontInfo.familyName == familyName)) {
  290. if (testUnicodeRange(docContent, rule.style.getPropertyValue("unicode-range")) && testUsedFont(rule, familyName, declaredFonts, filteredUsedFonts)) {
  291. stylesheetContent += rule.cssText;
  292. }
  293. }
  294. }
  295. } else {
  296. stylesheetContent += rule.cssText;
  297. }
  298. });
  299. }
  300. return stylesheetContent;
  301. }
  302. function testUsedFont(rule, familyName, declaredFonts, filteredUsedFonts) {
  303. let test;
  304. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  305. if (optionalUsedFonts && optionalUsedFonts.length) {
  306. const fontStyle = rule.style.getPropertyValue("font-style") || "normal";
  307. const fontWeight = getFontWeight(rule.style.getPropertyValue("font-weight")) || "400";
  308. const fontVariant = rule.style.getPropertyValue("font-variant") || "normal";
  309. const declaredFontsWeights = declaredFonts
  310. .filter(fontInfo => fontInfo.familyName == familyName && fontInfo.fontStyle == fontStyle && testFontVariant(fontInfo, fontVariant))
  311. .map(fontInfo => fontInfo.fontWeight)
  312. .sort((weight1, weight2) => weight1 - weight2);
  313. const usedFontWeights = optionalUsedFonts.map(fontInfo => findFontWeight(fontInfo.fontWeight, declaredFontsWeights));
  314. test = usedFontWeights.includes(fontWeight);
  315. } else {
  316. test = true;
  317. }
  318. return test;
  319. }
  320. function findFontWeight(fontWeight, fontWeights) {
  321. let foundWeight;
  322. if (fontWeight >= 400 && fontWeight <= 500) {
  323. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  324. if (!foundWeight) {
  325. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  326. }
  327. if (!foundWeight) {
  328. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  329. }
  330. }
  331. if (fontWeight < 400) {
  332. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  333. if (!foundWeight) {
  334. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  335. }
  336. }
  337. if (fontWeight > 500) {
  338. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  339. if (!foundWeight) {
  340. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  341. }
  342. }
  343. return foundWeight;
  344. }
  345. function findDescendingFontWeight(fontWeight, fontWeights) {
  346. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  347. }
  348. function findAscendingFontWeight(fontWeight, fontWeights) {
  349. return fontWeights.find(weight => weight > fontWeight);
  350. }
  351. function getPseudoElementsContent(doc, rules) {
  352. if (rules) {
  353. return Array.from(rules).map(rule => {
  354. if (rule.type == CSSRule.MEDIA_RULE) {
  355. return getPseudoElementsContent(doc, rule.cssRules);
  356. } else if (rule.type == CSSRule.STYLE_RULE && testPseudoElements(rule.selectorText)) {
  357. let content = rule.style.getPropertyValue("content");
  358. content = content && removeQuotes(content);
  359. return content;
  360. }
  361. }).join("");
  362. } else {
  363. return "";
  364. }
  365. }
  366. function testFontVariant(fontInfo, fontVariant) {
  367. return fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures";
  368. }
  369. function testUnicodeRange(docContent, unicodeRange) {
  370. if (unicodeRange) {
  371. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  372. const result = unicodeRanges.filter(rangeValue => {
  373. const range = rangeValue.split(REGEXP_DASH);
  374. if (range.length == 2) {
  375. range[0] = transformRange(range[0]);
  376. const regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  377. return (new RegExp(regExpString, "u")).test(docContent);
  378. }
  379. if (range.length == 1) {
  380. if (range[0].includes("?")) {
  381. const firstRange = transformRange(range[0]);
  382. const secondRange = firstRange;
  383. const regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  384. return (new RegExp(regExpString, "u")).test(docContent);
  385. } else {
  386. const regExpString = "[" + transformRange(range[0]) + "]";
  387. return (new RegExp(regExpString, "u")).test(docContent);
  388. }
  389. }
  390. return true;
  391. });
  392. return result.length;
  393. }
  394. return true;
  395. }
  396. function testPseudoElements(selectorText) {
  397. let indexSelector = 0, found;
  398. selectorText = selectorText.toLowerCase();
  399. while (indexSelector < PSEUDO_ELEMENTS.length && !found) {
  400. found = selectorText.includes(PSEUDO_ELEMENTS[indexSelector]);
  401. if (!found) {
  402. indexSelector++;
  403. }
  404. }
  405. return found;
  406. }
  407. function transformRange(range) {
  408. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  409. while (range.length < 6) {
  410. range = "0" + range;
  411. }
  412. return "\\u{" + range + "}";
  413. }
  414. function getFontKey(style) {
  415. return JSON.stringify([
  416. removeQuotes(style.getPropertyValue("font-family")),
  417. getFontWeight(style.getPropertyValue("font-weight")),
  418. style.getPropertyValue("font-style"),
  419. style.getPropertyValue("unicode-range"),
  420. getFontStretch(style.getPropertyValue("font-stretch")),
  421. style.getPropertyValue("font-variant"),
  422. style.getPropertyValue("font-feature-settings"),
  423. style.getPropertyValue("font-variation-settings")
  424. ]);
  425. }
  426. function removeQuotes(string) {
  427. string = string.toLowerCase().trim();
  428. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  429. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  430. } else {
  431. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  432. }
  433. return string.trim();
  434. }
  435. function getFontWeight(weight) {
  436. return FONT_WEIGHTS[weight] || weight;
  437. }
  438. function getFontStretch(stretch) {
  439. return FONT_STRETCHES[stretch] || stretch;
  440. }
  441. })();