css-fonts-alt-minifier.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. this.singlefile.lib.modules.fontsAltMinifier = this.singlefile.lib.modules.fontsAltMinifier || (() => {
  24. const singlefile = this.singlefile;
  25. const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
  26. const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
  27. const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
  28. const REGEXP_URL_FUNCTION = /(url|local)\(.*?\)\s*(,|$)/g;
  29. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  30. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  31. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  32. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  33. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  34. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  35. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  36. const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,["']?\)/;
  37. const LOCAL_SOURCE = "local(";
  38. const MEDIA_ALL = "all";
  39. const FONT_WEIGHTS = {
  40. normal: "400",
  41. bold: "700"
  42. };
  43. const FONT_STRETCHES = {
  44. "ultra-condensed": "50%",
  45. "extra-condensed": "62.5%",
  46. "condensed": "75%",
  47. "semi-condensed": "87.5%",
  48. "normal": "100%",
  49. "semi-expanded": "112.5%",
  50. "expanded": "125%",
  51. "extra-expanded": "150%",
  52. "ultra-expanded": "200%"
  53. };
  54. return {
  55. process: (doc, stylesheets) => {
  56. const fontsDetails = {
  57. fonts: new Map(),
  58. medias: new Map(),
  59. supports: new Map()
  60. };
  61. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  62. let sheetIndex = 0;
  63. stylesheets.forEach(stylesheetInfo => {
  64. const cssRules = stylesheetInfo.stylesheet.children;
  65. if (cssRules) {
  66. stats.rules.processed += cssRules.getSize();
  67. stats.rules.discarded += cssRules.getSize();
  68. if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
  69. const mediaFontsDetails = createFontsDetailsInfo();
  70. fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
  71. getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
  72. } else {
  73. getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
  74. }
  75. }
  76. sheetIndex++;
  77. });
  78. processFontDetails(fontsDetails);
  79. sheetIndex = 0;
  80. stylesheets.forEach(stylesheetInfo => {
  81. const cssRules = stylesheetInfo.stylesheet.children;
  82. const media = stylesheetInfo.mediaText;
  83. if (cssRules) {
  84. if (media && media != MEDIA_ALL) {
  85. processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), stats);
  86. } else {
  87. processFontFaceRules(cssRules, sheetIndex, fontsDetails, stats);
  88. }
  89. stats.rules.discarded -= cssRules.getSize();
  90. }
  91. sheetIndex++;
  92. });
  93. return stats;
  94. }
  95. };
  96. function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
  97. const cssTree = singlefile.lib.vendor.cssTree;
  98. let mediaIndex = 0, supportsIndex = 0;
  99. cssRules.forEach(ruleData => {
  100. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  101. const mediaText = cssTree.generate(ruleData.prelude);
  102. const fontsDetails = createFontsDetailsInfo();
  103. mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
  104. mediaIndex++;
  105. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  106. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  107. const supportsText = cssTree.generate(ruleData.prelude);
  108. const fontsDetails = createFontsDetailsInfo();
  109. mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
  110. supportsIndex++;
  111. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  112. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
  113. const fontKey = getFontKey(ruleData);
  114. let fontInfo = mediaFontsDetails.fonts.get(fontKey);
  115. if (!fontInfo) {
  116. fontInfo = [];
  117. mediaFontsDetails.fonts.set(fontKey, fontInfo);
  118. }
  119. const src = getPropertyValue(ruleData, "src");
  120. if (src) {
  121. const fontSources = src.match(REGEXP_URL_FUNCTION);
  122. if (fontSources) {
  123. fontSources.forEach(source => fontInfo.unshift(source));
  124. }
  125. }
  126. }
  127. });
  128. }
  129. function processFontDetails(fontsDetails) {
  130. fontsDetails.fonts.forEach((fontInfo, fontKey) => {
  131. fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
  132. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  133. let fontFormat;
  134. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  135. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  136. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  137. const fontUrl = urlMatch && urlMatch[1];
  138. if (fontFormatMatch && fontFormatMatch[1]) {
  139. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  140. }
  141. if (!fontFormat) {
  142. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  143. if (fontFormatMatch && fontFormatMatch[1]) {
  144. fontFormat = fontFormatMatch[1];
  145. } else {
  146. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  147. if (fontFormatMatch && fontFormatMatch[1]) {
  148. fontFormat = fontFormatMatch[1];
  149. }
  150. }
  151. }
  152. if (!fontFormat && fontUrl) {
  153. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  154. if (fontFormatMatch && fontFormatMatch[1]) {
  155. fontFormat = fontFormatMatch[1];
  156. }
  157. }
  158. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  159. }));
  160. });
  161. fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
  162. }
  163. function processFontFaceRules(cssRules, sheetIndex, fontsDetails, stats) {
  164. const cssTree = singlefile.lib.vendor.cssTree;
  165. const removedRules = [];
  166. let mediaIndex = 0, supportsIndex = 0;
  167. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  168. const ruleData = cssRule.data;
  169. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  170. const mediaText = cssTree.generate(ruleData.prelude);
  171. processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), stats);
  172. mediaIndex++;
  173. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  174. const supportsText = cssTree.generate(ruleData.prelude);
  175. processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), stats);
  176. supportsIndex++;
  177. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  178. const fontInfo = fontsDetails.fonts.get(getFontKey(ruleData));
  179. if (fontInfo) {
  180. fontsDetails.fonts.delete(getFontKey(ruleData));
  181. processFontFaceRule(ruleData, fontInfo, stats);
  182. } else {
  183. removedRules.push(cssRule);
  184. }
  185. }
  186. }
  187. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  188. }
  189. function processFontFaceRule(ruleData, fontInfo, stats) {
  190. const cssTree = singlefile.lib.vendor.cssTree;
  191. const findSource = fontFormat => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat);
  192. const filterSource = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
  193. stats.fonts.processed += fontInfo.length;
  194. stats.fonts.discarded += fontInfo.length;
  195. const woffFontFound = findSource("woff2-variations") || findSource("woff2") || findSource("woff");
  196. if (woffFontFound) {
  197. fontInfo = filterSource(woffFontFound);
  198. } else {
  199. const ttfFontFound = findSource("truetype-variations") || findSource("truetype");
  200. if (ttfFontFound) {
  201. fontInfo = filterSource(ttfFontFound);
  202. } else {
  203. const otfFontFound = findSource("opentype") || findSource("embedded-opentype");
  204. if (otfFontFound) {
  205. fontInfo = filterSource(otfFontFound);
  206. }
  207. }
  208. }
  209. stats.fonts.discarded -= fontInfo.length;
  210. const removedNodes = [];
  211. for (let node = ruleData.block.children.head; node; node = node.next) {
  212. if (node.data.property == "src") {
  213. removedNodes.push(node);
  214. }
  215. }
  216. removedNodes.pop();
  217. removedNodes.forEach(node => ruleData.block.children.remove(node));
  218. const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
  219. if (srcDeclaration) {
  220. fontInfo.reverse();
  221. try {
  222. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  223. }
  224. catch (error) {
  225. // ignored
  226. }
  227. }
  228. }
  229. function getPropertyValue(ruleData, propertyName) {
  230. const cssTree = singlefile.lib.vendor.cssTree;
  231. let property;
  232. if (ruleData.block.children) {
  233. property = ruleData.block.children.filter(node => node.property == propertyName).tail;
  234. }
  235. if (property) {
  236. try {
  237. return cssTree.generate(property.data.value);
  238. } catch (error) {
  239. // ignored
  240. }
  241. }
  242. }
  243. function getFontKey(ruleData) {
  244. return JSON.stringify([
  245. getFontFamily(getPropertyValue(ruleData, "font-family")),
  246. getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
  247. getPropertyValue(ruleData, "font-style") || "normal",
  248. getPropertyValue(ruleData, "unicode-range"),
  249. getFontStretch(getPropertyValue(ruleData, "font-stretch")),
  250. getPropertyValue(ruleData, "font-variant") || "normal",
  251. getPropertyValue(ruleData, "font-feature-settings"),
  252. getPropertyValue(ruleData, "font-variation-settings")
  253. ]);
  254. }
  255. function getFontFamily(string = "") {
  256. string = string.toLowerCase().trim();
  257. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  258. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  259. } else {
  260. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  261. }
  262. return string.trim();
  263. }
  264. function getFontWeight(weight) {
  265. return FONT_WEIGHTS[weight] || weight;
  266. }
  267. function getFontStretch(stretch) {
  268. return FONT_STRETCHES[stretch] || stretch;
  269. }
  270. function createFontsDetailsInfo() {
  271. return {
  272. fonts: new Map(),
  273. medias: new Map(),
  274. supports: new Map()
  275. };
  276. }
  277. })();