content-hooks-web.js 13 KB

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