content-hooks-frames-web.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global window, Event */
  24. (() => {
  25. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  26. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  27. const LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_START_EVENT = "single-file-load-deferred-images-keep-zoom-level-start";
  28. const LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT = "single-file-load-deferred-images-keep-zoom-level-end";
  29. const LOAD_DEFERRED_IMAGES_RESET_ZOOM_LEVEL_END_EVENT = "single-file-load-deferred-images-keep-zoom-level-reset";
  30. const BLOCK_COOKIES_START_EVENT = "single-file-block-cookies-start";
  31. const BLOCK_COOKIES_END_EVENT = "single-file-block-cookies-end";
  32. const BLOCK_STORAGE_START_EVENT = "single-file-block-storage-start";
  33. const BLOCK_STORAGE_END_EVENT = "single-file-block-storage-end";
  34. const LAZY_LOAD_ATTRIBUTE = "single-file-lazy-load";
  35. const LOAD_IMAGE_EVENT = "single-file-load-image";
  36. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  37. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  38. const FONT_STYLE_PROPERTIES = {
  39. family: "font-family",
  40. style: "font-style",
  41. weight: "font-weight",
  42. stretch: "font-stretch",
  43. unicodeRange: "unicode-range",
  44. variant: "font-variant",
  45. featureSettings: "font-feature-settings"
  46. };
  47. const addEventListener = window.addEventListener;
  48. const dispatchEvent = window.dispatchEvent;
  49. const CustomEvent = window.CustomEvent;
  50. const document = window.document;
  51. const screen = window.screen;
  52. const Element = window.Element;
  53. const UIEvent = window.UIEvent;
  54. const FileReader = window.FileReader;
  55. const Blob = window.Blob;
  56. const console = window.console;
  57. const warn = (console && console.warn) || (() => { });
  58. const observers = new Map();
  59. const observedElements = new Map();
  60. addEventListener.call(window, LOAD_DEFERRED_IMAGES_START_EVENT, () => loadDeferredImagesStart());
  61. addEventListener.call(window, LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_START_EVENT, () => loadDeferredImagesStart(true));
  62. function loadDeferredImagesStart(keepZoomLevel) {
  63. const scrollingElement = document.scrollingElement || document.documentElement;
  64. const clientHeight = scrollingElement.clientHeight;
  65. const clientWidth = scrollingElement.clientWidth;
  66. const scrollHeight = Math.max(scrollingElement.scrollHeight - clientHeight, clientHeight);
  67. const scrollWidth = Math.max(scrollingElement.scrollWidth - clientWidth, clientWidth);
  68. document.querySelectorAll("[loading=lazy]").forEach(element => {
  69. element.loading = "eager";
  70. element.setAttribute(LAZY_LOAD_ATTRIBUTE, "");
  71. });
  72. if (!keepZoomLevel) {
  73. scrollingElement.__defineGetter__("clientHeight", () => scrollHeight);
  74. scrollingElement.__defineGetter__("clientWidth", () => scrollWidth);
  75. screen.__defineGetter__("height", () => scrollHeight);
  76. screen.__defineGetter__("width", () => scrollWidth);
  77. if (!window._singleFile_getBoundingClientRect) {
  78. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  79. Element.prototype.getBoundingClientRect = function () {
  80. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  81. if (this == scrollingElement) {
  82. boundingRect.__defineGetter__("height", () => scrollHeight);
  83. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  84. boundingRect.__defineGetter__("width", () => scrollWidth);
  85. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  86. }
  87. return boundingRect;
  88. };
  89. window._singleFile_innerHeight = window.innerHeight;
  90. window._singleFile_innerWidth = window.innerWidth;
  91. window.__defineGetter__("innerHeight", () => scrollHeight);
  92. window.__defineGetter__("innerWidth", () => scrollWidth);
  93. }
  94. }
  95. if (!window._singleFileImage) {
  96. const Image = window.Image;
  97. window._singleFileImage = window.Image;
  98. window.__defineGetter__("Image", function () {
  99. return function () {
  100. const image = new Image(...arguments);
  101. const result = new Image(...arguments);
  102. result.__defineSetter__("src", function (value) {
  103. image.src = value;
  104. dispatchEvent.call(window, new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  105. });
  106. result.__defineGetter__("src", function () {
  107. return image.src;
  108. });
  109. result.__defineSetter__("srcset", function (value) {
  110. dispatchEvent.call(window, new CustomEvent(LOAD_IMAGE_EVENT));
  111. image.srcset = value;
  112. });
  113. result.__defineGetter__("srcset", function () {
  114. return image.srcset;
  115. });
  116. image.onload = image.onloadend = image.onerror = event => {
  117. dispatchEvent.call(window, new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  118. result.dispatchEvent(new UIEvent(event.type, event));
  119. };
  120. if (image.decode) {
  121. result.decode = () => image.decode();
  122. }
  123. return result;
  124. };
  125. });
  126. }
  127. let zoomFactorX, zoomFactorY;
  128. if (keepZoomLevel) {
  129. zoomFactorX = clientHeight / scrollHeight;
  130. zoomFactorY = clientWidth / scrollWidth;
  131. } else {
  132. zoomFactorX = (clientHeight + window.scrollY) / scrollHeight;
  133. zoomFactorY = (clientWidth + window.scrollX) / scrollWidth;
  134. }
  135. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  136. if (zoomFactor < 1) {
  137. const transform = document.documentElement.style.getPropertyValue("transform");
  138. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  139. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  140. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  141. const minHeight = document.documentElement.style.getPropertyValue("min-height");
  142. const minHeightPriority = document.documentElement.style.getPropertyPriority("min-height");
  143. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  144. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  145. document.documentElement.style.setProperty("min-height", (100 / zoomFactor) + "vh", "important");
  146. dispatchEvent.call(window, new UIEvent("resize"));
  147. dispatchEvent.call(window, new Event("scroll"));
  148. if (keepZoomLevel) {
  149. document.documentElement.style.setProperty("-sf-transform", transform, transformPriority);
  150. document.documentElement.style.setProperty("-sf-transform-origin", transformOrigin, transformOriginPriority);
  151. document.documentElement.style.setProperty("-sf-min-height", minHeight, minHeightPriority);
  152. } else {
  153. document.documentElement.style.setProperty("transform", transform, transformPriority);
  154. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  155. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  156. }
  157. }
  158. if (!keepZoomLevel) {
  159. dispatchEvent.call(window, new UIEvent("resize"));
  160. dispatchEvent.call(window, new Event("scroll"));
  161. const docBoundingRect = scrollingElement.getBoundingClientRect();
  162. [...observers].forEach(([intersectionObserver, observer]) => {
  163. const rootBoundingRect = observer.options && observer.options.root && observer.options.root.getBoundingClientRect();
  164. const targetElements = observedElements.get(intersectionObserver);
  165. if (targetElements) {
  166. observer.callback(targetElements.map(target => {
  167. const boundingClientRect = target.getBoundingClientRect();
  168. const isIntersecting = true;
  169. const intersectionRatio = 1;
  170. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  171. const time = 0;
  172. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  173. }), intersectionObserver);
  174. }
  175. });
  176. }
  177. }
  178. addEventListener.call(window, LOAD_DEFERRED_IMAGES_END_EVENT, () => loadDeferredImagesEnd());
  179. addEventListener.call(window, LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT, () => loadDeferredImagesEnd(true));
  180. addEventListener.call(window, LOAD_DEFERRED_IMAGES_RESET_ZOOM_LEVEL_END_EVENT, () => {
  181. const transform = document.documentElement.style.getPropertyValue("-sf-transform");
  182. const transformPriority = document.documentElement.style.getPropertyPriority("-sf-transform");
  183. const transformOrigin = document.documentElement.style.getPropertyValue("-sf-transform-origin");
  184. const transformOriginPriority = document.documentElement.style.getPropertyPriority("-sf-transform-origin");
  185. const minHeight = document.documentElement.style.getPropertyValue("-sf-min-height");
  186. const minHeightPriority = document.documentElement.style.getPropertyPriority("-sf-min-height");
  187. document.documentElement.style.setProperty("transform", transform, transformPriority);
  188. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  189. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  190. document.documentElement.style.removeProperty("-sf-transform");
  191. document.documentElement.style.removeProperty("-sf-transform-origin");
  192. document.documentElement.style.removeProperty("-sf-min-height");
  193. });
  194. function loadDeferredImagesEnd(keepZoomLevel) {
  195. const scrollingElement = document.scrollingElement || document.documentElement;
  196. document.querySelectorAll("[" + LAZY_LOAD_ATTRIBUTE + "]").forEach(element => {
  197. element.loading = "lazy";
  198. element.removeAttribute(LAZY_LOAD_ATTRIBUTE);
  199. });
  200. if (!keepZoomLevel) {
  201. delete scrollingElement.clientHeight;
  202. delete scrollingElement.clientWidth;
  203. delete screen.height;
  204. delete screen.width;
  205. if (window._singleFile_getBoundingClientRect) {
  206. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  207. window.innerHeight = window._singleFile_innerHeight;
  208. window.innerWidth = window._singleFile_innerWidth;
  209. delete window._singleFile_getBoundingClientRect;
  210. delete window._singleFile_innerHeight;
  211. delete window._singleFile_innerWidth;
  212. }
  213. }
  214. if (window._singleFileImage) {
  215. delete window.Image;
  216. window.Image = window._singleFileImage;
  217. delete window._singleFileImage;
  218. }
  219. if (!keepZoomLevel) {
  220. dispatchEvent.call(window, new UIEvent("resize"));
  221. dispatchEvent.call(window, new Event("scroll"));
  222. }
  223. }
  224. addEventListener.call(window, BLOCK_COOKIES_START_EVENT, () => {
  225. try {
  226. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  227. } catch (error) {
  228. // ignored
  229. }
  230. });
  231. addEventListener.call(window, BLOCK_COOKIES_END_EVENT, () => {
  232. delete document.cookie;
  233. });
  234. addEventListener.call(window, BLOCK_STORAGE_START_EVENT, () => {
  235. if (!window._singleFile_localStorage) {
  236. window._singleFile_localStorage = window.localStorage;
  237. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  238. }
  239. if (!window._singleFile_indexedDB) {
  240. window._singleFile_indexedDB = window.indexedDB;
  241. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  242. }
  243. });
  244. addEventListener.call(window, BLOCK_STORAGE_END_EVENT, () => {
  245. if (window._singleFile_localStorage) {
  246. delete window.localStorage;
  247. window.localStorage = window._singleFile_localStorage;
  248. delete window._singleFile_localStorage;
  249. }
  250. if (!window._singleFile_indexedDB) {
  251. delete window.indexedDB;
  252. window.indexedDB = window._singleFile_indexedDB;
  253. delete window._singleFile_indexedDB;
  254. }
  255. });
  256. if (window.FontFace) {
  257. const FontFace = window.FontFace;
  258. let warningFontFaceDisplayed;
  259. window.FontFace = function () {
  260. if (!warningFontFaceDisplayed) {
  261. warn.call(console, "SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  262. warningFontFaceDisplayed = true;
  263. }
  264. const detail = {};
  265. detail["font-family"] = arguments[0];
  266. detail.src = arguments[1];
  267. const descriptors = arguments[2];
  268. if (descriptors) {
  269. Object.keys(descriptors).forEach(descriptor => {
  270. if (FONT_STYLE_PROPERTIES[descriptor]) {
  271. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  272. }
  273. });
  274. }
  275. if (detail.src instanceof ArrayBuffer) {
  276. const reader = new FileReader();
  277. reader.readAsDataURL(new Blob([detail.src]));
  278. reader.addEventListener("load", () => {
  279. detail.src = "url(" + reader.result + ")";
  280. dispatchEvent.call(window, new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  281. });
  282. } else {
  283. dispatchEvent.call(window, new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  284. }
  285. return new FontFace(...arguments);
  286. };
  287. window.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  288. }
  289. if (window.IntersectionObserver) {
  290. const IntersectionObserver = window.IntersectionObserver;
  291. let warningIntersectionObserverDisplayed;
  292. window.IntersectionObserver = function () {
  293. if (!warningIntersectionObserverDisplayed) {
  294. warn.call(console, "SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  295. warningIntersectionObserverDisplayed = true;
  296. }
  297. const intersectionObserver = new IntersectionObserver(...arguments);
  298. const observeIntersection = IntersectionObserver.prototype.observe || intersectionObserver.observe;
  299. const unobserveIntersection = IntersectionObserver.prototype.unobserve || intersectionObserver.unobserve;
  300. const callback = arguments[0];
  301. const options = arguments[1];
  302. if (observeIntersection) {
  303. intersectionObserver.observe = function (targetElement) {
  304. let targetElements = observedElements.get(intersectionObserver);
  305. if (!targetElements) {
  306. targetElements = [];
  307. observedElements.set(intersectionObserver, targetElements);
  308. }
  309. targetElements.push(targetElement);
  310. return observeIntersection.call(intersectionObserver, targetElement);
  311. };
  312. }
  313. if (unobserveIntersection) {
  314. intersectionObserver.unobserve = function (targetElement) {
  315. let targetElements = observedElements.get(intersectionObserver);
  316. if (targetElements) {
  317. targetElements = targetElements.filter(element => element != targetElement);
  318. if (targetElements.length) {
  319. observedElements.set(intersectionObserver, targetElements);
  320. } else {
  321. observedElements.delete(intersectionObserver);
  322. observers.delete(intersectionObserver);
  323. }
  324. }
  325. return unobserveIntersection.call(intersectionObserver, targetElement);
  326. };
  327. }
  328. observers.set(intersectionObserver, { callback, options });
  329. return intersectionObserver;
  330. };
  331. window.IntersectionObserver.prototype = IntersectionObserver.prototype;
  332. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  333. }
  334. })();