css-fonts-minifier.js 11 KB

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