css-fonts-minifier.js 18 KB

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