content-hooks-frames-web.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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_EVENT = "single-file-load-deferred-images-keep-zoom-level-reset";
  30. const LOAD_DEFERRED_IMAGES_RESET_EVENT = "single-file-load-deferred-images-reset";
  31. const BLOCK_COOKIES_START_EVENT = "single-file-block-cookies-start";
  32. const BLOCK_COOKIES_END_EVENT = "single-file-block-cookies-end";
  33. const BLOCK_STORAGE_START_EVENT = "single-file-block-storage-start";
  34. const BLOCK_STORAGE_END_EVENT = "single-file-block-storage-end";
  35. const LAZY_LOAD_ATTRIBUTE = "single-file-lazy-load";
  36. const LOAD_IMAGE_EVENT = "single-file-load-image";
  37. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  38. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  39. const FONT_STYLE_PROPERTIES = {
  40. family: "font-family",
  41. style: "font-style",
  42. weight: "font-weight",
  43. stretch: "font-stretch",
  44. unicodeRange: "unicode-range",
  45. variant: "font-variant",
  46. featureSettings: "font-feature-settings"
  47. };
  48. const addEventListener = (type, listener, options) => window.addEventListener(type, listener, options);
  49. const dispatchEvent = event => window.dispatchEvent(event);
  50. const CustomEvent = window.CustomEvent;
  51. const document = window.document;
  52. const screen = window.screen;
  53. const Element = window.Element;
  54. const UIEvent = window.UIEvent;
  55. const FileReader = window.FileReader;
  56. const Blob = window.Blob;
  57. const console = window.console;
  58. const warn = (console && console.warn && ((...args) => console.warn(...args))) || (() => { });
  59. const observers = new Map();
  60. const observedElements = new Map();
  61. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => loadDeferredImagesStart());
  62. addEventListener(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_START_EVENT, () => loadDeferredImagesStart(true));
  63. function loadDeferredImagesStart(keepZoomLevel) {
  64. const scrollingElement = document.scrollingElement || document.documentElement;
  65. const clientHeight = scrollingElement.clientHeight;
  66. const clientWidth = scrollingElement.clientWidth;
  67. const scrollHeight = Math.max(scrollingElement.scrollHeight - clientHeight, clientHeight);
  68. const scrollWidth = Math.max(scrollingElement.scrollWidth - clientWidth, clientWidth);
  69. document.querySelectorAll("[loading=lazy]").forEach(element => {
  70. element.loading = "eager";
  71. element.setAttribute(LAZY_LOAD_ATTRIBUTE, "");
  72. });
  73. scrollingElement.__defineGetter__("clientHeight", () => scrollHeight);
  74. scrollingElement.__defineGetter__("clientWidth", () => scrollWidth);
  75. screen.__defineGetter__("height", () => scrollHeight);
  76. screen.__defineGetter__("width", () => scrollWidth);
  77. window._singleFile_innerHeight = window.innerHeight;
  78. window._singleFile_innerWidth = window.innerWidth;
  79. window.__defineGetter__("innerHeight", () => scrollHeight);
  80. window.__defineGetter__("innerWidth", () => scrollWidth);
  81. if (!keepZoomLevel) {
  82. if (!window._singleFile_getBoundingClientRect) {
  83. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  84. Element.prototype.getBoundingClientRect = function () {
  85. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  86. if (this == scrollingElement) {
  87. boundingRect.__defineGetter__("height", () => scrollHeight);
  88. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  89. boundingRect.__defineGetter__("width", () => scrollWidth);
  90. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  91. }
  92. return boundingRect;
  93. };
  94. }
  95. }
  96. if (!window._singleFileImage) {
  97. const Image = window.Image;
  98. window._singleFileImage = window.Image;
  99. window.__defineGetter__("Image", function () {
  100. return function () {
  101. const image = new Image(...arguments);
  102. const result = new Image(...arguments);
  103. result.__defineSetter__("src", function (value) {
  104. image.src = value;
  105. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  106. });
  107. result.__defineGetter__("src", function () {
  108. return image.src;
  109. });
  110. result.__defineSetter__("srcset", function (value) {
  111. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT));
  112. image.srcset = value;
  113. });
  114. result.__defineGetter__("srcset", function () {
  115. return image.srcset;
  116. });
  117. image.onload = image.onloadend = image.onerror = event => {
  118. dispatchEvent(new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  119. result.dispatchEvent(new UIEvent(event.type, event));
  120. };
  121. if (image.decode) {
  122. result.decode = () => image.decode();
  123. }
  124. return result;
  125. };
  126. });
  127. }
  128. let zoomFactorX, zoomFactorY;
  129. if (keepZoomLevel) {
  130. zoomFactorX = clientHeight / scrollHeight;
  131. zoomFactorY = clientWidth / scrollWidth;
  132. } else {
  133. zoomFactorX = (clientHeight + window.scrollY) / scrollHeight;
  134. zoomFactorY = (clientWidth + window.scrollX) / scrollWidth;
  135. }
  136. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  137. if (zoomFactor < 1) {
  138. const transform = document.documentElement.style.getPropertyValue("transform");
  139. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  140. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  141. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  142. const minHeight = document.documentElement.style.getPropertyValue("min-height");
  143. const minHeightPriority = document.documentElement.style.getPropertyPriority("min-height");
  144. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  145. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  146. document.documentElement.style.setProperty("min-height", (100 / zoomFactor) + "vh", "important");
  147. dispatchResizeEvent();
  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. dispatchResizeEvent();
  160. const docBoundingRect = scrollingElement.getBoundingClientRect();
  161. [...observers].forEach(([intersectionObserver, observer]) => {
  162. const rootBoundingRect = observer.options && observer.options.root && observer.options.root.getBoundingClientRect();
  163. const targetElements = observedElements.get(intersectionObserver);
  164. if (targetElements) {
  165. observer.callback(targetElements.map(target => {
  166. const boundingClientRect = target.getBoundingClientRect();
  167. const isIntersecting = true;
  168. const intersectionRatio = 1;
  169. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  170. const time = 0;
  171. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  172. }), intersectionObserver);
  173. }
  174. });
  175. }
  176. }
  177. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => loadDeferredImagesEnd());
  178. addEventListener(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT, () => loadDeferredImagesEnd(true));
  179. addEventListener(LOAD_DEFERRED_IMAGES_RESET_EVENT, resetScreenSize);
  180. addEventListener(LOAD_DEFERRED_IMAGES_RESET_ZOOM_LEVEL_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. resetScreenSize();
  194. });
  195. function loadDeferredImagesEnd(keepZoomLevel) {
  196. document.querySelectorAll("[" + LAZY_LOAD_ATTRIBUTE + "]").forEach(element => {
  197. element.loading = "lazy";
  198. element.removeAttribute(LAZY_LOAD_ATTRIBUTE);
  199. });
  200. if (!keepZoomLevel) {
  201. if (window._singleFile_getBoundingClientRect) {
  202. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  203. delete window._singleFile_getBoundingClientRect;
  204. }
  205. }
  206. if (window._singleFileImage) {
  207. delete window.Image;
  208. window.Image = window._singleFileImage;
  209. delete window._singleFileImage;
  210. }
  211. if (!keepZoomLevel) {
  212. dispatchResizeEvent();
  213. }
  214. }
  215. function resetScreenSize() {
  216. const scrollingElement = document.scrollingElement || document.documentElement;
  217. if (window._singleFile_innerHeight != null) {
  218. window.innerHeight = window._singleFile_innerHeight;
  219. delete window._singleFile_innerHeight;
  220. }
  221. if (window._singleFile_innerWidth != null) {
  222. window.innerWidth = window._singleFile_innerWidth;
  223. delete window._singleFile_innerWidth;
  224. }
  225. delete scrollingElement.clientHeight;
  226. delete scrollingElement.clientWidth;
  227. delete screen.height;
  228. delete screen.width;
  229. }
  230. addEventListener(BLOCK_COOKIES_START_EVENT, () => {
  231. try {
  232. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  233. } catch (error) {
  234. // ignored
  235. }
  236. });
  237. addEventListener(BLOCK_COOKIES_END_EVENT, () => {
  238. delete document.cookie;
  239. });
  240. addEventListener(BLOCK_STORAGE_START_EVENT, () => {
  241. if (!window._singleFile_localStorage) {
  242. window._singleFile_localStorage = window.localStorage;
  243. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  244. }
  245. if (!window._singleFile_indexedDB) {
  246. window._singleFile_indexedDB = window.indexedDB;
  247. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  248. }
  249. });
  250. addEventListener(BLOCK_STORAGE_END_EVENT, () => {
  251. if (window._singleFile_localStorage) {
  252. delete window.localStorage;
  253. window.localStorage = window._singleFile_localStorage;
  254. delete window._singleFile_localStorage;
  255. }
  256. if (!window._singleFile_indexedDB) {
  257. delete window.indexedDB;
  258. window.indexedDB = window._singleFile_indexedDB;
  259. delete window._singleFile_indexedDB;
  260. }
  261. });
  262. if (window.FontFace) {
  263. const FontFace = window.FontFace;
  264. let warningFontFaceDisplayed;
  265. window.FontFace = function () {
  266. if (!warningFontFaceDisplayed) {
  267. warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  268. warningFontFaceDisplayed = true;
  269. }
  270. const detail = {};
  271. detail["font-family"] = arguments[0];
  272. detail.src = arguments[1];
  273. const descriptors = arguments[2];
  274. if (descriptors) {
  275. Object.keys(descriptors).forEach(descriptor => {
  276. if (FONT_STYLE_PROPERTIES[descriptor]) {
  277. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  278. }
  279. });
  280. }
  281. if (detail.src instanceof ArrayBuffer) {
  282. const reader = new FileReader();
  283. reader.readAsDataURL(new Blob([detail.src]));
  284. reader.addEventListener("load", () => {
  285. detail.src = "url(" + reader.result + ")";
  286. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  287. });
  288. } else {
  289. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  290. }
  291. return new FontFace(...arguments);
  292. };
  293. window.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  294. }
  295. if (window.IntersectionObserver) {
  296. const IntersectionObserver = window.IntersectionObserver;
  297. let warningIntersectionObserverDisplayed;
  298. window.IntersectionObserver = function () {
  299. if (!warningIntersectionObserverDisplayed) {
  300. warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  301. warningIntersectionObserverDisplayed = true;
  302. }
  303. const intersectionObserver = new IntersectionObserver(...arguments);
  304. const observeIntersection = IntersectionObserver.prototype.observe || intersectionObserver.observe;
  305. const unobserveIntersection = IntersectionObserver.prototype.unobserve || intersectionObserver.unobserve;
  306. const callback = arguments[0];
  307. const options = arguments[1];
  308. if (observeIntersection) {
  309. intersectionObserver.observe = function (targetElement) {
  310. let targetElements = observedElements.get(intersectionObserver);
  311. if (!targetElements) {
  312. targetElements = [];
  313. observedElements.set(intersectionObserver, targetElements);
  314. }
  315. targetElements.push(targetElement);
  316. return observeIntersection.call(intersectionObserver, targetElement);
  317. };
  318. }
  319. if (unobserveIntersection) {
  320. intersectionObserver.unobserve = function (targetElement) {
  321. let targetElements = observedElements.get(intersectionObserver);
  322. if (targetElements) {
  323. targetElements = targetElements.filter(element => element != targetElement);
  324. if (targetElements.length) {
  325. observedElements.set(intersectionObserver, targetElements);
  326. } else {
  327. observedElements.delete(intersectionObserver);
  328. observers.delete(intersectionObserver);
  329. }
  330. }
  331. return unobserveIntersection.call(intersectionObserver, targetElement);
  332. };
  333. }
  334. observers.set(intersectionObserver, { callback, options });
  335. return intersectionObserver;
  336. };
  337. window.IntersectionObserver.prototype = IntersectionObserver.prototype;
  338. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  339. }
  340. function dispatchResizeEvent() {
  341. try {
  342. dispatchEvent(new UIEvent("resize"));
  343. document.dispatchEvent(new Event("scroll", { bubbles: true }));
  344. } catch (error) {
  345. // ignored
  346. }
  347. }
  348. })();