css-fonts-minifier.js 9.3 KB

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