content-hooks-frames-web.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. globalThis.innerHeight = globalThis._singleFile_innerHeight;
  225. delete globalThis._singleFile_innerHeight;
  226. }
  227. if (globalThis._singleFile_innerWidth != null) {
  228. globalThis.innerWidth = globalThis._singleFile_innerWidth;
  229. delete globalThis._singleFile_innerWidth;
  230. }
  231. delete scrollingElement.clientHeight;
  232. delete scrollingElement.clientWidth;
  233. delete screen.height;
  234. delete screen.width;
  235. }
  236. addEventListener(BLOCK_COOKIES_START_EVENT, () => {
  237. try {
  238. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  239. } catch (error) {
  240. // ignored
  241. }
  242. });
  243. addEventListener(BLOCK_COOKIES_END_EVENT, () => {
  244. delete document.cookie;
  245. });
  246. addEventListener(BLOCK_STORAGE_START_EVENT, () => {
  247. if (!globalThis._singleFile_localStorage) {
  248. globalThis._singleFile_localStorage = globalThis.localStorage;
  249. globalThis.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  250. }
  251. if (!globalThis._singleFile_indexedDB) {
  252. globalThis._singleFile_indexedDB = globalThis.indexedDB;
  253. globalThis.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  254. }
  255. });
  256. addEventListener(BLOCK_STORAGE_END_EVENT, () => {
  257. if (globalThis._singleFile_localStorage) {
  258. delete globalThis.localStorage;
  259. globalThis.localStorage = globalThis._singleFile_localStorage;
  260. delete globalThis._singleFile_localStorage;
  261. }
  262. if (!globalThis._singleFile_indexedDB) {
  263. delete globalThis.indexedDB;
  264. globalThis.indexedDB = globalThis._singleFile_indexedDB;
  265. delete globalThis._singleFile_indexedDB;
  266. }
  267. });
  268. if (globalThis.FontFace) {
  269. const FontFace = globalThis.FontFace;
  270. let warningFontFaceDisplayed;
  271. globalThis.FontFace = function () {
  272. if (!warningFontFaceDisplayed) {
  273. warn("SingleFile is hooking the FontFace constructor, document.fonts.delete and document.fonts.clear to handle dynamically loaded fonts.");
  274. warningFontFaceDisplayed = true;
  275. }
  276. getDetailObject(...arguments).then(detail => dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail })));
  277. return new FontFace(...arguments);
  278. };
  279. globalThis.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  280. const deleteFont = document.fonts.delete;
  281. document.fonts.delete = function (fontFace) {
  282. getDetailObject(fontFace.family).then(detail => dispatchEvent(new CustomEvent(DELETE_FONT_EVENT, { detail })));
  283. return deleteFont.call(document.fonts, fontFace);
  284. };
  285. document.fonts.delete.toString = function () { return "function delete() { [native code] }"; };
  286. const clearFonts = document.fonts.clear;
  287. document.fonts.clear = function () {
  288. dispatchEvent(new CustomEvent(CLEAR_FONTS_EVENT));
  289. return clearFonts.call(document.fonts);
  290. };
  291. document.fonts.clear.toString = function () { return "function clear() { [native code] }"; };
  292. }
  293. if (globalThis.IntersectionObserver) {
  294. const IntersectionObserver = globalThis.IntersectionObserver;
  295. let warningIntersectionObserverDisplayed;
  296. globalThis.IntersectionObserver = function () {
  297. if (!warningIntersectionObserverDisplayed) {
  298. warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images.");
  299. warningIntersectionObserverDisplayed = true;
  300. }
  301. const intersectionObserver = new IntersectionObserver(...arguments);
  302. const observeIntersection = IntersectionObserver.prototype.observe || intersectionObserver.observe;
  303. const unobserveIntersection = IntersectionObserver.prototype.unobserve || intersectionObserver.unobserve;
  304. const callback = arguments[0];
  305. const options = arguments[1];
  306. if (observeIntersection) {
  307. intersectionObserver.observe = function (targetElement) {
  308. let targetElements = observedElements.get(intersectionObserver);
  309. if (!targetElements) {
  310. targetElements = [];
  311. observedElements.set(intersectionObserver, targetElements);
  312. }
  313. targetElements.push(targetElement);
  314. return observeIntersection.call(intersectionObserver, targetElement);
  315. };
  316. }
  317. if (unobserveIntersection) {
  318. intersectionObserver.unobserve = function (targetElement) {
  319. let targetElements = observedElements.get(intersectionObserver);
  320. if (targetElements) {
  321. targetElements = targetElements.filter(element => element != targetElement);
  322. if (targetElements.length) {
  323. observedElements.set(intersectionObserver, targetElements);
  324. } else {
  325. observedElements.delete(intersectionObserver);
  326. observers.delete(intersectionObserver);
  327. }
  328. }
  329. return unobserveIntersection.call(intersectionObserver, targetElement);
  330. };
  331. }
  332. observers.set(intersectionObserver, { callback, options });
  333. return intersectionObserver;
  334. };
  335. globalThis.IntersectionObserver.prototype = IntersectionObserver.prototype;
  336. globalThis.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  337. }
  338. async function getDetailObject(fontFamily, src, descriptors) {
  339. const detail = {};
  340. detail["font-family"] = fontFamily;
  341. detail.src = src;
  342. if (descriptors) {
  343. Object.keys(descriptors).forEach(descriptor => {
  344. if (FONT_STYLE_PROPERTIES[descriptor]) {
  345. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  346. }
  347. });
  348. }
  349. return new Promise(resolve => {
  350. if (detail.src instanceof ArrayBuffer) {
  351. const reader = new FileReader();
  352. reader.readAsDataURL(new Blob([detail.src]));
  353. reader.addEventListener("load", () => {
  354. detail.src = "url(" + reader.result + ")";
  355. resolve(detail);
  356. });
  357. } else {
  358. resolve(detail);
  359. }
  360. });
  361. }
  362. function dispatchResizeEvent() {
  363. try {
  364. dispatchEvent(new UIEvent("resize"));
  365. } catch (error) {
  366. // ignored
  367. }
  368. }
  369. })(typeof globalThis == "object" ? globalThis : window);