css-fonts-minifier.js 12 KB

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