1
0

html-images-minifier.js 9.0 KB

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