css-fonts-minifier.js 13 KB

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