fonts-minifier.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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] + "-" + transformRange("U+" + range[1]) + "]";
  111. return (new RegExp(regExpString, "u")).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, "u")).test(docContent);
  119. } else {
  120. const regExpString = "[" + transformRange(range[0]) + "]";
  121. return (new RegExp(regExpString, "u")).test(docContent);
  122. }
  123. }
  124. return true;
  125. });
  126. return result.length;
  127. }
  128. return true;
  129. }
  130. function transformRange(range) {
  131. range = range.replace(/^U\+/i, "");
  132. while (range.length < 6) {
  133. range = "0" + range;
  134. }
  135. return "\\u{" + range + "}";
  136. }
  137. function processFontFaceRule(rule, fontSources, stats) {
  138. fontSources = fontSources.map(fontSrc => {
  139. const fontFormatMatch = fontSrc.match(/format\((.*?)\)\s*,?$/);
  140. let fontFormat;
  141. if (fontFormatMatch && fontFormatMatch[1]) {
  142. fontFormat = fontFormatMatch[1].replace(/^'(.*?)'$/, "$1").replace(/^"(.*?)"$/, "$1").toLowerCase();
  143. }
  144. if (!fontFormat) {
  145. const fontFormatMatch = fontSrc.match(/^url\(\s*["']?data:font\/(woff2?)/);
  146. if (fontFormatMatch && fontFormatMatch[1]) {
  147. fontFormat = fontFormatMatch[1];
  148. } else {
  149. const fontFormatMatch = fontSrc.match(/^url\(\s*["']?data:application\/x-font-(woff)/);
  150. if (fontFormatMatch && fontFormatMatch[1]) {
  151. fontFormat = fontFormatMatch[1];
  152. }
  153. }
  154. }
  155. if (!fontFormat) {
  156. const urlMatch = fontSrc.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  157. fontSrc.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  158. fontSrc.match(REGEXP_URL_NO_QUOTES_FN);
  159. const fontUrl = urlMatch && urlMatch[1];
  160. if (fontUrl) {
  161. const fontFormatMatch = fontUrl.match(/\.([^.?#]+)((\?|#).*?)?$/);
  162. if (fontFormatMatch && fontFormatMatch[1]) {
  163. fontFormat = fontFormatMatch[1];
  164. }
  165. }
  166. }
  167. return { src: fontSrc.match(/(.*?)\s*,?$/)[1], format: fontFormat };
  168. });
  169. const fontTest = (fontSource, format) => fontSource.format == format;
  170. const woff2FontFound = fontSources.find(fontSource => fontTest(fontSource, "woff2"));
  171. const woffFontFound = fontSources.find(fontSource => fontTest(fontSource, "woff"));
  172. stats.fonts.processed += fontSources.length;
  173. if (woffFontFound || woff2FontFound) {
  174. fontSources = fontSources.filter(fontSource => woff2FontFound ? fontTest(fontSource, "woff2") : fontTest(fontSource, "woff"));
  175. }
  176. stats.fonts.processed += stats.fonts.processed - fontSources.length;
  177. const cssStyles = [];
  178. Array.from(rule.style).forEach(propertyName => {
  179. if (propertyName == "src") {
  180. cssStyles.push("src:" + fontSources.map(fontSource => fontSource.src).join(","));
  181. } else {
  182. cssStyles.push(propertyName + ":" + rule.style.getPropertyValue(propertyName));
  183. }
  184. });
  185. return "@font-face{" + cssStyles.join(";") + "}";
  186. }
  187. function deleteUnusedFonts(doc, rules, unusedFonts) {
  188. let stylesheetContent = "";
  189. if (rules) {
  190. Array.from(rules).forEach(rule => {
  191. const fontFamilyName = rule.style && rule.style.getPropertyValue("font-family");
  192. if (rule.media) {
  193. stylesheetContent += "@media " + Array.prototype.join.call(rule.media, ",") + "{";
  194. stylesheetContent += deleteUnusedFonts(doc, rule.cssRules, unusedFonts);
  195. stylesheetContent += "}";
  196. } else if (rule.type != CSSRule.FONT_FACE_RULE || (rule.type == CSSRule.FONT_FACE_RULE && rule.style && fontFamilyName && !unusedFonts.includes(getFontFamilyName(fontFamilyName)))) {
  197. stylesheetContent += rule.cssText;
  198. }
  199. });
  200. }
  201. return stylesheetContent;
  202. }
  203. function getFontFamilyName(fontFamilyName) {
  204. fontFamilyName = fontFamilyName.toLowerCase().trim();
  205. if (fontFamilyName.match(/^'(.*)'$/)) {
  206. fontFamilyName = fontFamilyName.replace(/^'(.*)'$/, "$1");
  207. } else {
  208. fontFamilyName = fontFamilyName.replace(/^"(.*)"$/, "$1");
  209. }
  210. return fontFamilyName.trim();
  211. }
  212. })();