html-images-minifier.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 CSSRule, docHelper, cssWhat, lazyLoader */
  21. this.imagesMinifier = this.imagesMinifier || (() => {
  22. const DEBUG = false;
  23. const SVG_NS = "http://www.w3.org/2000/svg";
  24. return {
  25. process: (doc, mediaAllInfo, options) => {
  26. const imageGroups = getImageGroups(doc);
  27. let duplicates = new Set();
  28. const duplicateURLs = [];
  29. imageGroups.forEach((elements, src) => {
  30. if (elements.length > 1 && src && src != options.baseURI) {
  31. elements.forEach(element => duplicates.add(element));
  32. duplicateURLs.push(src);
  33. }
  34. });
  35. if (duplicateURLs.length) {
  36. processStyleSheets(doc, duplicates, mediaAllInfo);
  37. processImages(doc, duplicates, duplicateURLs, options);
  38. }
  39. }
  40. };
  41. function getImageGroups(doc) {
  42. const imageGroups = new Map();
  43. doc.querySelectorAll("img[src]:not([srcset])").forEach(imageElement => {
  44. if (imageElement.src) {
  45. let imageInfo = imageGroups.get(imageElement.src);
  46. if (!imageInfo) {
  47. imageInfo = [];
  48. imageGroups.set(imageElement.src, imageInfo);
  49. }
  50. imageInfo.push(imageElement);
  51. }
  52. });
  53. return imageGroups;
  54. }
  55. function processStyleSheets(doc, duplicates, mediaAllInfo) {
  56. const matchedSelectors = getMatchedSelectors(duplicates, mediaAllInfo);
  57. doc.querySelectorAll("style").forEach((styleElement, sheetIndex) => {
  58. if (styleElement.sheet) {
  59. const cssRules = styleElement.sheet.cssRules;
  60. let mediaInfo;
  61. if (styleElement.media && styleElement.media != "all") {
  62. mediaInfo = mediaAllInfo.medias.get(sheetIndex + "-" + styleElement.media);
  63. } else {
  64. mediaInfo = mediaAllInfo;
  65. }
  66. styleElement.textContent = processRules(doc, cssRules, sheetIndex, mediaInfo, matchedSelectors);
  67. }
  68. });
  69. }
  70. function processImages(doc, duplicates, duplicateURLs, options) {
  71. const svgElement = doc.createElementNS(SVG_NS, "svg");
  72. const defsElement = doc.createElementNS(SVG_NS, "defs");
  73. svgElement.setAttributeNS(SVG_NS, "width", 0);
  74. svgElement.setAttributeNS(SVG_NS, "height", 0);
  75. svgElement.setAttributeNS(SVG_NS, "style", "display:none!important");
  76. svgElement.appendChild(defsElement);
  77. duplicateURLs.forEach((src, srcIndex) => {
  78. const imageElement = doc.createElementNS(SVG_NS, "image");
  79. imageElement.setAttribute("xlink:href", src);
  80. imageElement.id = "single-file-" + srcIndex;
  81. defsElement.appendChild(imageElement);
  82. });
  83. doc.body.appendChild(svgElement);
  84. const ignoredAttributeNames = [];
  85. if (options.lazyLoadImages) {
  86. const imageSelectors = lazyLoader.imageSelectors;
  87. Object.keys(imageSelectors.src).forEach(selector => ignoredAttributeNames.push(imageSelectors.src[selector]));
  88. Object.keys(imageSelectors.srcset).forEach(selector => ignoredAttributeNames.push(imageSelectors.srcset[selector]));
  89. }
  90. doc.querySelectorAll("img").forEach(imgElement => {
  91. let replaceImage = !options.lazyLoadImages;
  92. if (!replaceImage) {
  93. replaceImage = !Object.keys(ignoredAttributeNames).map(key => ignoredAttributeNames[key]).find(attributeName => imgElement.getAttribute(attributeName));
  94. }
  95. if (replaceImage && duplicates.has(imgElement)) {
  96. const urlIndex = duplicateURLs.indexOf(imgElement.src);
  97. if (urlIndex != -1) {
  98. const dataAttributeName = docHelper.imagesAttributeName(options.sessionId);
  99. const imageData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  100. const width = (imageData.naturalWidth > 1 && imageData.naturalWidth) || imageData.width;
  101. const height = (imageData.naturalHeight > 1 && imageData.naturalHeight) || imageData.height;
  102. if (width > 1 && height > 1) {
  103. const svgElement = doc.createElementNS(SVG_NS, "svg");
  104. const useElement = doc.createElementNS(SVG_NS, "use");
  105. svgElement.appendChild(useElement);
  106. imgElement.getAttributeNames().forEach(attributeName => attributeName != "src" && svgElement.setAttribute(attributeName, imgElement.getAttribute(attributeName)));
  107. svgElement.setAttributeNS(SVG_NS, "viewBox", "0 0 " + width + " " + height);
  108. svgElement.setAttributeNS(SVG_NS, "width", imageData.clientWidth);
  109. svgElement.setAttributeNS(SVG_NS, "height", imageData.clientHeight);
  110. svgElement.setAttributeNS(SVG_NS, "preserveAspectRatio", "none");
  111. useElement.setAttributeNS(SVG_NS, "xlink:href", "#single-file-" + urlIndex);
  112. const imageElement = doc.getElementById("single-file-" + urlIndex);
  113. if (!imageElement.getAttributeNS(SVG_NS, "width") && !imageElement.getAttributeNS(SVG_NS, "height")) {
  114. imageElement.setAttributeNS(SVG_NS, "viewBox", "0 0 " + width + " " + height);
  115. imageElement.setAttributeNS(SVG_NS, "width", width);
  116. imageElement.setAttributeNS(SVG_NS, "height", height);
  117. }
  118. // svgElement.style.border = "1px solid red";
  119. imgElement.parentElement.replaceChild(svgElement, imgElement);
  120. }
  121. }
  122. }
  123. });
  124. }
  125. function getMatchedSelectors(duplicates, parentMediaInfo, matchedRules = new Map()) {
  126. duplicates.forEach(imageElement => {
  127. let elementInfos = parentMediaInfo.elements.get(imageElement);
  128. if (!elementInfos) {
  129. elementInfos = parentMediaInfo.pseudos.get(imageElement);
  130. }
  131. if (elementInfos) {
  132. elementInfos.forEach(elementInfo => {
  133. if (elementInfo.cssRule) {
  134. let selectorInfo = matchedRules.get(elementInfo.cssRule.selectorText);
  135. if (!selectorInfo) {
  136. matchedRules.set(elementInfo.cssRule.selectorText, elementInfo.selectors);
  137. }
  138. }
  139. });
  140. }
  141. });
  142. parentMediaInfo.medias.forEach(mediaInfo => getMatchedSelectors(duplicates, mediaInfo, matchedRules));
  143. return matchedRules;
  144. }
  145. function processRules(doc, cssRules, sheetIndex, mediaInfo, matchedSelectors) {
  146. let sheetContent = "", mediaRuleIndex = 0;
  147. let startTime;
  148. if (DEBUG && cssRules.length > 1) {
  149. startTime = Date.now();
  150. log(" -- STARTED processRules", "rules.length =", cssRules.length);
  151. }
  152. Array.from(cssRules).forEach(cssRule => {
  153. if (cssRule.type == CSSRule.MEDIA_RULE) {
  154. sheetContent += "@media " + Array.from(cssRule.media).join(",") + "{";
  155. sheetContent += processRules(doc, cssRule.cssRules, sheetIndex, mediaInfo.medias.get("rule-" + sheetIndex + "-" + mediaRuleIndex + "-" + cssRule.media.mediaText), matchedSelectors);
  156. mediaRuleIndex++;
  157. sheetContent += "}";
  158. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  159. const selectors = matchedSelectors.get(cssRule.selectorText);
  160. if (selectors) {
  161. selectors.forEach(selector => {
  162. const newSelector = transformSelector(selector);
  163. if (newSelector) {
  164. selectors.push(newSelector);
  165. }
  166. });
  167. const selectorText = selectors.map(selector => cssWhat.stringify([selector])).join(",");
  168. cssRule.selectorText = selectorText;
  169. }
  170. sheetContent += cssRule.cssText;
  171. } else {
  172. sheetContent += cssRule.cssText;
  173. }
  174. });
  175. if (DEBUG && cssRules.length > 1) {
  176. log(" -- ENDED processRules delay =", Date.now() - startTime);
  177. }
  178. return sheetContent;
  179. }
  180. function transformSelector(selector) {
  181. selector = JSON.parse(JSON.stringify(selector));
  182. let simpleSelector, selectorIndex = selector.length - 1, imageTagFound;
  183. while (selectorIndex >= 0 && !imageTagFound) {
  184. simpleSelector = selector[selectorIndex];
  185. imageTagFound = simpleSelector.type == "tag" && simpleSelector.name == "img";
  186. if (!imageTagFound) {
  187. selectorIndex--;
  188. }
  189. }
  190. if (imageTagFound) {
  191. simpleSelector.name = "svg";
  192. return selector;
  193. }
  194. }
  195. function log(...args) {
  196. console.log("S-File <img-min>", ...args); // eslint-disable-line no-console
  197. }
  198. })();