css-fonts-minifier.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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.fontsMinifier = this.fontsMinifier || (() => {
  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_COMMA = /\s*,\s*/;
  27. const REGEXP_DASH = /-/;
  28. const REGEXP_QUESTION_MARK = /\?/g;
  29. const REGEXP_STARTS_U_PLUS = /^U\+/i;
  30. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  31. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  32. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  33. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  34. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  35. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  36. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  37. const EMPTY_URL_SOURCE = "url(\"data:base64,\")";
  38. const PSEUDO_ELEMENTS = ["::after", "::before", "::first-line", "::first-letter", ":before", ":after", ":first-line", ":first-letter", "::placeholder", "::selection", "::marker", "::cue", "::slotted", "::spelling-error", "::grammar-error"];
  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. removeUnusedFonts: (doc, stylesheets, styles, options) => {
  56. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  57. const fontsInfo = { declared: [], used: [] };
  58. let pseudoElementsContent = "";
  59. stylesheets.forEach(stylesheetInfo => {
  60. const cssRules = stylesheetInfo.stylesheet.children;
  61. stats.processed += cssRules.getSize();
  62. stats.discarded += cssRules.getSize();
  63. getFontsInfo(cssRules, fontsInfo);
  64. pseudoElementsContent += getPseudoElementsContent(cssRules);
  65. });
  66. styles.forEach(style => {
  67. const fontFamilyNames = getFontFamilyNames(style);
  68. if (fontFamilyNames.length) {
  69. fontsInfo.used.push(fontFamilyNames);
  70. }
  71. });
  72. const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
  73. let unusedFonts, filteredUsedFonts;
  74. if (variableFound) {
  75. unusedFonts = [];
  76. } else {
  77. filteredUsedFonts = new Map();
  78. fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
  79. if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
  80. const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo.fontFamily == familyName);
  81. filteredUsedFonts.set(familyName, optionalData);
  82. }
  83. }));
  84. unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
  85. }
  86. const docContent = doc.body.innerText + pseudoElementsContent;
  87. stylesheets.forEach(stylesheetInfo => {
  88. const cssRules = stylesheetInfo.stylesheet.children;
  89. filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
  90. stats.rules.discarded -= cssRules.getSize();
  91. });
  92. return stats;
  93. },
  94. removeAlternativeFonts: (doc, stylesheets) => {
  95. const fontsDetails = new Map();
  96. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  97. stylesheets.forEach(stylesheetInfo => {
  98. const cssRules = stylesheetInfo.stylesheet.children;
  99. stats.rules.processed += cssRules.getSize();
  100. stats.rules.discarded += cssRules.getSize();
  101. getFontsDetails(doc, cssRules, fontsDetails);
  102. });
  103. processFontDetails(fontsDetails);
  104. stylesheets.forEach(stylesheetInfo => {
  105. const cssRules = stylesheetInfo.stylesheet.children;
  106. processFontFaceRules(cssRules, fontsDetails, "all", stats);
  107. stats.rules.discarded -= cssRules.getSize();
  108. });
  109. return stats;
  110. }
  111. };
  112. function processFontDetails(fontsDetails) {
  113. fontsDetails.forEach((fontInfo, fontKey) => {
  114. fontsDetails.set(fontKey, fontInfo.map(fontSource => {
  115. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  116. let fontFormat;
  117. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  118. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  119. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  120. const fontUrl = urlMatch && urlMatch[1];
  121. if (fontFormatMatch && fontFormatMatch[1]) {
  122. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  123. }
  124. if (!fontFormat) {
  125. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  126. if (fontFormatMatch && fontFormatMatch[1]) {
  127. fontFormat = fontFormatMatch[1];
  128. } else {
  129. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  130. if (fontFormatMatch && fontFormatMatch[1]) {
  131. fontFormat = fontFormatMatch[1];
  132. }
  133. }
  134. }
  135. if (!fontFormat && fontUrl) {
  136. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  137. if (fontFormatMatch && fontFormatMatch[1]) {
  138. fontFormat = fontFormatMatch[1];
  139. }
  140. }
  141. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  142. }));
  143. });
  144. }
  145. function getFontsInfo(cssRules, fontsInfo) {
  146. cssRules.forEach(cssRule => {
  147. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  148. getFontsInfo(cssRule.block.children, fontsInfo);
  149. } else if (cssRule.type == "Rule") {
  150. const fontFamilyNames = getFontFamilyNames(cssRule.block);
  151. if (fontFamilyNames.length) {
  152. fontsInfo.used.push(fontFamilyNames);
  153. }
  154. } else {
  155. if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  156. const fontFamily = getFontFamily(getPropertyValue(cssRule, "font-family"));
  157. if (fontFamily) {
  158. const fontWeight = getFontWeight(getPropertyValue(cssRule, "font-weight") || "400");
  159. const fontStyle = getPropertyValue(cssRule, "font-style") || "normal";
  160. const fontVariant = getPropertyValue(cssRule, "font-variant") || "normal";
  161. fontsInfo.declared.push({ fontFamily, fontWeight, fontStyle, fontVariant });
  162. }
  163. }
  164. }
  165. });
  166. }
  167. function filterUnusedFonts(rules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
  168. const removedRules = [];
  169. for (let rule = rules.head; rule; rule = rule.next) {
  170. const ruleData = rule.data;
  171. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  172. filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
  173. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  174. const fontFamily = getFontFamily(getPropertyValue(ruleData, "font-family"));
  175. if (fontFamily) {
  176. const unicodeRange = getPropertyValue(ruleData, "unicode-range");
  177. if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
  178. removedRules.push(rule);
  179. }
  180. }
  181. }
  182. }
  183. removedRules.forEach(rule => rules.remove(rule));
  184. }
  185. function testUsedFont(rule, familyName, declaredFonts, filteredUsedFonts) {
  186. let test;
  187. const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
  188. if (optionalUsedFonts && optionalUsedFonts.length) {
  189. const fontStyle = getPropertyValue(rule, "font-style") || "normal";
  190. const fontWeight = getFontWeight(getPropertyValue(rule, "font-weight") || "400");
  191. const fontVariant = getPropertyValue(rule, "font-variant") || "normal";
  192. const declaredFontsWeights = declaredFonts
  193. .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle && testFontVariant(fontInfo, fontVariant))
  194. .map(fontInfo => fontInfo.fontWeight)
  195. .sort((weight1, weight2) => weight1 - weight2);
  196. const usedFontWeights = optionalUsedFonts.map(fontInfo => findFontWeight(fontInfo.fontWeight, declaredFontsWeights));
  197. test = usedFontWeights.includes(fontWeight);
  198. } else {
  199. test = true;
  200. }
  201. return test;
  202. }
  203. function processFontFaceRules(cssRules, fontsDetails, media, stats) {
  204. const removedRules = [];
  205. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  206. const ruleData = cssRule.data;
  207. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  208. const mediaText = cssTree.generate(ruleData.prelude);
  209. processFontFaceRules(ruleData.block.children, fontsDetails, mediaText, stats);
  210. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && (media.includes("all") || media.includes("screen"))) {
  211. const fontInfo = fontsDetails.get(getFontKey(ruleData));
  212. if (fontInfo) {
  213. fontsDetails.delete(getFontKey(ruleData));
  214. processFontFaceRule(ruleData, fontInfo, stats);
  215. } else {
  216. removedRules.push(cssRule);
  217. }
  218. }
  219. }
  220. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  221. }
  222. function processFontFaceRule(cssRule, fontInfo, stats) {
  223. const fontTest = (fontSource, format) => !fontSource.src.startsWith(EMPTY_URL_SOURCE) && fontSource.format == format;
  224. let woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff2-variations"));
  225. if (!woffFontFound) {
  226. woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff2"));
  227. }
  228. if (!woffFontFound) {
  229. woffFontFound = fontInfo.find(fontSource => fontTest(fontSource, "woff"));
  230. }
  231. stats.fonts.processed += fontInfo.length;
  232. stats.fonts.discarded += fontInfo.length;
  233. if (woffFontFound) {
  234. fontInfo = [woffFontFound];
  235. } else {
  236. let ttfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "truetype-variations"));
  237. if (!ttfFontFound) {
  238. ttfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "truetype"));
  239. }
  240. if (ttfFontFound) {
  241. fontInfo = [ttfFontFound];
  242. } else {
  243. let otfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "opentype"));
  244. if (!otfFontFound) {
  245. otfFontFound = fontInfo.find(fontSource => fontTest(fontSource, "embedded-opentype"));
  246. }
  247. if (otfFontFound) {
  248. fontInfo = [otfFontFound];
  249. }
  250. }
  251. }
  252. stats.fonts.discarded -= fontInfo.length;
  253. const removedNodes = [];
  254. for (let node = cssRule.block.children.head; node; node = node.next) {
  255. if (node.data.property == "src") {
  256. removedNodes.push(node);
  257. }
  258. }
  259. removedNodes.pop();
  260. removedNodes.forEach(node => cssRule.block.children.remove(node));
  261. const srcDeclaration = cssRule.block.children.filter(node => node.property == "src").tail;
  262. if (srcDeclaration) {
  263. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  264. }
  265. }
  266. function getPropertyValue(cssRule, propertyName) {
  267. const property = cssRule.block.children.filter(node => node.property == propertyName).tail;
  268. if (property) {
  269. return cssTree.generate(property.data.value);
  270. }
  271. }
  272. function getFontFamilyNames(declarations) {
  273. let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
  274. let fontFamilyNames = [];
  275. if (fontFamilyName) {
  276. let familyName = "";
  277. fontFamilyName.data.value.children.forEach(node => {
  278. if (node.type == "Operator" && node.value == "," && familyName) {
  279. fontFamilyNames.push(getFontFamily(familyName));
  280. familyName = "";
  281. } else {
  282. familyName += cssTree.generate(node);
  283. }
  284. });
  285. if (familyName) {
  286. fontFamilyNames.push(getFontFamily(familyName));
  287. }
  288. }
  289. const font = declarations.children.filter(node => node.property == "font").tail;
  290. if (font) {
  291. for (let node = font.data.value.children.tail; node && node.data.type != "WhiteSpace"; node = node.prev) {
  292. if (node.data.type == "String" || node.data.type == "Identifier") {
  293. fontFamilyNames.push(getFontFamily(cssTree.generate(node.data)));
  294. }
  295. }
  296. }
  297. return fontFamilyNames;
  298. }
  299. function getFontsDetails(doc, cssRules, fontsDetails) {
  300. cssRules.forEach(cssRule => {
  301. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  302. getFontsDetails(doc, cssRule.block.children, fontsDetails);
  303. } else {
  304. if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  305. const fontKey = getFontKey(cssRule);
  306. let fontInfo = fontsDetails.get(fontKey);
  307. if (!fontInfo) {
  308. fontInfo = [];
  309. fontsDetails.set(fontKey, fontInfo);
  310. }
  311. const src = getPropertyValue(cssRule, "src");
  312. if (src) {
  313. const fontSources = src.match(REGEXP_URL_FUNCTION);
  314. if (fontSources) {
  315. fontSources.forEach(source => fontInfo.unshift(source));
  316. }
  317. }
  318. }
  319. }
  320. });
  321. }
  322. function findFontWeight(fontWeight, fontWeights) {
  323. let foundWeight;
  324. if (fontWeight >= 400 && fontWeight <= 500) {
  325. foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
  326. if (!foundWeight) {
  327. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  328. }
  329. if (!foundWeight) {
  330. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  331. }
  332. }
  333. if (fontWeight < 400) {
  334. foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
  335. if (!foundWeight) {
  336. foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
  337. }
  338. }
  339. if (fontWeight > 500) {
  340. foundWeight = fontWeights.find(weight => weight >= fontWeight);
  341. if (!foundWeight) {
  342. foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
  343. }
  344. }
  345. return foundWeight;
  346. }
  347. function findDescendingFontWeight(fontWeight, fontWeights) {
  348. return fontWeights.slice().reverse().find(weight => weight < fontWeight);
  349. }
  350. function findAscendingFontWeight(fontWeight, fontWeights) {
  351. return fontWeights.find(weight => weight > fontWeight);
  352. }
  353. function getPseudoElementsContent(cssRules) {
  354. return cssRules.toArray().map(cssRule => {
  355. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  356. return getPseudoElementsContent(cssRule.block.children);
  357. } else if (cssRule.type == "Rule") {
  358. const selector = cssTree.generate(cssRule.prelude); // TODO use OM
  359. if (testPseudoElements(selector)) {
  360. return getPropertyValue(cssRule, "content");
  361. }
  362. }
  363. }).join("");
  364. }
  365. function testFontVariant(fontInfo, fontVariant) {
  366. return fontInfo.fontVariant == fontVariant || "normal" || fontInfo.fontVariant == fontVariant || "common-ligatures";
  367. }
  368. function testUnicodeRange(docContent, unicodeRange) {
  369. if (unicodeRange) {
  370. const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
  371. let invalid;
  372. const result = unicodeRanges.filter(rangeValue => {
  373. const range = rangeValue.split(REGEXP_DASH);
  374. let regExpString;
  375. if (range.length == 2) {
  376. range[0] = transformRange(range[0]);
  377. regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
  378. }
  379. if (range.length == 1) {
  380. if (range[0].includes("?")) {
  381. const firstRange = transformRange(range[0]);
  382. const secondRange = firstRange;
  383. regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
  384. } else {
  385. regExpString = "[" + transformRange(range[0]) + "]";
  386. }
  387. }
  388. if (regExpString) {
  389. try {
  390. return (new RegExp(regExpString, "u")).test(docContent);
  391. } catch (error) {
  392. invalid = true;
  393. return false;
  394. }
  395. }
  396. return true;
  397. });
  398. return !invalid && (!unicodeRanges.length || result.length);
  399. }
  400. return true;
  401. }
  402. function testPseudoElements(selectorText) {
  403. let indexSelector = 0, found;
  404. selectorText = selectorText.toLowerCase();
  405. while (indexSelector < PSEUDO_ELEMENTS.length && !found) {
  406. found = selectorText.includes(PSEUDO_ELEMENTS[indexSelector]);
  407. if (!found) {
  408. indexSelector++;
  409. }
  410. }
  411. return found;
  412. }
  413. function transformRange(range) {
  414. range = range.replace(REGEXP_STARTS_U_PLUS, "");
  415. while (range.length < 6) {
  416. range = "0" + range;
  417. }
  418. return "\\u{" + range + "}";
  419. }
  420. function getFontKey(cssRule) {
  421. return JSON.stringify([
  422. getFontFamily(getPropertyValue(cssRule, "font-family")),
  423. getFontWeight(getPropertyValue(cssRule, "font-weight") || "400"),
  424. getPropertyValue(cssRule, "font-style") || "normal",
  425. getPropertyValue(cssRule, "unicode-range"),
  426. getFontStretch(getPropertyValue(cssRule, "font-stretch")),
  427. getPropertyValue(cssRule, "font-variant") || "normal",
  428. getPropertyValue(cssRule, "font-feature-settings"),
  429. getPropertyValue(cssRule, "font-variation-settings")
  430. ]);
  431. }
  432. function getFontFamily(string = "") {
  433. string = string.toLowerCase().trim();
  434. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  435. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  436. } else {
  437. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  438. }
  439. return string.trim();
  440. }
  441. function getFontWeight(weight) {
  442. return FONT_WEIGHTS[weight] || weight;
  443. }
  444. function getFontStretch(stretch) {
  445. return FONT_STRETCHES[stretch] || stretch;
  446. }
  447. })();