css-fonts-minifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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\(.*?\)\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 PSEUDO_ELEMENTS = ["::after", "::before", "::first-line", "::first-letter", ":before", ":after", ":first-line", ":first-letter", "::placeholder", "::selection", "::marker", "::cue", "::slotted", "::spelling-error", "::grammar-error"];
  38. const FONT_WEIGHTS = {
  39. normal: 400,
  40. bold: 700
  41. };
  42. const FONT_STRETCHES = {
  43. "ultra-condensed": "50%",
  44. "extra-condensed": "62.5%",
  45. "condensed": "75%",
  46. "semi-condensed": "87.5%",
  47. "normal": "100%",
  48. "semi-expanded": "112.5%",
  49. "expanded": "125%",
  50. "extra-expanded": "150%",
  51. "ultra-expanded": "200%"
  52. };
  53. return {
  54. process: (doc, secondPass) => {
  55. const declaredFonts = new Set();
  56. const fontsDetails = new Map();
  57. const usedFonts = [];
  58. const stats = {
  59. rules: {
  60. processed: 0,
  61. discarded: 0
  62. },
  63. fonts: {
  64. processed: 0,
  65. discarded: 0
  66. }
  67. };
  68. const pseudoElementsContent = Array.from(doc.querySelectorAll("style")).map(style => getPseudoElementsContent(doc, style.sheet.cssRules)).join("");
  69. doc.querySelectorAll("style").forEach(style => {
  70. if (style.sheet) {
  71. stats.rules.processed += style.sheet.cssRules.length;
  72. stats.rules.discarded += style.sheet.cssRules.length;
  73. processRules(doc, style.sheet.cssRules, fontsDetails, declaredFonts, usedFonts, pseudoElementsContent, secondPass);
  74. }
  75. });
  76. doc.querySelectorAll("style").forEach(style => {
  77. if (style.sheet) {
  78. style.textContent = processFontFaceRules(style.sheet.cssRules, fontsDetails, "all", stats);
  79. }
  80. });
  81. doc.querySelectorAll("[style]").forEach(element => {
  82. if (element.style.fontFamily) {
  83. const fontFamilyNames = element.style.fontFamily.split(",").map(fontFamilyName => removeQuotes(fontFamilyName));
  84. usedFonts.push(fontFamilyNames);
  85. }
  86. });
  87. const variableFound = usedFonts.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  88. let unusedFonts;
  89. if (variableFound) {
  90. unusedFonts = [];
  91. } else {
  92. const filteredUsedFonts = new Set(usedFonts.map(fontNames => fontNames.find(fontName => declaredFonts.has(fontName))).filter(fontName => fontName));
  93. unusedFonts = Array.from(declaredFonts).filter(fontFamilyName => !filteredUsedFonts.has(fontFamilyName));
  94. }
  95. doc.querySelectorAll("style").forEach(style => {
  96. if (style.sheet) {
  97. stats.fonts.discarded += style.sheet.cssRules.length;
  98. style.textContent = deleteUnusedFonts(doc, style.sheet.cssRules, unusedFonts);
  99. stats.fonts.discarded -= style.sheet.cssRules.length;
  100. stats.rules.discarded -= style.sheet.cssRules.length;
  101. }
  102. });
  103. return stats;
  104. }
  105. };
  106. function getPseudoElementsContent(doc, rules) {
  107. if (rules) {
  108. return Array.from(rules).map(rule => {
  109. if (rule.type == CSSRule.MEDIA_RULE) {
  110. return getPseudoElementsContent(doc, rule.cssRules);
  111. } else if (rule.type == CSSRule.STYLE_RULE && testPseudoElements(rule.selectorText)) {
  112. let content = rule.style.getPropertyValue("content");
  113. content = content && removeQuotes(content);
  114. return content;
  115. }
  116. }).join("");
  117. } else {
  118. return "";
  119. }
  120. }
  121. function processRules(doc, rules, fontsDetails, declaredFonts, usedFonts, pseudoElementsContent, secondPass) {
  122. if (rules) {
  123. Array.from(rules).forEach(rule => {
  124. if (rule.type == CSSRule.MEDIA_RULE) {
  125. processRules(doc, rule.cssRules, fontsDetails, declaredFonts, usedFonts, pseudoElementsContent, secondPass);
  126. } else if (rule.type == CSSRule.STYLE_RULE) {
  127. if (rule.style && rule.style.fontFamily) {
  128. const fontFamilyNames = rule.style.fontFamily.split(",").map(fontFamilyName => removeQuotes(fontFamilyName));
  129. usedFonts.push(fontFamilyNames);
  130. }
  131. } else {
  132. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  133. const fontFamilyName = removeQuotes(rule.style.getPropertyValue("font-family"));
  134. if (fontFamilyName) {
  135. declaredFonts.add(fontFamilyName);
  136. }
  137. if (secondPass || testUnicodeRange(doc.body.innerText + pseudoElementsContent, rule)) {
  138. const fontKey = getFontKey(rule.style);
  139. let fontInfo = fontsDetails.get(fontKey);
  140. if (!fontInfo) {
  141. fontInfo = [];
  142. fontsDetails.set(fontKey, fontInfo);
  143. }
  144. const src = rule.style.getPropertyValue("src");
  145. if (src) {
  146. const fontSources = src.match(REGEXP_URL_FUNCTION);
  147. if (fontSources) {
  148. fontSources.forEach(source => fontInfo.unshift(source));
  149. }
  150. }
  151. }
  152. }
  153. }
  154. });
  155. }
  156. }
  157. function processFontFaceRules(rules, fontsDetails, media, stats) {
  158. let stylesheetContent = "";
  159. Array.from(rules).forEach(rule => {
  160. if (rule.type == CSSRule.MEDIA_RULE) {
  161. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  162. stylesheetContent += processFontFaceRules(rule.cssRules, fontsDetails, rule.media.mediaText, stats);
  163. stylesheetContent += "}";
  164. } else if (rule.type == CSSRule.FONT_FACE_RULE && (media.includes("all") || media.includes("screen"))) {
  165. const fontInfo = fontsDetails.get(getFontKey(rule.style));
  166. if (fontInfo) {
  167. fontsDetails.delete(getFontKey(rule.style));
  168. stylesheetContent += "@font-face {" + processFontFaceRule(rule, fontInfo, stats) + "}";
  169. }
  170. } else {
  171. stylesheetContent += rule.cssText;
  172. }
  173. });
  174. return stylesheetContent;
  175. }
  176. function processFontFaceRule(rule, fontInfo, stats) {
  177. let fontSources = fontInfo.map(fontSource => {
  178. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  179. let fontFormat;
  180. if (fontFormatMatch && fontFormatMatch[1]) {
  181. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  182. }
  183. if (!fontFormat) {
  184. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  185. if (fontFormatMatch && fontFormatMatch[1]) {
  186. fontFormat = fontFormatMatch[1];
  187. } else {
  188. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  189. if (fontFormatMatch && fontFormatMatch[1]) {
  190. fontFormat = fontFormatMatch[1];
  191. }
  192. }
  193. }
  194. if (!fontFormat) {
  195. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  196. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  197. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  198. const fontUrl = urlMatch && urlMatch[1];
  199. if (fontUrl) {
  200. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  201. if (fontFormatMatch && fontFormatMatch[1]) {
  202. fontFormat = fontFormatMatch[1];
  203. }
  204. }
  205. }
  206. return { src: fontSource.match(REGEXP_FONT_SRC)[1], format: fontFormat };
  207. });
  208. const fontTest = (fontSource, format) => fontSource.format == format;
  209. let woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2-variations"));
  210. if (!woffFontFound) {
  211. woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2"));
  212. }
  213. if (!woffFontFound) {
  214. woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff"));
  215. }
  216. stats.fonts.processed += fontSources.length;
  217. stats.fonts.discarded += fontSources.length;
  218. if (woffFontFound) {
  219. fontSources = [woffFontFound];
  220. } else {
  221. let ttfFontFound = fontSources.find(fontSource => fontTest(fontSource, "truetype-variations"));
  222. if (!ttfFontFound) {
  223. ttfFontFound = fontSources.find(fontSource => fontTest(fontSource, "truetype"));
  224. }
  225. if (ttfFontFound) {
  226. fontSources = [ttfFontFound];
  227. } else {
  228. let otfFontFound = fontSources.find(fontSource => fontTest(fontSource, "opentype"));
  229. if (!otfFontFound) {
  230. otfFontFound = fontSources.find(fontSource => fontTest(fontSource, "embedded-opentype"));
  231. }
  232. if (otfFontFound) {
  233. fontSources = [otfFontFound];
  234. }
  235. }
  236. }
  237. stats.fonts.discarded -= fontSources.length;
  238. let cssText = "";
  239. Array.from(rule.style).forEach(propertyName => {
  240. cssText += propertyName + ":";
  241. if (propertyName == "src") {
  242. cssText += fontSources.map(fontSource => fontSource.src).join(",");
  243. } else {
  244. cssText += rule.style.getPropertyValue(propertyName);
  245. }
  246. cssText += ";";
  247. });
  248. return cssText;
  249. }
  250. function deleteUnusedFonts(doc, rules, unusedFonts) {
  251. let stylesheetContent = "";
  252. if (rules) {
  253. Array.from(rules).forEach(rule => {
  254. const fontFamilyName = rule.style && rule.style.getPropertyValue("font-family");
  255. if (rule.media) {
  256. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  257. stylesheetContent += deleteUnusedFonts(doc, rule.cssRules, unusedFonts);
  258. stylesheetContent += "}";
  259. } else if (rule.type != CSSRule.FONT_FACE_RULE || (rule.type == CSSRule.FONT_FACE_RULE && rule.style && fontFamilyName && !unusedFonts.includes(removeQuotes(fontFamilyName)))) {
  260. stylesheetContent += rule.cssText;
  261. }
  262. });
  263. }
  264. return stylesheetContent;
  265. }
  266. function testUnicodeRange(docContent, rule) {
  267. const unicodeRange = rule.style.getPropertyValue("unicode-range");
  268. if (unicodeRange) {
  269. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  270. const result = unicodeRanges.filter(rangeValue => {
  271. const range = rangeValue.split(REGEXP_DASH);
  272. if (range.length == 2) {
  273. range[0] = transformRange(range[0]);
  274. const regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  275. return (new RegExp(regExpString, "u")).test(docContent);
  276. }
  277. if (range.length == 1) {
  278. if (range[0].includes("?")) {
  279. const firstRange = transformRange(range[0]);
  280. const secondRange = firstRange;
  281. const regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  282. return (new RegExp(regExpString, "u")).test(docContent);
  283. } else {
  284. const regExpString = "[" + transformRange(range[0]) + "]";
  285. return (new RegExp(regExpString, "u")).test(docContent);
  286. }
  287. }
  288. return true;
  289. });
  290. return result.length;
  291. }
  292. return true;
  293. }
  294. function testPseudoElements(selectorText) {
  295. let indexSelector = 0, found;
  296. selectorText = selectorText.toLowerCase();
  297. while (indexSelector < PSEUDO_ELEMENTS.length && !found) {
  298. found = selectorText.includes(PSEUDO_ELEMENTS[indexSelector]);
  299. if (!found) {
  300. indexSelector++;
  301. }
  302. }
  303. return found;
  304. }
  305. function transformRange(range) {
  306. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  307. while (range.length < 6) {
  308. range = "0" + range;
  309. }
  310. return "\\u{" + range + "}";
  311. }
  312. function getFontKey(style) {
  313. return JSON.stringify([
  314. removeQuotes(style.getPropertyValue("font-family")),
  315. getFontWeight(style.getPropertyValue("font-weight")),
  316. style.getPropertyValue("font-style"),
  317. style.getPropertyValue("unicode-range"),
  318. getFontStretch(style.getPropertyValue("font-stretch")),
  319. style.getPropertyValue("font-variant"),
  320. style.getPropertyValue("font-feature-settings"),
  321. style.getPropertyValue("font-variation-settings")
  322. ]);
  323. }
  324. function removeQuotes(string) {
  325. string = string.toLowerCase().trim();
  326. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  327. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  328. } else {
  329. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  330. }
  331. return string.trim();
  332. }
  333. function getFontWeight(weight) {
  334. return FONT_WEIGHTS[weight] || weight;
  335. }
  336. function getFontStretch(stretch) {
  337. return FONT_STRETCHES[stretch] || stretch;
  338. }
  339. })();