css-fonts-minifier.js 13 KB

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