css-fonts-alt-minifier.js 10 KB

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