css-fonts-minifier.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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.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, 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. doc.querySelectorAll("style").forEach(style => {
  125. if (style.sheet) {
  126. style.textContent = processFontFaceRules(style.sheet.cssRules, fontsDetails, "all", stats);
  127. stats.rules.discarded -= style.sheet.cssRules.length;
  128. }
  129. });
  130. return stats;
  131. }
  132. };
  133. function getFontsInfo(doc, rules, fontsInfo) {
  134. if (rules) {
  135. Array.from(rules).forEach(rule => {
  136. if (rule.type == CSSRule.MEDIA_RULE) {
  137. getFontsInfo(doc, rule.cssRules, fontsInfo);
  138. } else if (rule.type == CSSRule.STYLE_RULE) {
  139. if (rule.style && rule.style.fontFamily) {
  140. const fontFamilyNames = rule.style.fontFamily.split(",").map(fontFamilyName => removeQuotes(fontFamilyName));
  141. fontsInfo.used.push(fontFamilyNames);
  142. }
  143. } else {
  144. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  145. const familyName = removeQuotes(rule.style.getPropertyValue("font-family"));
  146. const fontWeight = getFontWeight(rule.style.getPropertyValue("font-weight")) || "400";
  147. const fontStyle = rule.style.getPropertyValue("font-style") || "normal";
  148. const fontVariant = rule.style.getPropertyValue("font-variant") || "normal";
  149. if (familyName) {
  150. fontsInfo.declared.push({ familyName, fontWeight, fontStyle, fontVariant });
  151. }
  152. }
  153. }
  154. });
  155. }
  156. }
  157. function getFontsDetails(doc, rules, fontsDetails) {
  158. if (rules) {
  159. Array.from(rules).forEach(rule => {
  160. if (rule.type == CSSRule.MEDIA_RULE) {
  161. getFontsDetails(doc, rule.cssRules, fontsDetails);
  162. } else {
  163. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  164. const fontKey = getFontKey(rule.style);
  165. let fontInfo = fontsDetails.get(fontKey);
  166. if (!fontInfo) {
  167. fontInfo = [];
  168. fontsDetails.set(fontKey, fontInfo);
  169. }
  170. const src = rule.style.getPropertyValue("src");
  171. if (src) {
  172. const fontSources = src.match(REGEXP_URL_FUNCTION);
  173. if (fontSources) {
  174. fontSources.forEach(source => fontInfo.unshift(source));
  175. }
  176. }
  177. }
  178. }
  179. });
  180. }
  181. }
  182. function processFontFaceRules(rules, fontsDetails, media, stats) {
  183. let stylesheetContent = "";
  184. Array.from(rules).forEach(rule => {
  185. if (rule.type == CSSRule.MEDIA_RULE) {
  186. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  187. stylesheetContent += processFontFaceRules(rule.cssRules, fontsDetails, rule.media.mediaText, stats);
  188. stylesheetContent += "}";
  189. } else if (rule.type == CSSRule.FONT_FACE_RULE && (media.includes("all") || media.includes("screen"))) {
  190. const fontInfo = fontsDetails.get(getFontKey(rule.style));
  191. if (fontInfo) {
  192. fontsDetails.delete(getFontKey(rule.style));
  193. stylesheetContent += "@font-face {" + processFontFaceRule(rule, fontInfo, stats) + "}";
  194. }
  195. } else {
  196. stylesheetContent += rule.cssText;
  197. }
  198. });
  199. return stylesheetContent;
  200. }
  201. function processFontFaceRule(rule, fontInfo, stats) {
  202. let fontSources = fontInfo.map(fontSource => {
  203. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  204. let fontFormat;
  205. if (fontFormatMatch && fontFormatMatch[1]) {
  206. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  207. }
  208. if (!fontFormat) {
  209. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  210. if (fontFormatMatch && fontFormatMatch[1]) {
  211. fontFormat = fontFormatMatch[1];
  212. } else {
  213. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  214. if (fontFormatMatch && fontFormatMatch[1]) {
  215. fontFormat = fontFormatMatch[1];
  216. }
  217. }
  218. }
  219. if (!fontFormat) {
  220. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  221. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  222. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  223. const fontUrl = urlMatch && urlMatch[1];
  224. if (fontUrl) {
  225. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  226. if (fontFormatMatch && fontFormatMatch[1]) {
  227. fontFormat = fontFormatMatch[1];
  228. }
  229. }
  230. }
  231. return { src: fontSource.match(REGEXP_FONT_SRC)[1], format: fontFormat };
  232. });
  233. const fontTest = (fontSource, format) => !fontSource.src.startsWith(EMPTY_URL_SOURCE) && fontSource.format == format;
  234. let woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2-variations"));
  235. if (!woffFontFound) {
  236. woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2"));
  237. }
  238. if (!woffFontFound) {
  239. woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff"));
  240. }
  241. stats.fonts.processed += fontSources.length;
  242. stats.fonts.discarded += fontSources.length;
  243. if (woffFontFound) {
  244. fontSources = [woffFontFound];
  245. } else {
  246. let ttfFontFound = fontSources.find(fontSource => fontTest(fontSource, "truetype-variations"));
  247. if (!ttfFontFound) {
  248. ttfFontFound = fontSources.find(fontSource => fontTest(fontSource, "truetype"));
  249. }
  250. if (ttfFontFound) {
  251. fontSources = [ttfFontFound];
  252. } else {
  253. let otfFontFound = fontSources.find(fontSource => fontTest(fontSource, "opentype"));
  254. if (!otfFontFound) {
  255. otfFontFound = fontSources.find(fontSource => fontTest(fontSource, "embedded-opentype"));
  256. }
  257. if (otfFontFound) {
  258. fontSources = [otfFontFound];
  259. }
  260. }
  261. }
  262. stats.fonts.discarded -= fontSources.length;
  263. let cssText = "";
  264. Array.from(rule.style).forEach(propertyName => {
  265. cssText += propertyName + ":";
  266. if (propertyName == "src") {
  267. cssText += fontSources.map(fontSource => fontSource.src).join(",");
  268. } else {
  269. cssText += rule.style.getPropertyValue(propertyName);
  270. }
  271. cssText += ";";
  272. });
  273. return cssText;
  274. }
  275. function filterUnusedFonts(doc, rules, unusedFonts, filteredUsedFonts, docContent) {
  276. let stylesheetContent = "";
  277. if (rules) {
  278. Array.from(rules).forEach(rule => {
  279. if (rule.media) {
  280. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  281. stylesheetContent += filterUnusedFonts(doc, rule.cssRules, unusedFonts, filteredUsedFonts, docContent);
  282. stylesheetContent += "}";
  283. } else if (rule.type == CSSRule.FONT_FACE_RULE) {
  284. if (rule.style) {
  285. const fontFamily = removeQuotes(rule.style.getPropertyValue("font-family"));
  286. if (fontFamily && !unusedFonts.includes(fontFamily)) {
  287. let optionalTest;
  288. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(fontFamily);
  289. if (optionalUsedFonts && optionalUsedFonts.length) {
  290. const fontStyle = rule.style.getPropertyValue("font-style") || "normal";
  291. optionalTest = optionalUsedFonts.find(fontInfo => fontInfo.fontStyle == fontStyle);
  292. if (optionalTest) {
  293. const fontVariant = rule.style.getPropertyValue("font-variant");
  294. optionalTest = optionalUsedFonts.find(fontInfo => fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures");
  295. }
  296. } else {
  297. optionalTest = true;
  298. }
  299. if (testUnicodeRange(docContent, rule.style.getPropertyValue("unicode-range")) && optionalTest) {
  300. stylesheetContent += rule.cssText;
  301. }
  302. }
  303. }
  304. } else {
  305. stylesheetContent += rule.cssText;
  306. }
  307. });
  308. }
  309. return stylesheetContent;
  310. }
  311. function getPseudoElementsContent(doc, rules) {
  312. if (rules) {
  313. return Array.from(rules).map(rule => {
  314. if (rule.type == CSSRule.MEDIA_RULE) {
  315. return getPseudoElementsContent(doc, rule.cssRules);
  316. } else if (rule.type == CSSRule.STYLE_RULE && testPseudoElements(rule.selectorText)) {
  317. let content = rule.style.getPropertyValue("content");
  318. content = content && removeQuotes(content);
  319. return content;
  320. }
  321. }).join("");
  322. } else {
  323. return "";
  324. }
  325. }
  326. function testUnicodeRange(docContent, unicodeRange) {
  327. if (unicodeRange) {
  328. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  329. const result = unicodeRanges.filter(rangeValue => {
  330. const range = rangeValue.split(REGEXP_DASH);
  331. if (range.length == 2) {
  332. range[0] = transformRange(range[0]);
  333. const regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  334. return (new RegExp(regExpString, "u")).test(docContent);
  335. }
  336. if (range.length == 1) {
  337. if (range[0].includes("?")) {
  338. const firstRange = transformRange(range[0]);
  339. const secondRange = firstRange;
  340. const regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  341. return (new RegExp(regExpString, "u")).test(docContent);
  342. } else {
  343. const regExpString = "[" + transformRange(range[0]) + "]";
  344. return (new RegExp(regExpString, "u")).test(docContent);
  345. }
  346. }
  347. return true;
  348. });
  349. return result.length;
  350. }
  351. return true;
  352. }
  353. function testPseudoElements(selectorText) {
  354. let indexSelector = 0, found;
  355. selectorText = selectorText.toLowerCase();
  356. while (indexSelector < PSEUDO_ELEMENTS.length && !found) {
  357. found = selectorText.includes(PSEUDO_ELEMENTS[indexSelector]);
  358. if (!found) {
  359. indexSelector++;
  360. }
  361. }
  362. return found;
  363. }
  364. function transformRange(range) {
  365. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  366. while (range.length < 6) {
  367. range = "0" + range;
  368. }
  369. return "\\u{" + range + "}";
  370. }
  371. function getFontKey(style) {
  372. return JSON.stringify([
  373. removeQuotes(style.getPropertyValue("font-family")),
  374. getFontWeight(style.getPropertyValue("font-weight")),
  375. style.getPropertyValue("font-style"),
  376. style.getPropertyValue("unicode-range"),
  377. getFontStretch(style.getPropertyValue("font-stretch")),
  378. style.getPropertyValue("font-variant"),
  379. style.getPropertyValue("font-feature-settings"),
  380. style.getPropertyValue("font-variation-settings")
  381. ]);
  382. }
  383. function removeQuotes(string) {
  384. string = string.toLowerCase().trim();
  385. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  386. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  387. } else {
  388. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  389. }
  390. return string.trim();
  391. }
  392. function getFontWeight(weight) {
  393. return FONT_WEIGHTS[weight] || weight;
  394. }
  395. function getFontStretch(stretch) {
  396. return FONT_STRETCHES[stretch] || stretch;
  397. }
  398. })();