doc-helper.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 fontFaceProxy */
  21. this.docHelper = this.docHelper || (() => {
  22. const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-single-file-removed-content";
  23. const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-single-file-preserved-space-element";
  24. const WIN_ID_ATTRIBUTE_NAME = "data-frame-tree-win-id";
  25. const IMAGE_ATTRIBUTE_NAME = "data-single-file-image";
  26. const INPUT_VALUE_ATTRIBUTE_NAME = "data-single-file-value";
  27. const SHEET_ATTRIBUTE_NAME = "data-single-file-sheet";
  28. const IGNORED_REMOVED_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT"];
  29. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  30. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  31. const FONT_WEIGHTS = {
  32. normal: "400",
  33. bold: "700"
  34. };
  35. return {
  36. preProcessDoc,
  37. postProcessDoc,
  38. serialize,
  39. windowIdAttributeName,
  40. preservedSpaceAttributeName,
  41. removedContentAttributeName,
  42. imagesAttributeName,
  43. inputValueAttributeName,
  44. sheetAttributeName
  45. };
  46. function preProcessDoc(doc, win, options) {
  47. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  48. doc.querySelectorAll("noscript").forEach(element => {
  49. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  50. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  51. disabledNoscriptElement.hidden = true;
  52. element.parentElement.replaceChild(disabledNoscriptElement, element);
  53. });
  54. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  55. let canvasData, imageData, usedFonts;
  56. if (win) {
  57. canvasData = getCanvasData(doc, win);
  58. imageData = getImageData(doc, win, options);
  59. if (options.removeHiddenElements || options.removeUnusedStyles || options.compressHTML) {
  60. let styles = getStyles(win, doc.body);
  61. if (options.removeHiddenElements) {
  62. const markerRemovedContent = removedContentAttributeName(options.sessionId);
  63. let ignoredTags = JSON.parse(JSON.stringify(IGNORED_REMOVED_TAG_NAMES));
  64. if (!options.removeScripts) {
  65. ignoredTags = ignoredTags.concat("SCRIPT");
  66. }
  67. markHiddenCandidates(win, doc.body, styles, false, markerRemovedContent, new Set(), ignoredTags);
  68. markHiddenElements(win, doc.body, markerRemovedContent);
  69. doc.querySelectorAll("iframe").forEach(element => {
  70. const boundingRect = element.getBoundingClientRect();
  71. if (element.hidden || element.style.display == "none" || boundingRect.width <= 1 && boundingRect.height <= 1) {
  72. element.setAttribute(markerRemovedContent, "");
  73. }
  74. });
  75. styles = new Map(Array.from(styles).filter(([element]) => element.getAttribute(markerRemovedContent) != ""));
  76. }
  77. if (options.removeUnusedStyles) {
  78. usedFonts = getUsedFonts(styles);
  79. }
  80. if (options.compressHTML) {
  81. styles.forEach((style, element) => {
  82. if (style.whiteSpace.startsWith("pre")) {
  83. element.setAttribute(preservedSpaceAttributeName(options.sessionId), "");
  84. }
  85. });
  86. }
  87. }
  88. }
  89. retrieveInputValues(doc, options);
  90. return {
  91. canvasData,
  92. fontsData: getFontsData(doc),
  93. stylesheetContents: getStylesheetContents(doc),
  94. imageData,
  95. postersData: getPostersData(doc),
  96. usedFonts
  97. };
  98. }
  99. function getUsedFonts(styles) {
  100. const usedFonts = new Set();
  101. styles.forEach(style => {
  102. const fontFamilyNames = style.fontFamily.split(",");
  103. fontFamilyNames.forEach(fontFamilyName => {
  104. style.fontFamily = removeQuotes(fontFamilyName);
  105. usedFonts.add(getFontKey(style));
  106. });
  107. });
  108. return Array.from(usedFonts).map(key => {
  109. const [fontFamily, fontWeight, fontStyle, fontVariant] = JSON.parse(key);
  110. return { fontFamily, fontWeight, fontStyle, fontVariant };
  111. });
  112. }
  113. function getStyles(win, element, styles = new Map()) {
  114. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  115. elements.forEach(element => {
  116. getStyles(win, element, styles);
  117. const computedStyle = win.getComputedStyle(element);
  118. styles.set(element, {
  119. display: computedStyle.getPropertyValue("display"),
  120. opacity: computedStyle.getPropertyValue("opacity"),
  121. visibility: computedStyle.getPropertyValue("visibility"),
  122. fontFamily: computedStyle.getPropertyValue("font-family"),
  123. fontWeight: getFontWeight(computedStyle.getPropertyValue("font-weight")),
  124. fontStyle: computedStyle.getPropertyValue("font-style") || "normal",
  125. fontVariant: computedStyle.getPropertyValue("font-variant") || "normal",
  126. whiteSpace: computedStyle.getPropertyValue("white-space")
  127. });
  128. });
  129. return styles;
  130. }
  131. function markHiddenCandidates(win, element, styles, elementHidden, markerRemovedContent, removedCandidates, ignoredTags) {
  132. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  133. elements.forEach(element => markHiddenCandidates(win, element, styles, elementHidden || testHiddenElement(element, styles.get(element)), markerRemovedContent, removedCandidates, ignoredTags));
  134. if (elementHidden && !ignoredTags.includes(element.tagName)) {
  135. if (elements.length) {
  136. if (!elements.find(element => !removedCandidates.has(element))) {
  137. removedCandidates.add(element);
  138. elements.forEach(element => element.setAttribute(markerRemovedContent, ""));
  139. }
  140. } else {
  141. removedCandidates.add(element);
  142. }
  143. }
  144. }
  145. function markHiddenElements(win, element, markerRemovedContent) {
  146. const elements = Array.from(element.childNodes).filter(node => node.nodeType == win.Node.ELEMENT_NODE);
  147. if (element.getAttribute(markerRemovedContent) == "") {
  148. element.removeAttribute(markerRemovedContent);
  149. } else {
  150. elements.forEach(element => markHiddenElements(win, element, markerRemovedContent));
  151. }
  152. }
  153. function testHiddenElement(element, style) {
  154. let hidden = false;
  155. if (style) {
  156. hidden = style.display == "none";
  157. if (!hidden && (style.opacity == "0" || style.visibility == "hidden")) {
  158. const boundingRect = element.getBoundingClientRect();
  159. hidden = !boundingRect.width && !boundingRect.height;
  160. }
  161. }
  162. return Boolean(hidden);
  163. }
  164. function postProcessDoc(doc, options) {
  165. doc.querySelectorAll("disabled-noscript").forEach(element => {
  166. const noscriptElement = doc.createElement("noscript");
  167. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  168. element.parentElement.replaceChild(noscriptElement, element);
  169. });
  170. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  171. if (options.removeHiddenElements) {
  172. doc.querySelectorAll("[" + removedContentAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(removedContentAttributeName(options.sessionId)));
  173. }
  174. if (options.compressHTML) {
  175. doc.querySelectorAll("[" + preservedSpaceAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(preservedSpaceAttributeName(options.sessionId)));
  176. }
  177. doc.querySelectorAll("[" + imagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(imagesAttributeName(options.sessionId)));
  178. doc.querySelectorAll("[" + inputValueAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(inputValueAttributeName(options.sessionId)));
  179. }
  180. function imagesAttributeName(sessionId) {
  181. return IMAGE_ATTRIBUTE_NAME + (sessionId || "");
  182. }
  183. function preservedSpaceAttributeName(sessionId) {
  184. return PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + (sessionId || "");
  185. }
  186. function removedContentAttributeName(sessionId) {
  187. return REMOVED_CONTENT_ATTRIBUTE_NAME + (sessionId || "");
  188. }
  189. function windowIdAttributeName(sessionId) {
  190. return WIN_ID_ATTRIBUTE_NAME + (sessionId || "");
  191. }
  192. function inputValueAttributeName(sessionId) {
  193. return INPUT_VALUE_ATTRIBUTE_NAME + (sessionId || "");
  194. }
  195. function sheetAttributeName(sessionId) {
  196. return SHEET_ATTRIBUTE_NAME + (sessionId || "");
  197. }
  198. function getCanvasData(doc, win) {
  199. if (doc) {
  200. const canvasData = [];
  201. doc.querySelectorAll("canvas").forEach(canvasElement => {
  202. try {
  203. const size = getSize(win, canvasElement);
  204. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: size.width, height: size.height });
  205. } catch (error) {
  206. canvasData.push(null);
  207. }
  208. });
  209. return canvasData;
  210. }
  211. }
  212. function getStylesheetContents(doc) {
  213. if (doc) {
  214. const contents = [];
  215. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  216. let stylesheet;
  217. try {
  218. const tempStyleElement = doc.createElement("style");
  219. tempStyleElement.textContent = styleElement.textContent;
  220. doc.body.appendChild(tempStyleElement);
  221. stylesheet = tempStyleElement.sheet;
  222. tempStyleElement.remove();
  223. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  224. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n");
  225. }
  226. } catch (error) {
  227. /* ignored */
  228. }
  229. });
  230. return contents;
  231. }
  232. }
  233. function getImageData(doc, win, options) {
  234. if (doc) {
  235. const data = [];
  236. doc.querySelectorAll("img").forEach((imageElement, imageElementIndex) => {
  237. imageElement.setAttribute(imagesAttributeName(options.sessionId), imageElementIndex);
  238. const imageData = {
  239. currentSrc: (options.lazyLoadImages && imageElement.getAttribute("data-lazy-loaded-src")) || imageElement.currentSrc
  240. };
  241. imageElement.removeAttribute("data-lazy-loaded-src");
  242. const computedStyle = win.getComputedStyle(imageElement);
  243. if (computedStyle) {
  244. imageData.size = getSize(win, imageElement);
  245. if ((!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none") && (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
  246. imageData.replaceable = true;
  247. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  248. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  249. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  250. }
  251. }
  252. data.push(imageData);
  253. });
  254. return data;
  255. }
  256. }
  257. function getSize(win, imageElement) {
  258. const computedStyle = win.getComputedStyle(imageElement);
  259. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  260. paddingLeft = getWidth("padding-left", computedStyle);
  261. paddingRight = getWidth("padding-right", computedStyle);
  262. paddingTop = getWidth("padding-top", computedStyle);
  263. paddingBottom = getWidth("padding-bottom", computedStyle);
  264. if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
  265. borderLeft = getWidth("border-left-width", computedStyle);
  266. borderRight = getWidth("border-right-width", computedStyle);
  267. borderTop = getWidth("border-top-width", computedStyle);
  268. borderBottom = getWidth("border-bottom-width", computedStyle);
  269. } else {
  270. borderLeft = borderRight = borderTop = borderBottom = 0;
  271. }
  272. const width = imageElement.clientWidth;
  273. const height = imageElement.clientHeight;
  274. if (width >= 0 && height >= 0 && paddingLeft >= 0 && paddingRight >= 0 && paddingTop >= 0 && paddingBottom >= 0 && borderLeft >= 0 && borderRight >= 0 && borderTop >= 0 && borderBottom >= 0) {
  275. return {
  276. width: (paddingLeft || paddingRight || borderLeft || borderRight) && (width - paddingLeft - paddingRight - borderLeft - borderRight) + "px",
  277. pxWidth: width - paddingLeft - paddingRight - borderLeft - borderRight,
  278. height: (paddingTop || paddingBottom || borderTop || borderBottom) && (height - paddingTop - paddingBottom - borderTop - borderBottom) + "px",
  279. pxHeight: height - paddingTop - paddingBottom - borderTop - borderBottom,
  280. };
  281. }
  282. }
  283. function getWidth(styleName, computedStyle) {
  284. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  285. return parseFloat(computedStyle.getPropertyValue(styleName));
  286. }
  287. }
  288. function getPostersData(doc) {
  289. if (doc) {
  290. const postersData = [];
  291. doc.querySelectorAll("video").forEach(videoElement => {
  292. if (videoElement.poster) {
  293. postersData.push(null);
  294. } else {
  295. const canvasElement = doc.createElement("canvas");
  296. const context = canvasElement.getContext("2d");
  297. canvasElement.width = videoElement.clientWidth;
  298. canvasElement.height = videoElement.clientHeight;
  299. try {
  300. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  301. postersData.push(canvasElement.toDataURL("image/png", ""));
  302. } catch (error) {
  303. postersData.push(null);
  304. }
  305. }
  306. });
  307. return postersData;
  308. }
  309. }
  310. function getFontsData() {
  311. if (typeof fontFaceProxy != "undefined") {
  312. return fontFaceProxy.getFontsData();
  313. }
  314. }
  315. function retrieveInputValues(doc, options) {
  316. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  317. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  318. doc.querySelectorAll("select").forEach(select => {
  319. select.querySelectorAll("option").forEach(option => {
  320. if (option.selected) {
  321. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  322. }
  323. });
  324. });
  325. }
  326. function serialize(doc) {
  327. const docType = doc.doctype;
  328. let docTypeString = "";
  329. if (docType) {
  330. docTypeString = "<!DOCTYPE " + docType.nodeName;
  331. if (docType.publicId) {
  332. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  333. if (docType.systemId) {
  334. docTypeString += " \"" + docType.systemId + "\"";
  335. }
  336. } else if (docType.systemId) {
  337. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  338. } if (docType.internalSubset) {
  339. docTypeString += " [" + docType.internalSubset + "]";
  340. }
  341. docTypeString += "> ";
  342. }
  343. return docTypeString + doc.documentElement.outerHTML;
  344. }
  345. function getFontKey(style) {
  346. return JSON.stringify([
  347. style.fontFamily,
  348. style.fontWeight,
  349. style.fontStyle,
  350. style.fontVariant
  351. ]);
  352. }
  353. function removeQuotes(string) {
  354. string = string.toLowerCase().trim();
  355. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  356. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  357. } else {
  358. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  359. }
  360. return string.trim();
  361. }
  362. function getFontWeight(weight) {
  363. return FONT_WEIGHTS[weight] || weight;
  364. }
  365. })();