css-fonts-minifier.js 8.6 KB

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