fonts-minifier.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. return {
  26. process: (doc, secondPass) => {
  27. const declaredFonts = new Set();
  28. const usedFonts = new Set();
  29. const stats = {
  30. rules: {
  31. processed: 0,
  32. discarded: 0
  33. },
  34. fonts: {
  35. processed: 0,
  36. discarded: 0
  37. }
  38. };
  39. doc.querySelectorAll("style").forEach(style => {
  40. if (style.sheet) {
  41. const processedRules = style.sheet.cssRules.length;
  42. stats.rules.processed += processedRules;
  43. style.textContent = processRules(doc, style.sheet.cssRules, declaredFonts, usedFonts, stats, secondPass);
  44. stats.rules.discarded += processedRules - style.sheet.cssRules.length;
  45. }
  46. });
  47. doc.querySelectorAll("[style]").forEach(element => {
  48. if (element.style.fontFamily) {
  49. element.style.fontFamily.split(",").forEach(fontFamilyName => usedFonts.add(getFontFamilyName(fontFamilyName)));
  50. }
  51. });
  52. const unusedFonts = Array.from(declaredFonts).filter(fontFamilyName => !usedFonts.has(fontFamilyName));
  53. doc.querySelectorAll("style").forEach(style => {
  54. if (style.sheet) {
  55. const processedRules = style.sheet.cssRules.length;
  56. style.textContent = deleteUnusedFonts(doc, style.sheet.cssRules, unusedFonts);
  57. stats.rules.discarded += processedRules - style.sheet.cssRules.length;
  58. }
  59. });
  60. return stats;
  61. }
  62. };
  63. function processRules(doc, rules, declaredFonts, usedFonts, stats, secondPass) {
  64. let stylesheetContent = "";
  65. if (rules) {
  66. Array.from(rules).forEach(rule => {
  67. if (rule.type == CSSRule.MEDIA_RULE) {
  68. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + " {";
  69. stylesheetContent += processRules(doc, rule.cssRules, declaredFonts, usedFonts, stats, secondPass);
  70. stylesheetContent += "}";
  71. } else if (rule.type == CSSRule.STYLE_RULE) {
  72. if (rule.style && rule.style.fontFamily) {
  73. rule.style.fontFamily.split(",").forEach(fontFamilyName => usedFonts.add(getFontFamilyName(fontFamilyName)));
  74. }
  75. stylesheetContent += rule.cssText;
  76. } else {
  77. let cssText = rule.cssText;
  78. if (rule.type == CSSRule.FONT_FACE_RULE && rule.style) {
  79. const fontFamilyName = rule.style.getPropertyValue("font-family");
  80. if (fontFamilyName) {
  81. declaredFonts.add(getFontFamilyName(fontFamilyName));
  82. }
  83. const src = rule.style.getPropertyValue("src");
  84. if (src) {
  85. const fontSources = src.match(/url\(.*?\)\s*(,|$)/g);
  86. if (fontSources) {
  87. if (secondPass || testUnicodeRange(doc, rule)) {
  88. cssText = processFontFaceRule(rule, fontSources, stats);
  89. } else {
  90. cssText = "";
  91. }
  92. }
  93. }
  94. }
  95. stylesheetContent += cssText;
  96. }
  97. });
  98. }
  99. return stylesheetContent;
  100. }
  101. function testUnicodeRange(doc, rule) {
  102. const unicodeRange = rule.style.getPropertyValue("unicode-range");
  103. const docContent = doc.body.outerText;
  104. if (unicodeRange) {
  105. const unicodeRanges = unicodeRange.split(/\s*,\s*/);
  106. const result = unicodeRanges.filter(rangeValue => {
  107. const range = rangeValue.split(/-/);
  108. if (range.length == 2) {
  109. range[0] = transformRange(range[0]);
  110. const regExpString = "[" + range[0] + "-\\u" + range[1] + "]";
  111. return (new RegExp(regExpString)).test(docContent);
  112. }
  113. if (range.length == 1) {
  114. if (range[0].includes("?")) {
  115. const firstRange = transformRange(range[0]);
  116. const secondRange = firstRange;
  117. const regExpString = "[" + firstRange.replace(/\?/g, "0") + "-" + secondRange.replace(/\?/g, "F") + "]";
  118. return (new RegExp(regExpString)).test(docContent);
  119. } else {
  120. const regExpString = "[" + transformRange(range[0]) + "]";
  121. return (new RegExp(regExpString)).test(docContent);
  122. }
  123. }
  124. return true;
  125. });
  126. return result.length;
  127. }
  128. return true;
  129. }
  130. function transformRange(range) {
  131. return range.replace(/^U\+/i, "\\u");
  132. }
  133. function processFontFaceRule(rule, fontSources, stats) {
  134. fontSources = fontSources.map(fontSrc => {
  135. const fontFormatMatch = fontSrc.match(/format\((.*?)\)\s*,?$/);
  136. let fontFormat;
  137. if (fontFormatMatch && fontFormatMatch[1]) {
  138. fontFormat = fontFormatMatch[1].replace(/^'(.*?)'$/, "$1").replace(/^"(.*?)"$/, "$1").toLowerCase();
  139. }
  140. if (!fontFormat) {
  141. const fontFormatMatch = fontSrc.match(/^url\(\s*["']?data:font\/(woff2?)/);
  142. if (fontFormatMatch && fontFormatMatch[1]) {
  143. fontFormat = fontFormatMatch[1];
  144. } else {
  145. const fontFormatMatch = fontSrc.match(/^url\(\s*["']?data:application\/x-font-(woff)/);
  146. if (fontFormatMatch && fontFormatMatch[1]) {
  147. fontFormat = fontFormatMatch[1];
  148. }
  149. }
  150. }
  151. if (!fontFormat) {
  152. const urlMatch = fontSrc.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  153. fontSrc.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  154. fontSrc.match(REGEXP_URL_NO_QUOTES_FN);
  155. const fontUrl = urlMatch && urlMatch[1];
  156. if (fontUrl) {
  157. const fontFormatMatch = fontUrl.match(/\.([^.?#]+)((\?|#).*?)?$/);
  158. if (fontFormatMatch && fontFormatMatch[1]) {
  159. fontFormat = fontFormatMatch[1];
  160. }
  161. }
  162. }
  163. return { src: fontSrc.match(/(.*?)\s*,?$/)[1], format: fontFormat };
  164. });
  165. const fontTest = (fontSource, format) => fontSource.format == format;
  166. const woff2FontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2"));
  167. const woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff"));
  168. stats.fonts.processed += fontSources.length;
  169. if (woffFontFound || woff2FontFound) {
  170. fontSources = fontSources.filter(fontSource => woff2FontFound ? fontTest(fontSource, "woff2") : fontTest(fontSource, "woff"));
  171. }
  172. stats.fonts.processed += stats.fonts.processed - fontSources.length;
  173. const cssStyles = [];
  174. Array.from(rule.style).forEach(propertyName => {
  175. if (propertyName == "src") {
  176. cssStyles.push("src:" + fontSources.map(fontSource => fontSource.src).join(","));
  177. } else {
  178. cssStyles.push(propertyName + ":" + rule.style.getPropertyValue(propertyName));
  179. }
  180. });
  181. return "@font-face{" + cssStyles.join(";") + "}";
  182. }
  183. function deleteUnusedFonts(doc, rules, unusedFonts) {
  184. let stylesheetContent = "";
  185. if (rules) {
  186. Array.from(rules).forEach(rule => {
  187. const fontFamilyName = rule.style && rule.style.getPropertyValue("font-family");
  188. if (rule.media) {
  189. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  190. stylesheetContent += deleteUnusedFonts(doc, rule.cssRules, unusedFonts);
  191. stylesheetContent += "}";
  192. } else if (rule.type != CSSRule.FONT_FACE_RULE || (rule.type == CSSRule.FONT_FACE_RULE && rule.style && fontFamilyName && !unusedFonts.includes(getFontFamilyName(fontFamilyName)))) {
  193. stylesheetContent += rule.cssText;
  194. }
  195. });
  196. }
  197. return stylesheetContent;
  198. }
  199. function getFontFamilyName(fontFamilyName) {
  200. fontFamilyName = fontFamilyName.toLowerCase().trim();
  201. if (fontFamilyName.match(/^'(.*)'$/)) {
  202. fontFamilyName = fontFamilyName.replace(/^'(.*)'$/, "$1");
  203. } else {
  204. fontFamilyName = fontFamilyName.replace(/^"(.*)"$/, "$1");
  205. }
  206. return fontFamilyName.trim();
  207. }
  208. })();