css-fonts-minifier.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. return {
  38. process: (doc, secondPass) => {
  39. const declaredFonts = new Set();
  40. const usedFonts = [];
  41. const stats = {
  42. rules: {
  43. processed: 0,
  44. discarded: 0
  45. },
  46. fonts: {
  47. processed: 0,
  48. discarded: 0
  49. }
  50. };
  51. doc.querySelectorAll("style").forEach(style => {
  52. if (style.sheet) {
  53. const processedRules = style.sheet.cssRules.length;
  54. stats.rules.processed += processedRules;
  55. style.textContent = processRules(doc, style.sheet.cssRules, declaredFonts, usedFonts, stats, secondPass);
  56. stats.rules.discarded += processedRules - style.sheet.cssRules.length;
  57. }
  58. });
  59. doc.querySelectorAll("[style]").forEach(element => {
  60. if (element.style.fontFamily) {
  61. const fontFamilyNames = element.style.fontFamily.split(",").map(fontFamilyName => getFontFamilyName(fontFamilyName));
  62. usedFonts.push(fontFamilyNames);
  63. }
  64. });
  65. const variableFound = usedFonts.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  66. let unusedFonts;
  67. if (variableFound) {
  68. unusedFonts = [];
  69. } else {
  70. const filteredUsedFonts = new Set(usedFonts.map(fontNames => fontNames.find(fontName => declaredFonts.has(fontName))).filter(fontName => fontName));
  71. unusedFonts = Array.from(declaredFonts).filter(fontFamilyName => !filteredUsedFonts.has(fontFamilyName));
  72. }
  73. doc.querySelectorAll("style").forEach(style => {
  74. if (style.sheet) {
  75. const processedRules = style.sheet.cssRules.length;
  76. style.textContent = deleteUnusedFonts(doc, style.sheet.cssRules, unusedFonts);
  77. stats.rules.discarded += processedRules - style.sheet.cssRules.length;
  78. }
  79. });
  80. return stats;
  81. }
  82. };
  83. function processRules(doc, rules, declaredFonts, usedFonts, stats, secondPass) {
  84. let stylesheetContent = "";
  85. if (rules) {
  86. Array.from(rules).forEach(rule => {
  87. if (rule.type == CSSRule.MEDIA_RULE) {
  88. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + " {";
  89. stylesheetContent += processRules(doc, rule.cssRules, declaredFonts, usedFonts, stats, secondPass);
  90. stylesheetContent += "}";
  91. } else if (rule.type == CSSRule.STYLE_RULE) {
  92. if (rule.style && rule.style.fontFamily) {
  93. const fontFamilyNames = rule.style.fontFamily.split(",").map(fontFamilyName => getFontFamilyName(fontFamilyName));
  94. usedFonts.push(fontFamilyNames);
  95. }
  96. stylesheetContent += rule.cssText;
  97. } else {
  98. let cssText = rule.cssText;
  99. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  100. const fontFamilyName = rule.style.getPropertyValue("font-family");
  101. if (fontFamilyName) {
  102. declaredFonts.add(getFontFamilyName(fontFamilyName));
  103. }
  104. const src = rule.style.getPropertyValue("src");
  105. if (src) {
  106. const fontSources = src.match(REGEXP_URL_FUNCTION);
  107. if (fontSources) {
  108. if (secondPass || testUnicodeRange(doc, rule)) {
  109. cssText = processFontFaceRule(rule, fontSources, stats);
  110. } else {
  111. cssText = "";
  112. }
  113. }
  114. }
  115. }
  116. stylesheetContent += cssText;
  117. }
  118. });
  119. }
  120. return stylesheetContent;
  121. }
  122. function testUnicodeRange(doc, rule) {
  123. const unicodeRange = rule.style.getPropertyValue("unicode-range");
  124. const docContent = doc.body.outerText;
  125. if (unicodeRange) {
  126. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  127. const result = unicodeRanges.filter(rangeValue => {
  128. const range = rangeValue.split(REGEXP_DASH);
  129. if (range.length == 2) {
  130. range[0] = transformRange(range[0]);
  131. const regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  132. return (new RegExp(regExpString, "u")).test(docContent);
  133. }
  134. if (range.length == 1) {
  135. if (range[0].includes("?")) {
  136. const firstRange = transformRange(range[0]);
  137. const secondRange = firstRange;
  138. const regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  139. return (new RegExp(regExpString, "u")).test(docContent);
  140. } else {
  141. const regExpString = "[" + transformRange(range[0]) + "]";
  142. return (new RegExp(regExpString, "u")).test(docContent);
  143. }
  144. }
  145. return true;
  146. });
  147. return result.length;
  148. }
  149. return true;
  150. }
  151. function transformRange(range) {
  152. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  153. while (range.length < 6) {
  154. range = "0" + range;
  155. }
  156. return "\\u{" + range + "}";
  157. }
  158. function processFontFaceRule(rule, fontSources, stats) {
  159. fontSources = fontSources.map(fontSrc => {
  160. const fontFormatMatch = fontSrc.match(REGEXP_FONT_FORMAT_VALUE);
  161. let fontFormat;
  162. if (fontFormatMatch && fontFormatMatch[1]) {
  163. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  164. }
  165. if (!fontFormat) {
  166. const fontFormatMatch = fontSrc.match(REGEXP_URL_FUNCTION_WOFF);
  167. if (fontFormatMatch && fontFormatMatch[1]) {
  168. fontFormat = fontFormatMatch[1];
  169. } else {
  170. const fontFormatMatch = fontSrc.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  171. if (fontFormatMatch && fontFormatMatch[1]) {
  172. fontFormat = fontFormatMatch[1];
  173. }
  174. }
  175. }
  176. if (!fontFormat) {
  177. const urlMatch = fontSrc.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  178. fontSrc.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  179. fontSrc.match(REGEXP_URL_NO_QUOTES_FN);
  180. const fontUrl = urlMatch && urlMatch[1];
  181. if (fontUrl) {
  182. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  183. if (fontFormatMatch && fontFormatMatch[1]) {
  184. fontFormat = fontFormatMatch[1];
  185. }
  186. }
  187. }
  188. return { src: fontSrc.match(REGEXP_FONT_SRC)[1], format: fontFormat };
  189. });
  190. const fontTest = (fontSource, format) => fontSource.format == format;
  191. const woff2FontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2"));
  192. const woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff"));
  193. stats.fonts.processed += fontSources.length;
  194. if (woffFontFound || woff2FontFound) {
  195. fontSources = fontSources.filter(fontSource => woff2FontFound ? fontTest(fontSource, "woff2") : fontTest(fontSource, "woff"));
  196. } else {
  197. const otfFontFound = fontSources.find(fontSource => fontTest(fontSource, "otf"));
  198. const ttfFontFound = fontSources.find(fontSource => fontTest(fontSource, "ttf"));
  199. if (otfFontFound || ttfFontFound) {
  200. fontSources = fontSources.filter(fontSource => otfFontFound ? fontTest(fontSource, "otf") : fontTest(fontSource, "ttf"));
  201. }
  202. }
  203. stats.fonts.processed += stats.fonts.processed - fontSources.length;
  204. const cssStyles = [];
  205. Array.from(rule.style).forEach(propertyName => {
  206. if (propertyName == "src") {
  207. cssStyles.push("src:" + fontSources.map(fontSource => fontSource.src).join(","));
  208. } else {
  209. cssStyles.push(propertyName + ":" + rule.style.getPropertyValue(propertyName));
  210. }
  211. });
  212. return "@font-face{" + cssStyles.join(";") + "}";
  213. }
  214. function deleteUnusedFonts(doc, rules, unusedFonts) {
  215. let stylesheetContent = "";
  216. if (rules) {
  217. Array.from(rules).forEach(rule => {
  218. const fontFamilyName = rule.style && rule.style.getPropertyValue("font-family");
  219. if (rule.media) {
  220. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  221. stylesheetContent += deleteUnusedFonts(doc, rule.cssRules, unusedFonts);
  222. stylesheetContent += "}";
  223. } else if (rule.type != CSSRule.FONT_FACE_RULE || (rule.type == CSSRule.FONT_FACE_RULE && rule.style && fontFamilyName && !unusedFonts.includes(getFontFamilyName(fontFamilyName)))) {
  224. stylesheetContent += rule.cssText;
  225. }
  226. });
  227. }
  228. return stylesheetContent;
  229. }
  230. function getFontFamilyName(fontFamilyName) {
  231. fontFamilyName = fontFamilyName.toLowerCase().trim();
  232. if (fontFamilyName.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  233. fontFamilyName = fontFamilyName.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  234. } else {
  235. fontFamilyName = fontFamilyName.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  236. }
  237. return fontFamilyName.trim();
  238. }
  239. })();