content-hooks-frames-web.js 17 KB

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