css-fonts-minifier.js 13 KB

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