css-fonts-alt-minifier.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 cssTree */
  21. this.fontsAltMinifier = this.fontsAltMinifier || (() => {
  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|local)\(.*?\)\s*(,|$)/g;
  26. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  27. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  28. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  29. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  30. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  31. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  32. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  33. const EMPTY_URL_SOURCE = "url(\"data:base64,\")";
  34. const LOCAL_SOURCE = "local(";
  35. const FONT_WEIGHTS = {
  36. normal: "400",
  37. bold: "700"
  38. };
  39. const FONT_STRETCHES = {
  40. "ultra-condensed": "50%",
  41. "extra-condensed": "62.5%",
  42. "condensed": "75%",
  43. "semi-condensed": "87.5%",
  44. "normal": "100%",
  45. "semi-expanded": "112.5%",
  46. "expanded": "125%",
  47. "extra-expanded": "150%",
  48. "ultra-expanded": "200%"
  49. };
  50. return {
  51. process: (doc, stylesheets) => {
  52. const fontsDetails = new Map();
  53. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  54. stylesheets.forEach(stylesheetInfo => {
  55. const cssRules = stylesheetInfo.stylesheet.children;
  56. stats.rules.processed += cssRules.getSize();
  57. stats.rules.discarded += cssRules.getSize();
  58. getFontsDetails(doc, cssRules, fontsDetails);
  59. });
  60. processFontDetails(fontsDetails);
  61. stylesheets.forEach(stylesheetInfo => {
  62. const cssRules = stylesheetInfo.stylesheet.children;
  63. processFontFaceRules(cssRules, fontsDetails, "all", stats);
  64. stats.rules.discarded -= cssRules.getSize();
  65. });
  66. return stats;
  67. }
  68. };
  69. function processFontDetails(fontsDetails) {
  70. fontsDetails.forEach((fontInfo, fontKey) => {
  71. fontsDetails.set(fontKey, fontInfo.map(fontSource => {
  72. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  73. let fontFormat;
  74. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  75. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  76. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  77. const fontUrl = urlMatch && urlMatch[1];
  78. if (fontFormatMatch && fontFormatMatch[1]) {
  79. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  80. }
  81. if (!fontFormat) {
  82. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  83. if (fontFormatMatch && fontFormatMatch[1]) {
  84. fontFormat = fontFormatMatch[1];
  85. } else {
  86. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  87. if (fontFormatMatch && fontFormatMatch[1]) {
  88. fontFormat = fontFormatMatch[1];
  89. }
  90. }
  91. }
  92. if (!fontFormat && fontUrl) {
  93. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  94. if (fontFormatMatch && fontFormatMatch[1]) {
  95. fontFormat = fontFormatMatch[1];
  96. }
  97. }
  98. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  99. }));
  100. });
  101. }
  102. function processFontFaceRules(cssRules, fontsDetails, media, stats) {
  103. const removedRules = [];
  104. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  105. const ruleData = cssRule.data;
  106. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.prelude && ruleData.prelude.children) {
  107. const mediaText = cssTree.generate(ruleData.prelude);
  108. processFontFaceRules(ruleData.block.children, fontsDetails, mediaText, stats);
  109. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && (media.includes("all") || media.includes("screen"))) {
  110. const fontInfo = fontsDetails.get(getFontKey(ruleData));
  111. if (fontInfo) {
  112. fontsDetails.delete(getFontKey(ruleData));
  113. processFontFaceRule(ruleData, fontInfo, stats);
  114. } else {
  115. removedRules.push(cssRule);
  116. }
  117. }
  118. }
  119. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  120. }
  121. function processFontFaceRule(cssRule, fontInfo, stats) {
  122. const findSource = fontFormat => fontInfo.find(source => source.src != EMPTY_URL_SOURCE && source.format == fontFormat);
  123. const filterSource = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
  124. stats.fonts.processed += fontInfo.length;
  125. stats.fonts.discarded += fontInfo.length;
  126. const woffFontFound = findSource("woff2-variations") || findSource("woff2") || findSource("woff");
  127. if (woffFontFound) {
  128. fontInfo = filterSource(woffFontFound);
  129. } else {
  130. const ttfFontFound = findSource("truetype-variations") || findSource("truetype");
  131. if (ttfFontFound) {
  132. fontInfo = filterSource(ttfFontFound);
  133. } else {
  134. const otfFontFound = findSource("opentype") || findSource("embedded-opentype");
  135. if (otfFontFound) {
  136. fontInfo = filterSource(otfFontFound);
  137. }
  138. }
  139. }
  140. stats.fonts.discarded -= fontInfo.length;
  141. const removedNodes = [];
  142. for (let node = cssRule.block.children.head; node; node = node.next) {
  143. if (node.data.property == "src") {
  144. removedNodes.push(node);
  145. }
  146. }
  147. removedNodes.pop();
  148. removedNodes.forEach(node => cssRule.block.children.remove(node));
  149. const srcDeclaration = cssRule.block.children.filter(node => node.property == "src").tail;
  150. if (srcDeclaration) {
  151. fontInfo.reverse();
  152. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  153. }
  154. }
  155. function getPropertyValue(cssRule, propertyName) {
  156. const property = cssRule.block.children.filter(node => node.property == propertyName).tail;
  157. if (property) {
  158. try {
  159. return cssTree.generate(property.data.value);
  160. } catch (error) {
  161. // ignored
  162. }
  163. }
  164. }
  165. function getFontsDetails(doc, cssRules, fontsDetails) {
  166. cssRules.forEach(cssRule => {
  167. if (cssRule.type == "Atrule" && cssRule.name == "media" && cssRule.block) {
  168. getFontsDetails(doc, cssRule.block.children, fontsDetails);
  169. } else {
  170. if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  171. const fontKey = getFontKey(cssRule);
  172. let fontInfo = fontsDetails.get(fontKey);
  173. if (!fontInfo) {
  174. fontInfo = [];
  175. fontsDetails.set(fontKey, fontInfo);
  176. }
  177. const src = getPropertyValue(cssRule, "src");
  178. if (src) {
  179. const fontSources = src.match(REGEXP_URL_FUNCTION);
  180. if (fontSources) {
  181. fontSources.forEach(source => fontInfo.unshift(source));
  182. }
  183. }
  184. }
  185. }
  186. });
  187. }
  188. function getFontKey(cssRule) {
  189. return JSON.stringify([
  190. getFontFamily(getPropertyValue(cssRule, "font-family")),
  191. getFontWeight(getPropertyValue(cssRule, "font-weight") || "400"),
  192. getPropertyValue(cssRule, "font-style") || "normal",
  193. getPropertyValue(cssRule, "unicode-range"),
  194. getFontStretch(getPropertyValue(cssRule, "font-stretch")),
  195. getPropertyValue(cssRule, "font-variant") || "normal",
  196. getPropertyValue(cssRule, "font-feature-settings"),
  197. getPropertyValue(cssRule, "font-variation-settings")
  198. ]);
  199. }
  200. function getFontFamily(string = "") {
  201. string = string.toLowerCase().trim();
  202. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  203. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  204. } else {
  205. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  206. }
  207. return string.trim();
  208. }
  209. function getFontWeight(weight) {
  210. return FONT_WEIGHTS[weight] || weight;
  211. }
  212. function getFontStretch(stretch) {
  213. return FONT_STRETCHES[stretch] || stretch;
  214. }
  215. })();