content-hooks-frames-web.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 DELETE_FONT_EVENT = "single-file-delete-font";
  40. const CLEAR_FONTS_EVENT = "single-file-clear-fonts";
  41. const FONT_STYLE_PROPERTIES = {
  42. family: "font-family",
  43. style: "font-style",
  44. weight: "font-weight",
  45. stretch: "font-stretch",
  46. unicodeRange: "unicode-range",
  47. variant: "font-variant",
  48. featureSettings: "font-feature-settings"
  49. };
  50. const addEventListener = (type, listener, options) => globalThis.addEventListener(type, listener, options);
  51. const dispatchEvent = event => globalThis.dispatchEvent(event);
  52. const CustomEvent = globalThis.CustomEvent;
  53. const document = globalThis.document;
  54. const screen = globalThis.screen;
  55. const Element = globalThis.Element;
  56. const UIEvent = globalThis.UIEvent;
  57. const FileReader = globalThis.FileReader;
  58. const Blob = globalThis.Blob;
  59. const console = globalThis.console;
  60. const warn = (console && console.warn && ((...args) => console.warn(...args))) || (() => { });
  61. const observers = new Map();
  62. const observedElements = new Map();
  63. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => loadDeferredImagesStart());
  64. addEventListener(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_START_EVENT, () => loadDeferredImagesStart(true));
  65. function loadDeferredImagesStart(keepZoomLevel) {
  66. const scrollingElement = document.scrollingElement || document.documentElement;
  67. const clientHeight = scrollingElement.clientHeight;
  68. const clientWidth = scrollingElement.clientWidth;
  69. const scrollHeight = Math.max(scrollingElement.scrollHeight - clientHeight, clientHeight);
  70. const scrollWidth = Math.max(scrollingElement.scrollWidth - clientWidth, clientWidth);
  71. document.querySelectorAll("[loading=lazy]").forEach(element => {
  72. element.loading = "eager";
  73. element.setAttribute(LAZY_LOAD_ATTRIBUTE, "");
  74. });
  75. scrollingElement.__defineGetter__("clientHeight", () => scrollHeight);
  76. scrollingElement.__defineGetter__("clientWidth", () => scrollWidth);
  77. screen.__defineGetter__("height", () => scrollHeight);
  78. screen.__defineGetter__("width", () => scrollWidth);
  79. globalThis._singleFile_innerHeight = globalThis.innerHeight;
  80. globalThis._singleFile_innerWidth = globalThis.innerWidth;
  81. globalThis.__defineGetter__("innerHeight", () => scrollHeight);
  82. globalThis.__defineGetter__("innerWidth", () => scrollWidth);
  83. if (!keepZoomLevel) {
  84. if (!globalThis._singleFile_getBoundingClientRect) {
  85. globalThis._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  86. Element.prototype.getBoundingClientRect = function () {
  87. const boundingRect = globalThis._singleFile_getBoundingClientRect.call(this);
  88. if (this == scrollingElement) {
  89. boundingRect.__defineGetter__("height", () => scrollHeight);
  90. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  91. boundingRect.__defineGetter__("width", () => scrollWidth);
  92. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  93. }
  94. return boundingRect;
  95. };
  96. }
  97. }
  98. if (!globalThis._singleFileImage) {
  99. const Image = globalThis.Image;
  100. globalThis._singleFileImage = globalThis.Image;
  101. globalThis.__defineGetter__("Image", function () {
  102. return function () {
  103. const image = new Image(...arguments);
  104. const result = new Image(...arguments);
  105. result.__defineSetter__("src", function (value) {
  106. image.src = value;
  107. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  108. });
  109. result.__defineGetter__("src", function () {
  110. return image.src;
  111. });
  112. result.__defineSetter__("srcset", function (value) {
  113. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT));
  114. image.srcset = value;
  115. });
  116. result.__defineGetter__("srcset", function () {
  117. return image.srcset;
  118. });
  119. image.onload = image.onloadend = image.onerror = event => {
  120. dispatchEvent(new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  121. result.dispatchEvent(new UIEvent(event.type, event));
  122. };
  123. if (image.decode) {
  124. result.decode = () => image.decode();
  125. }
  126. return result;
  127. };
  128. });
  129. }
  130. let zoomFactorX, zoomFactorY;
  131. if (keepZoomLevel) {
  132. zoomFactorX = clientHeight / scrollHeight;
  133. zoomFactorY = clientWidth / scrollWidth;
  134. } else {
  135. zoomFactorX = (clientHeight + globalThis.scrollY) / scrollHeight;
  136. zoomFactorY = (clientWidth + globalThis.scrollX) / scrollWidth;
  137. }
  138. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  139. if (zoomFactor < 1) {
  140. const transform = document.documentElement.style.getPropertyValue("transform");
  141. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  142. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  143. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  144. const minHeight = document.documentElement.style.getPropertyValue("min-height");
  145. const minHeightPriority = document.documentElement.style.getPropertyPriority("min-height");
  146. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  147. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  148. document.documentElement.style.setProperty("min-height", (100 / zoomFactor) + "vh", "important");
  149. dispatchResizeEvent();
  150. if (keepZoomLevel) {
  151. document.documentElement.style.setProperty("-sf-transform", transform, transformPriority);
  152. document.documentElement.style.setProperty("-sf-transform-origin", transformOrigin, transformOriginPriority);
  153. document.documentElement.style.setProperty("-sf-min-height", minHeight, minHeightPriority);
  154. } else {
  155. document.documentElement.style.setProperty("transform", transform, transformPriority);
  156. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  157. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  158. }
  159. }
  160. if (!keepZoomLevel) {
  161. dispatchResizeEvent();
  162. const docBoundingRect = scrollingElement.getBoundingClientRect();
  163. if (window == window.top) {
  164. [...observers].forEach(([intersectionObserver, observer]) => {
  165. const getBoundingClientRectDefined = observer.options && observer.options.root && observer.options.root.getBoundingClientRect;
  166. const rootBoundingRect = getBoundingClientRectDefined && observer.options.root.getBoundingClientRect();
  167. const targetElements = observedElements.get(intersectionObserver);
  168. if (targetElements) {
  169. const params = targetElements.map(target => {
  170. const boundingClientRect = target.getBoundingClientRect();
  171. const isIntersecting = true;
  172. const intersectionRatio = 1;
  173. const rootBounds = getBoundingClientRectDefined ? rootBoundingRect : docBoundingRect;
  174. const time = 0;
  175. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  176. });
  177. observer.callback(params, intersectionObserver);
  178. }
  179. });
  180. }
  181. }
  182. }
  183. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => loadDeferredImagesEnd());
  184. addEventListener(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT, () => loadDeferredImagesEnd(true));
  185. addEventListener(LOAD_DEFERRED_IMAGES_RESET_EVENT, resetScreenSize);
  186. addEventListener(LOAD_DEFERRED_IMAGES_RESET_ZOOM_LEVEL_EVENT, () => {
  187. const transform = document.documentElement.style.getPropertyValue("-sf-transform");
  188. const transformPriority = document.documentElement.style.getPropertyPriority("-sf-transform");
  189. const transformOrigin = document.documentElement.style.getPropertyValue("-sf-transform-origin");
  190. const transformOriginPriority = document.documentElement.style.getPropertyPriority("-sf-transform-origin");
  191. const minHeight = document.documentElement.style.getPropertyValue("-sf-min-height");
  192. const minHeightPriority = document.documentElement.style.getPropertyPriority("-sf-min-height");
  193. document.documentElement.style.setProperty("transform", transform, transformPriority);
  194. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  195. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  196. document.documentElement.style.removeProperty("-sf-transform");
  197. document.documentElement.style.removeProperty("-sf-transform-origin");
  198. document.documentElement.style.removeProperty("-sf-min-height");
  199. resetScreenSize();
  200. });
  201. function loadDeferredImagesEnd(keepZoomLevel) {
  202. document.querySelectorAll("[" + LAZY_LOAD_ATTRIBUTE + "]").forEach(element => {
  203. element.loading = "lazy";
  204. element.removeAttribute(LAZY_LOAD_ATTRIBUTE);
  205. });
  206. if (!keepZoomLevel) {
  207. if (globalThis._singleFile_getBoundingClientRect) {
  208. Element.prototype.getBoundingClientRect = globalThis._singleFile_getBoundingClientRect;
  209. delete globalThis._singleFile_getBoundingClientRect;
  210. }
  211. }
  212. if (globalThis._singleFileImage) {
  213. delete globalThis.Image;
  214. globalThis.Image = globalThis._singleFileImage;
  215. delete globalThis._singleFileImage;
  216. }
  217. if (!keepZoomLevel) {
  218. dispatchResizeEvent();
  219. }
  220. }
  221. function resetScreenSize() {
  222. const scrollingElement = document.scrollingElement || document.documentElement;
  223. if (globalThis._singleFile_innerHeight != null) {
  224. delete globalThis.innerHeight;
  225. globalThis.innerHeight = globalThis._singleFile_innerHeight;
  226. delete globalThis._singleFile_innerHeight;
  227. }
  228. if (globalThis._singleFile_innerWidth != null) {
  229. delete globalThis.innerWidth;
  230. globalThis.innerWidth = globalThis._singleFile_innerWidth;
  231. delete globalThis._singleFile_innerWidth;
  232. }
  233. delete scrollingElement.clientHeight;
  234. delete scrollingElement.clientWidth;
  235. delete screen.height;
  236. delete screen.width;
  237. }
  238. addEventListener(BLOCK_COOKIES_START_EVENT, () => {
  239. try {
  240. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  241. } catch (error) {
  242. // ignored
  243. }
  244. });
  245. addEventListener(BLOCK_COOKIES_END_EVENT, () => {
  246. delete document.cookie;
  247. });
  248. addEventListener(BLOCK_STORAGE_START_EVENT, () => {
  249. if (!globalThis._singleFile_localStorage) {
  250. globalThis._singleFile_localStorage = globalThis.localStorage;
  251. globalThis.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  252. }
  253. if (!globalThis._singleFile_indexedDB) {
  254. globalThis._singleFile_indexedDB = globalThis.indexedDB;
  255. globalThis.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  256. }
  257. });
  258. addEventListener(BLOCK_STORAGE_END_EVENT, () => {
  259. if (globalThis._singleFile_localStorage) {
  260. delete globalThis.localStorage;
  261. globalThis.localStorage = globalThis._singleFile_localStorage;
  262. delete globalThis._singleFile_localStorage;
  263. }
  264. if (!globalThis._singleFile_indexedDB) {
  265. delete globalThis.indexedDB;
  266. globalThis.indexedDB = globalThis._singleFile_indexedDB;
  267. delete globalThis._singleFile_indexedDB;
  268. }
  269. });
  270. if (globalThis.FontFace) {
  271. const FontFace = globalThis.FontFace;
  272. let warningFontFaceDisplayed;
  273. globalThis.FontFace = function () {
  274. if (!warningFontFaceDisplayed) {
  275. warn("SingleFile is hooking the FontFace constructor, document.fonts.delete and document.fonts.clear to handle dynamically loaded fonts.");
  276. warningFontFaceDisplayed = true;
  277. }
  278. getDetailObject(...arguments).then(detail => dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail })));
  279. return new FontFace(...arguments);
  280. };
  281. globalThis.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  282. const deleteFont = document.fonts.delete;
  283. document.fonts.delete = function (fontFace) {
  284. getDetailObject(fontFace.family).then(detail => dispatchEvent(new CustomEvent(DELETE_FONT_EVENT, { detail })));
  285. return deleteFont.call(document.fonts, fontFace);
  286. };
  287. document.fonts.delete.toString = function () { return "function delete() { [native code] }"; };
  288. const clearFonts = document.fonts.clear;
  289. document.fonts.clear = function () {
  290. dispatchEvent(new CustomEvent(CLEAR_FONTS_EVENT));
  291. return clearFonts.call(document.fonts);
  292. };
  293. document.fonts.clear.toString = function () { return "function clear() { [native code] }"; };
  294. }
  295. if (globalThis.IntersectionObserver) {
  296. const IntersectionObserver = globalThis.IntersectionObserver;
  297. let warningIntersectionObserverDisplayed;
  298. globalThis.IntersectionObserver = function () {
  299. if (!warningIntersectionObserverDisplayed) {
  300. warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images.");
  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. globalThis.IntersectionObserver.prototype = IntersectionObserver.prototype;
  338. globalThis.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  339. }
  340. async function getDetailObject(fontFamily, src, descriptors) {
  341. const detail = {};
  342. detail["font-family"] = fontFamily;
  343. detail.src = src;
  344. if (descriptors) {
  345. Object.keys(descriptors).forEach(descriptor => {
  346. if (FONT_STYLE_PROPERTIES[descriptor]) {
  347. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  348. }
  349. });
  350. }
  351. return new Promise(resolve => {
  352. if (detail.src instanceof ArrayBuffer) {
  353. const reader = new FileReader();
  354. reader.readAsDataURL(new Blob([detail.src]));
  355. reader.addEventListener("load", () => {
  356. detail.src = "url(" + reader.result + ")";
  357. resolve(detail);
  358. });
  359. } else {
  360. resolve(detail);
  361. }
  362. });
  363. }
  364. function dispatchResizeEvent() {
  365. try {
  366. dispatchEvent(new UIEvent("resize"));
  367. } catch (error) {
  368. // ignored
  369. }
  370. }
  371. })(typeof globalThis == "object" ? globalThis : window);