doc-helper.js 17 KB

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