css-fonts-minifier.js 9.5 KB

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