css-fonts-alt-minifier.js 11 KB

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