css-fonts-alt-minifier.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * Copyright 2010-2019 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. this.fontsAltMinifier = this.fontsAltMinifier || (() => {
  21. const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
  22. const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
  23. const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
  24. const REGEXP_URL_FUNCTION = /(url|local)\(.*?\)\s*(,|$)/g;
  25. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  26. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  27. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  28. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  29. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  30. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  31. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  32. const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,["']?\)/;
  33. const LOCAL_SOURCE = "local(";
  34. const MEDIA_ALL = "all";
  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. let cssTree;
  51. return {
  52. getInstance(cssTreeImpl) {
  53. cssTree = cssTreeImpl;
  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. }
  97. };
  98. function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
  99. let mediaIndex = 0, supportsIndex = 0;
  100. cssRules.forEach(ruleData => {
  101. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  102. const mediaText = cssTree.generate(ruleData.prelude);
  103. const fontsDetails = createFontsDetailsInfo();
  104. mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
  105. mediaIndex++;
  106. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  107. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  108. const supportsText = cssTree.generate(ruleData.prelude);
  109. const fontsDetails = createFontsDetailsInfo();
  110. mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
  111. supportsIndex++;
  112. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  113. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
  114. const fontKey = getFontKey(ruleData);
  115. let fontInfo = mediaFontsDetails.fonts.get(fontKey);
  116. if (!fontInfo) {
  117. fontInfo = [];
  118. mediaFontsDetails.fonts.set(fontKey, fontInfo);
  119. }
  120. const src = getPropertyValue(ruleData, "src");
  121. if (src) {
  122. const fontSources = src.match(REGEXP_URL_FUNCTION);
  123. if (fontSources) {
  124. fontSources.forEach(source => fontInfo.unshift(source));
  125. }
  126. }
  127. }
  128. });
  129. }
  130. function processFontDetails(fontsDetails) {
  131. fontsDetails.fonts.forEach((fontInfo, fontKey) => {
  132. fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
  133. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  134. let fontFormat;
  135. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  136. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  137. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  138. const fontUrl = urlMatch && urlMatch[1];
  139. if (fontFormatMatch && fontFormatMatch[1]) {
  140. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  141. }
  142. if (!fontFormat) {
  143. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  144. if (fontFormatMatch && fontFormatMatch[1]) {
  145. fontFormat = fontFormatMatch[1];
  146. } else {
  147. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  148. if (fontFormatMatch && fontFormatMatch[1]) {
  149. fontFormat = fontFormatMatch[1];
  150. }
  151. }
  152. }
  153. if (!fontFormat && fontUrl) {
  154. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  155. if (fontFormatMatch && fontFormatMatch[1]) {
  156. fontFormat = fontFormatMatch[1];
  157. }
  158. }
  159. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  160. }));
  161. });
  162. fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
  163. }
  164. function processFontFaceRules(cssRules, sheetIndex, fontsDetails, stats) {
  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 findSource = fontFormat => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat);
  191. const filterSource = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
  192. stats.fonts.processed += fontInfo.length;
  193. stats.fonts.discarded += fontInfo.length;
  194. const woffFontFound = findSource("woff2-variations") || findSource("woff2") || findSource("woff");
  195. if (woffFontFound) {
  196. fontInfo = filterSource(woffFontFound);
  197. } else {
  198. const ttfFontFound = findSource("truetype-variations") || findSource("truetype");
  199. if (ttfFontFound) {
  200. fontInfo = filterSource(ttfFontFound);
  201. } else {
  202. const otfFontFound = findSource("opentype") || findSource("embedded-opentype");
  203. if (otfFontFound) {
  204. fontInfo = filterSource(otfFontFound);
  205. }
  206. }
  207. }
  208. stats.fonts.discarded -= fontInfo.length;
  209. const removedNodes = [];
  210. for (let node = ruleData.block.children.head; node; node = node.next) {
  211. if (node.data.property == "src") {
  212. removedNodes.push(node);
  213. }
  214. }
  215. removedNodes.pop();
  216. removedNodes.forEach(node => ruleData.block.children.remove(node));
  217. const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
  218. if (srcDeclaration) {
  219. fontInfo.reverse();
  220. try {
  221. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  222. }
  223. catch (error) {
  224. // ignored
  225. }
  226. }
  227. }
  228. function getPropertyValue(ruleData, propertyName) {
  229. let property;
  230. if (ruleData.block.children) {
  231. property = ruleData.block.children.filter(node => node.property == propertyName).tail;
  232. }
  233. if (property) {
  234. try {
  235. return cssTree.generate(property.data.value);
  236. } catch (error) {
  237. // ignored
  238. }
  239. }
  240. }
  241. function getFontKey(ruleData) {
  242. return JSON.stringify([
  243. getFontFamily(getPropertyValue(ruleData, "font-family")),
  244. getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
  245. getPropertyValue(ruleData, "font-style") || "normal",
  246. getPropertyValue(ruleData, "unicode-range"),
  247. getFontStretch(getPropertyValue(ruleData, "font-stretch")),
  248. getPropertyValue(ruleData, "font-variant") || "normal",
  249. getPropertyValue(ruleData, "font-feature-settings"),
  250. getPropertyValue(ruleData, "font-variation-settings")
  251. ]);
  252. }
  253. function getFontFamily(string = "") {
  254. string = string.toLowerCase().trim();
  255. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  256. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  257. } else {
  258. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  259. }
  260. return string.trim();
  261. }
  262. function getFontWeight(weight) {
  263. return FONT_WEIGHTS[weight] || weight;
  264. }
  265. function getFontStretch(stretch) {
  266. return FONT_STRETCHES[stretch] || stretch;
  267. }
  268. function createFontsDetailsInfo() {
  269. return {
  270. fonts: new Map(),
  271. medias: new Map(),
  272. supports: new Map()
  273. };
  274. }
  275. })();