css-fonts-minifier.js 13 KB

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