css-fonts-minifier.js 11 KB

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