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, globalThis */
  24. (globalThis => {
  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) => globalThis.addEventListener(type, listener, options);
  49. const dispatchEvent = event => globalThis.dispatchEvent(event);
  50. const CustomEvent = globalThis.CustomEvent;
  51. const document = globalThis.document;
  52. const screen = globalThis.screen;
  53. const Element = globalThis.Element;
  54. const UIEvent = globalThis.UIEvent;
  55. const FileReader = globalThis.FileReader;
  56. const Blob = globalThis.Blob;
  57. const console = globalThis.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. globalThis._singleFile_innerHeight = globalThis.innerHeight;
  78. globalThis._singleFile_innerWidth = globalThis.innerWidth;
  79. globalThis.__defineGetter__("innerHeight", () => scrollHeight);
  80. globalThis.__defineGetter__("innerWidth", () => scrollWidth);
  81. if (!keepZoomLevel) {
  82. if (!globalThis._singleFile_getBoundingClientRect) {
  83. globalThis._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  84. Element.prototype.getBoundingClientRect = function () {
  85. const boundingRect = globalThis._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 (!globalThis._singleFileImage) {
  97. const Image = globalThis.Image;
  98. globalThis._singleFileImage = globalThis.Image;
  99. globalThis.__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 + globalThis.scrollY) / scrollHeight;
  134. zoomFactorY = (clientWidth + globalThis.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 getBoundingClientRectDefined = observer.options && observer.options.root && observer.options.root.getBoundingClientRect;
  163. const rootBoundingRect = getBoundingClientRectDefined && 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 = getBoundingClientRectDefined ? rootBoundingRect : docBoundingRect;
  171. const time = 0;
  172. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  173. }), intersectionObserver);
  174. }
  175. });
  176. }
  177. }
  178. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => loadDeferredImagesEnd());
  179. addEventListener(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT, () => loadDeferredImagesEnd(true));
  180. addEventListener(LOAD_DEFERRED_IMAGES_RESET_EVENT, resetScreenSize);
  181. addEventListener(LOAD_DEFERRED_IMAGES_RESET_ZOOM_LEVEL_EVENT, () => {
  182. const transform = document.documentElement.style.getPropertyValue("-sf-transform");
  183. const transformPriority = document.documentElement.style.getPropertyPriority("-sf-transform");
  184. const transformOrigin = document.documentElement.style.getPropertyValue("-sf-transform-origin");
  185. const transformOriginPriority = document.documentElement.style.getPropertyPriority("-sf-transform-origin");
  186. const minHeight = document.documentElement.style.getPropertyValue("-sf-min-height");
  187. const minHeightPriority = document.documentElement.style.getPropertyPriority("-sf-min-height");
  188. document.documentElement.style.setProperty("transform", transform, transformPriority);
  189. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  190. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  191. document.documentElement.style.removeProperty("-sf-transform");
  192. document.documentElement.style.removeProperty("-sf-transform-origin");
  193. document.documentElement.style.removeProperty("-sf-min-height");
  194. resetScreenSize();
  195. });
  196. function loadDeferredImagesEnd(keepZoomLevel) {
  197. document.querySelectorAll("[" + LAZY_LOAD_ATTRIBUTE + "]").forEach(element => {
  198. element.loading = "lazy";
  199. element.removeAttribute(LAZY_LOAD_ATTRIBUTE);
  200. });
  201. if (!keepZoomLevel) {
  202. if (globalThis._singleFile_getBoundingClientRect) {
  203. Element.prototype.getBoundingClientRect = globalThis._singleFile_getBoundingClientRect;
  204. delete globalThis._singleFile_getBoundingClientRect;
  205. }
  206. }
  207. if (globalThis._singleFileImage) {
  208. delete globalThis.Image;
  209. globalThis.Image = globalThis._singleFileImage;
  210. delete globalThis._singleFileImage;
  211. }
  212. if (!keepZoomLevel) {
  213. dispatchResizeEvent();
  214. }
  215. }
  216. function resetScreenSize() {
  217. const scrollingElement = document.scrollingElement || document.documentElement;
  218. if (globalThis._singleFile_innerHeight != null) {
  219. globalThis.innerHeight = globalThis._singleFile_innerHeight;
  220. delete globalThis._singleFile_innerHeight;
  221. }
  222. if (globalThis._singleFile_innerWidth != null) {
  223. globalThis.innerWidth = globalThis._singleFile_innerWidth;
  224. delete globalThis._singleFile_innerWidth;
  225. }
  226. delete scrollingElement.clientHeight;
  227. delete scrollingElement.clientWidth;
  228. delete screen.height;
  229. delete screen.width;
  230. }
  231. addEventListener(BLOCK_COOKIES_START_EVENT, () => {
  232. try {
  233. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  234. } catch (error) {
  235. // ignored
  236. }
  237. });
  238. addEventListener(BLOCK_COOKIES_END_EVENT, () => {
  239. delete document.cookie;
  240. });
  241. addEventListener(BLOCK_STORAGE_START_EVENT, () => {
  242. if (!globalThis._singleFile_localStorage) {
  243. globalThis._singleFile_localStorage = globalThis.localStorage;
  244. globalThis.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  245. }
  246. if (!globalThis._singleFile_indexedDB) {
  247. globalThis._singleFile_indexedDB = globalThis.indexedDB;
  248. globalThis.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  249. }
  250. });
  251. addEventListener(BLOCK_STORAGE_END_EVENT, () => {
  252. if (globalThis._singleFile_localStorage) {
  253. delete globalThis.localStorage;
  254. globalThis.localStorage = globalThis._singleFile_localStorage;
  255. delete globalThis._singleFile_localStorage;
  256. }
  257. if (!globalThis._singleFile_indexedDB) {
  258. delete globalThis.indexedDB;
  259. globalThis.indexedDB = globalThis._singleFile_indexedDB;
  260. delete globalThis._singleFile_indexedDB;
  261. }
  262. });
  263. if (globalThis.FontFace) {
  264. const FontFace = globalThis.FontFace;
  265. let warningFontFaceDisplayed;
  266. globalThis.FontFace = function () {
  267. if (!warningFontFaceDisplayed) {
  268. warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  269. warningFontFaceDisplayed = true;
  270. }
  271. const detail = {};
  272. detail["font-family"] = arguments[0];
  273. detail.src = arguments[1];
  274. const descriptors = arguments[2];
  275. if (descriptors) {
  276. Object.keys(descriptors).forEach(descriptor => {
  277. if (FONT_STYLE_PROPERTIES[descriptor]) {
  278. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  279. }
  280. });
  281. }
  282. if (detail.src instanceof ArrayBuffer) {
  283. const reader = new FileReader();
  284. reader.readAsDataURL(new Blob([detail.src]));
  285. reader.addEventListener("load", () => {
  286. detail.src = "url(" + reader.result + ")";
  287. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  288. });
  289. } else {
  290. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  291. }
  292. return new FontFace(...arguments);
  293. };
  294. globalThis.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  295. }
  296. if (globalThis.IntersectionObserver) {
  297. const IntersectionObserver = globalThis.IntersectionObserver;
  298. let warningIntersectionObserverDisplayed;
  299. globalThis.IntersectionObserver = function () {
  300. if (!warningIntersectionObserverDisplayed) {
  301. warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  302. warningIntersectionObserverDisplayed = true;
  303. }
  304. const intersectionObserver = new IntersectionObserver(...arguments);
  305. const observeIntersection = IntersectionObserver.prototype.observe || intersectionObserver.observe;
  306. const unobserveIntersection = IntersectionObserver.prototype.unobserve || intersectionObserver.unobserve;
  307. const callback = arguments[0];
  308. const options = arguments[1];
  309. if (observeIntersection) {
  310. intersectionObserver.observe = function (targetElement) {
  311. let targetElements = observedElements.get(intersectionObserver);
  312. if (!targetElements) {
  313. targetElements = [];
  314. observedElements.set(intersectionObserver, targetElements);
  315. }
  316. targetElements.push(targetElement);
  317. return observeIntersection.call(intersectionObserver, targetElement);
  318. };
  319. }
  320. if (unobserveIntersection) {
  321. intersectionObserver.unobserve = function (targetElement) {
  322. let targetElements = observedElements.get(intersectionObserver);
  323. if (targetElements) {
  324. targetElements = targetElements.filter(element => element != targetElement);
  325. if (targetElements.length) {
  326. observedElements.set(intersectionObserver, targetElements);
  327. } else {
  328. observedElements.delete(intersectionObserver);
  329. observers.delete(intersectionObserver);
  330. }
  331. }
  332. return unobserveIntersection.call(intersectionObserver, targetElement);
  333. };
  334. }
  335. observers.set(intersectionObserver, { callback, options });
  336. return intersectionObserver;
  337. };
  338. globalThis.IntersectionObserver.prototype = IntersectionObserver.prototype;
  339. globalThis.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  340. }
  341. function dispatchResizeEvent() {
  342. try {
  343. dispatchEvent(new UIEvent("resize"));
  344. } catch (error) {
  345. // ignored
  346. }
  347. }
  348. })(typeof globalThis == "object" ? globalThis : window);