content-hooks-frames-web.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*
  2. * Copyright 2010-2019 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, addEventListener, dispatchEvent, CustomEvent, document, screen, Element, UIEvent, FileReader, Blob */
  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_IMAGE_EVENT = "single-file-load-image";
  28. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  29. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  30. const FONT_STYLE_PROPERTIES = {
  31. family: "font-family",
  32. style: "font-style",
  33. weight: "font-weight",
  34. stretch: "font-stretch",
  35. unicodeRange: "unicode-range",
  36. variant: "font-variant",
  37. featureSettings: "font-feature-settings"
  38. };
  39. const requestAnimationFrame = window.requestAnimationFrame;
  40. const cancelAnimationFrame = window.cancelAnimationFrame;
  41. const observers = new Map();
  42. const observedElements = new Map();
  43. let loadDeferredImages;
  44. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  45. const clientHeight = document.documentElement.clientHeight;
  46. const clientWidth = document.documentElement.clientWidth;
  47. const scrollHeight = Math.max(document.documentElement.scrollHeight - (clientHeight * .5), clientHeight);
  48. const scrollWidth = Math.max(document.documentElement.scrollWidth - (clientWidth * .5), clientWidth);
  49. document.documentElement.__defineGetter__("clientHeight", () => scrollHeight);
  50. document.documentElement.__defineGetter__("clientWidth", () => scrollWidth);
  51. screen.__defineGetter__("height", () => scrollHeight);
  52. screen.__defineGetter__("width", () => scrollWidth);
  53. try {
  54. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  55. } catch (error) {
  56. // ignored
  57. }
  58. if (!window._singleFile_getBoundingClientRect) {
  59. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  60. Element.prototype.getBoundingClientRect = function () {
  61. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  62. if (this == document.documentElement) {
  63. boundingRect.__defineGetter__("height", () => scrollHeight);
  64. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  65. boundingRect.__defineGetter__("width", () => scrollWidth);
  66. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  67. }
  68. return boundingRect;
  69. };
  70. window._singleFile_innerHeight = window.innerHeight;
  71. window._singleFile_innerWidth = window.innerWidth;
  72. window.__defineGetter__("innerHeight", () => scrollHeight);
  73. window.__defineGetter__("innerWidth", () => scrollWidth);
  74. }
  75. if (!window._singleFile_localStorage) {
  76. window._singleFile_localStorage = window.localStorage;
  77. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  78. }
  79. if (!window._singleFile_indexedDB) {
  80. window._singleFile_indexedDB = window.indexedDB;
  81. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  82. }
  83. if (!window._singleFileImage) {
  84. const Image = window.Image;
  85. window._singleFileImage = window.Image;
  86. window.__defineGetter__("Image", function () {
  87. return function () {
  88. const image = new Image(...arguments);
  89. const result = new Image(...arguments);
  90. result.__defineSetter__("src", function (value) {
  91. image.src = value;
  92. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  93. });
  94. result.__defineGetter__("src", function () {
  95. return image.src;
  96. });
  97. result.__defineSetter__("srcset", function (value) {
  98. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT));
  99. image.srcset = value;
  100. });
  101. result.__defineGetter__("srcset", function () {
  102. return image.srcset;
  103. });
  104. image.onload = image.onloadend = image.onerror = event => {
  105. dispatchEvent(new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  106. result.dispatchEvent(new UIEvent(event.type, event));
  107. };
  108. return result;
  109. };
  110. });
  111. }
  112. const zoomFactorX = (clientHeight + window.scrollY) / scrollHeight;
  113. const zoomFactorY = (clientWidth + window.scrollX) / scrollWidth;
  114. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  115. if (zoomFactor < 1) {
  116. const transform = document.documentElement.style.getPropertyValue("transform");
  117. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  118. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  119. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  120. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  121. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  122. dispatchEvent(new UIEvent("resize"));
  123. dispatchEvent(new UIEvent("scroll"));
  124. document.documentElement.style.setProperty("transform", transform, transformPriority);
  125. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  126. }
  127. dispatchEvent(new UIEvent("resize"));
  128. dispatchEvent(new UIEvent("scroll"));
  129. });
  130. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  131. delete document.documentElement.clientHeight;
  132. delete document.documentElement.clientWidth;
  133. delete screen.height;
  134. delete screen.width;
  135. delete document.cookie;
  136. if (window._singleFile_getBoundingClientRect) {
  137. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  138. window.innerHeight = window._singleFile_innerHeight;
  139. window.innerWidth = window._singleFile_innerWidth;
  140. delete window._singleFile_getBoundingClientRect;
  141. delete window._singleFile_innerHeight;
  142. delete window._singleFile_innerWidth;
  143. }
  144. if (window._singleFile_localStorage) {
  145. delete window.localStorage;
  146. window.localStorage = window._singleFile_localStorage;
  147. delete window._singleFile_localStorage;
  148. }
  149. if (!window._singleFile_indexedDB) {
  150. delete window.indexedDB;
  151. window.indexedDB = window._singleFile_indexedDB;
  152. delete window._singleFile_indexedDB;
  153. }
  154. if (window._singleFileImage) {
  155. delete window.Image;
  156. window.Image = window._singleFileImage;
  157. delete window._singleFileImage;
  158. }
  159. dispatchEvent(new UIEvent("resize"));
  160. dispatchEvent(new UIEvent("scroll"));
  161. });
  162. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  163. loadDeferredImages = true;
  164. const docBoundingRect = document.documentElement.getBoundingClientRect();
  165. Array.from(observers).forEach(([intersectionObserver, observer]) => {
  166. const rootBoundingRect = observer.options.root && observer.options.root.getBoundingClientRect();
  167. observer.callback(observedElements.get(intersectionObserver).map(target => {
  168. const boundingClientRect = target.getBoundingClientRect();
  169. const isIntersecting = true;
  170. const intersectionRatio = 1;
  171. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  172. const time = 0;
  173. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  174. }), intersectionObserver);
  175. });
  176. if (pendingRequestAnimationFrameCalls.size) {
  177. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  178. cancelAnimationFrame(id);
  179. callback();
  180. });
  181. }
  182. });
  183. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  184. loadDeferredImages = false;
  185. });
  186. let warningRequestAnimationFrameDisplayed;
  187. const pendingRequestAnimationFrameCalls = new Map();
  188. let lastTimestamp = 0;
  189. let errorDetected;
  190. window.requestAnimationFrame = function (callback) {
  191. if (!warningRequestAnimationFrameDisplayed) {
  192. console.warn("SingleFile is hooking the requestAnimationFrame and cancelAnimationFrame functions to load deferred images."); // eslint-disable-line no-console
  193. warningRequestAnimationFrameDisplayed = true;
  194. }
  195. let requestId;
  196. if (loadDeferredImages && !errorDetected) {
  197. try {
  198. requestId = 0;
  199. callback(lastTimestamp);
  200. } catch (error) {
  201. errorDetected = true;
  202. requestId = requestAnimationFrame(timestamp => {
  203. lastTimestamp = timestamp;
  204. callback(timestamp);
  205. });
  206. }
  207. } else {
  208. if (!loadDeferredImages) {
  209. errorDetected = false;
  210. }
  211. requestId = requestAnimationFrame(timestamp => {
  212. pendingRequestAnimationFrameCalls.delete(requestId);
  213. lastTimestamp = timestamp;
  214. callback(timestamp);
  215. });
  216. pendingRequestAnimationFrameCalls.set(requestId, callback);
  217. }
  218. return requestId;
  219. };
  220. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  221. window.cancelAnimationFrame = function (requestId) {
  222. pendingRequestAnimationFrameCalls.delete(requestId);
  223. return cancelAnimationFrame(requestId);
  224. };
  225. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  226. if (window.FontFace) {
  227. const FontFace = window.FontFace;
  228. let warningFontFaceDisplayed;
  229. window.FontFace = function () {
  230. if (!warningFontFaceDisplayed) {
  231. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  232. warningFontFaceDisplayed = true;
  233. }
  234. const detail = {};
  235. detail["font-family"] = arguments[0];
  236. detail.src = arguments[1];
  237. const descriptors = arguments[2];
  238. if (descriptors) {
  239. Object.keys(descriptors).forEach(descriptor => {
  240. if (FONT_STYLE_PROPERTIES[descriptor]) {
  241. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  242. }
  243. });
  244. }
  245. if (detail.src instanceof ArrayBuffer) {
  246. const reader = new FileReader();
  247. reader.readAsDataURL(new Blob([detail.src]));
  248. reader.addEventListener("load", () => {
  249. detail.src = "url(" + reader.result + ")";
  250. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  251. });
  252. } else {
  253. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  254. }
  255. return new FontFace(...arguments);
  256. };
  257. window.FontFace.toString = function () { return "function FontFace() { [native code]"; };
  258. }
  259. if (window.IntersectionObserver) {
  260. const IntersectionObserver = window.IntersectionObserver;
  261. const observeIntersection = IntersectionObserver.prototype.observe;
  262. const unobserveIntersection = IntersectionObserver.prototype.unobserve;
  263. let warningIntersectionObserverDisplayed;
  264. window.IntersectionObserver = function () {
  265. if (!warningIntersectionObserverDisplayed) {
  266. console.warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  267. warningIntersectionObserverDisplayed = true;
  268. }
  269. const intersectionObserver = new IntersectionObserver(...arguments);
  270. const callback = arguments[0];
  271. const options = arguments[1];
  272. intersectionObserver.observe = function (targetElement) {
  273. let targetElements = observedElements.get(intersectionObserver);
  274. if (!targetElements) {
  275. targetElements = [];
  276. observedElements.set(intersectionObserver, targetElements);
  277. }
  278. targetElements.push(targetElement);
  279. return observeIntersection.call(intersectionObserver, targetElement);
  280. };
  281. intersectionObserver.unobserve = function (targetElement) {
  282. let targetElements = observedElements.get(intersectionObserver);
  283. if (targetElements) {
  284. targetElements = targetElements.filter(element => element <= targetElement);
  285. if (targetElements.length) {
  286. observedElements.set(intersectionObserver, targetElements);
  287. } else {
  288. observedElements.delete(intersectionObserver);
  289. }
  290. }
  291. return unobserveIntersection.call(intersectionObserver, targetElement);
  292. };
  293. observers.set(intersectionObserver, { callback, options });
  294. return intersectionObserver;
  295. };
  296. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code]"; };
  297. }
  298. })();