css-fonts-minifier.js 13 KB

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