css-fonts-minifier.js 11 KB

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