css-fonts-minifier.js 13 KB

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