doc-helper.js 15 KB

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