intersection-observer.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. /**
  2. * Copyright 2016 Google Inc. All Rights Reserved.
  3. *
  4. * Licensed under the W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE.
  5. *
  6. * https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
  7. *
  8. */
  9. (function() {
  10. 'use strict';
  11. // Exit early if we're not running in a browser.
  12. if (typeof window !== 'object') {
  13. return;
  14. }
  15. // Exit early if all IntersectionObserver and IntersectionObserverEntry
  16. // features are natively supported.
  17. if ('IntersectionObserver' in window &&
  18. 'IntersectionObserverEntry' in window &&
  19. 'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
  20. // Minimal polyfill for Edge 15's lack of `isIntersecting`
  21. // See: https://github.com/w3c/IntersectionObserver/issues/211
  22. if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
  23. Object.defineProperty(window.IntersectionObserverEntry.prototype,
  24. 'isIntersecting', {
  25. get: function () {
  26. return this.intersectionRatio > 0;
  27. }
  28. });
  29. }
  30. return;
  31. }
  32. /**
  33. * Returns the embedding frame element, if any.
  34. * @param {!Document} doc
  35. * @return {!Element}
  36. */
  37. function getFrameElement(doc) {
  38. try {
  39. return doc.defaultView && doc.defaultView.frameElement || null;
  40. } catch (e) {
  41. // Ignore the error.
  42. return null;
  43. }
  44. }
  45. /**
  46. * A local reference to the root document.
  47. */
  48. var document = (function(startDoc) {
  49. var doc = startDoc;
  50. var frame = getFrameElement(doc);
  51. while (frame) {
  52. doc = frame.ownerDocument;
  53. frame = getFrameElement(doc);
  54. }
  55. return doc;
  56. })(window.document);
  57. /**
  58. * An IntersectionObserver registry. This registry exists to hold a strong
  59. * reference to IntersectionObserver instances currently observing a target
  60. * element. Without this registry, instances without another reference may be
  61. * garbage collected.
  62. */
  63. var registry = [];
  64. /**
  65. * The signal updater for cross-origin intersection. When not null, it means
  66. * that the polyfill is configured to work in a cross-origin mode.
  67. * @type {function(DOMRect|ClientRect, DOMRect|ClientRect)}
  68. */
  69. var crossOriginUpdater = null;
  70. /**
  71. * The current cross-origin intersection. Only used in the cross-origin mode.
  72. * @type {DOMRect|ClientRect}
  73. */
  74. var crossOriginRect = null;
  75. /**
  76. * Creates the global IntersectionObserverEntry constructor.
  77. * https://w3c.github.io/IntersectionObserver/#intersection-observer-entry
  78. * @param {Object} entry A dictionary of instance properties.
  79. * @constructor
  80. */
  81. function IntersectionObserverEntry(entry) {
  82. this.time = entry.time;
  83. this.target = entry.target;
  84. this.rootBounds = ensureDOMRect(entry.rootBounds);
  85. this.boundingClientRect = ensureDOMRect(entry.boundingClientRect);
  86. this.intersectionRect = ensureDOMRect(entry.intersectionRect || getEmptyRect());
  87. this.isIntersecting = !!entry.intersectionRect;
  88. // Calculates the intersection ratio.
  89. var targetRect = this.boundingClientRect;
  90. var targetArea = targetRect.width * targetRect.height;
  91. var intersectionRect = this.intersectionRect;
  92. var intersectionArea = intersectionRect.width * intersectionRect.height;
  93. // Sets intersection ratio.
  94. if (targetArea) {
  95. // Round the intersection ratio to avoid floating point math issues:
  96. // https://github.com/w3c/IntersectionObserver/issues/324
  97. this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4));
  98. } else {
  99. // If area is zero and is intersecting, sets to 1, otherwise to 0
  100. this.intersectionRatio = this.isIntersecting ? 1 : 0;
  101. }
  102. }
  103. /**
  104. * Creates the global IntersectionObserver constructor.
  105. * https://w3c.github.io/IntersectionObserver/#intersection-observer-interface
  106. * @param {Function} callback The function to be invoked after intersection
  107. * changes have queued. The function is not invoked if the queue has
  108. * been emptied by calling the `takeRecords` method.
  109. * @param {Object=} opt_options Optional configuration options.
  110. * @constructor
  111. */
  112. function IntersectionObserver(callback, opt_options) {
  113. var options = opt_options || {};
  114. if (typeof callback != 'function') {
  115. throw new Error('callback must be a function');
  116. }
  117. if (
  118. options.root &&
  119. options.root.nodeType != 1 &&
  120. options.root.nodeType != 9
  121. ) {
  122. throw new Error('root must be a Document or Element');
  123. }
  124. // Binds and throttles `this._checkForIntersections`.
  125. this._checkForIntersections = throttle(
  126. this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT);
  127. // Private properties.
  128. this._callback = callback;
  129. this._observationTargets = [];
  130. this._queuedEntries = [];
  131. this._rootMarginValues = this._parseRootMargin(options.rootMargin);
  132. // Public properties.
  133. this.thresholds = this._initThresholds(options.threshold);
  134. this.root = options.root || null;
  135. this.rootMargin = this._rootMarginValues.map(function(margin) {
  136. return margin.value + margin.unit;
  137. }).join(' ');
  138. /** @private @const {!Array<!Document>} */
  139. this._monitoringDocuments = [];
  140. /** @private @const {!Array<function()>} */
  141. this._monitoringUnsubscribes = [];
  142. }
  143. /**
  144. * The minimum interval within which the document will be checked for
  145. * intersection changes.
  146. */
  147. IntersectionObserver.prototype.THROTTLE_TIMEOUT = 100;
  148. /**
  149. * The frequency in which the polyfill polls for intersection changes.
  150. * this can be updated on a per instance basis and must be set prior to
  151. * calling `observe` on the first target.
  152. */
  153. IntersectionObserver.prototype.POLL_INTERVAL = null;
  154. /**
  155. * Use a mutation observer on the root element
  156. * to detect intersection changes.
  157. */
  158. IntersectionObserver.prototype.USE_MUTATION_OBSERVER = true;
  159. /**
  160. * Sets up the polyfill in the cross-origin mode. The result is the
  161. * updater function that accepts two arguments: `boundingClientRect` and
  162. * `intersectionRect` - just as these fields would be available to the
  163. * parent via `IntersectionObserverEntry`. This function should be called
  164. * each time the iframe receives intersection information from the parent
  165. * window, e.g. via messaging.
  166. * @return {function(DOMRect|ClientRect, DOMRect|ClientRect)}
  167. */
  168. IntersectionObserver._setupCrossOriginUpdater = function() {
  169. if (!crossOriginUpdater) {
  170. /**
  171. * @param {DOMRect|ClientRect} boundingClientRect
  172. * @param {DOMRect|ClientRect} intersectionRect
  173. */
  174. crossOriginUpdater = function(boundingClientRect, intersectionRect) {
  175. if (!boundingClientRect || !intersectionRect) {
  176. crossOriginRect = getEmptyRect();
  177. } else {
  178. crossOriginRect = convertFromParentRect(boundingClientRect, intersectionRect);
  179. }
  180. registry.forEach(function(observer) {
  181. observer._checkForIntersections();
  182. });
  183. };
  184. }
  185. return crossOriginUpdater;
  186. };
  187. /**
  188. * Resets the cross-origin mode.
  189. */
  190. IntersectionObserver._resetCrossOriginUpdater = function() {
  191. crossOriginUpdater = null;
  192. crossOriginRect = null;
  193. };
  194. /**
  195. * Starts observing a target element for intersection changes based on
  196. * the thresholds values.
  197. * @param {Element} target The DOM element to observe.
  198. */
  199. IntersectionObserver.prototype.observe = function(target) {
  200. var isTargetAlreadyObserved = this._observationTargets.some(function(item) {
  201. return item.element == target;
  202. });
  203. if (isTargetAlreadyObserved) {
  204. return;
  205. }
  206. if (!(target && target.nodeType == 1)) {
  207. throw new Error('target must be an Element');
  208. }
  209. this._registerInstance();
  210. this._observationTargets.push({element: target, entry: null});
  211. this._monitorIntersections(target.ownerDocument);
  212. this._checkForIntersections();
  213. };
  214. /**
  215. * Stops observing a target element for intersection changes.
  216. * @param {Element} target The DOM element to observe.
  217. */
  218. IntersectionObserver.prototype.unobserve = function(target) {
  219. this._observationTargets =
  220. this._observationTargets.filter(function(item) {
  221. return item.element != target;
  222. });
  223. this._unmonitorIntersections(target.ownerDocument);
  224. if (this._observationTargets.length == 0) {
  225. this._unregisterInstance();
  226. }
  227. };
  228. /**
  229. * Stops observing all target elements for intersection changes.
  230. */
  231. IntersectionObserver.prototype.disconnect = function() {
  232. this._observationTargets = [];
  233. this._unmonitorAllIntersections();
  234. this._unregisterInstance();
  235. };
  236. /**
  237. * Returns any queue entries that have not yet been reported to the
  238. * callback and clears the queue. This can be used in conjunction with the
  239. * callback to obtain the absolute most up-to-date intersection information.
  240. * @return {Array} The currently queued entries.
  241. */
  242. IntersectionObserver.prototype.takeRecords = function() {
  243. var records = this._queuedEntries.slice();
  244. this._queuedEntries = [];
  245. return records;
  246. };
  247. /**
  248. * Accepts the threshold value from the user configuration object and
  249. * returns a sorted array of unique threshold values. If a value is not
  250. * between 0 and 1 and error is thrown.
  251. * @private
  252. * @param {Array|number=} opt_threshold An optional threshold value or
  253. * a list of threshold values, defaulting to [0].
  254. * @return {Array} A sorted list of unique and valid threshold values.
  255. */
  256. IntersectionObserver.prototype._initThresholds = function(opt_threshold) {
  257. var threshold = opt_threshold || [0];
  258. if (!Array.isArray(threshold)) threshold = [threshold];
  259. return threshold.sort().filter(function(t, i, a) {
  260. if (typeof t != 'number' || isNaN(t) || t < 0 || t > 1) {
  261. throw new Error('threshold must be a number between 0 and 1 inclusively');
  262. }
  263. return t !== a[i - 1];
  264. });
  265. };
  266. /**
  267. * Accepts the rootMargin value from the user configuration object
  268. * and returns an array of the four margin values as an object containing
  269. * the value and unit properties. If any of the values are not properly
  270. * formatted or use a unit other than px or %, and error is thrown.
  271. * @private
  272. * @param {string=} opt_rootMargin An optional rootMargin value,
  273. * defaulting to '0px'.
  274. * @return {Array<Object>} An array of margin objects with the keys
  275. * value and unit.
  276. */
  277. IntersectionObserver.prototype._parseRootMargin = function(opt_rootMargin) {
  278. var marginString = opt_rootMargin || '0px';
  279. var margins = marginString.split(/\s+/).map(function(margin) {
  280. var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin);
  281. if (!parts) {
  282. throw new Error('rootMargin must be specified in pixels or percent');
  283. }
  284. return {value: parseFloat(parts[1]), unit: parts[2]};
  285. });
  286. // Handles shorthand.
  287. margins[1] = margins[1] || margins[0];
  288. margins[2] = margins[2] || margins[0];
  289. margins[3] = margins[3] || margins[1];
  290. return margins;
  291. };
  292. /**
  293. * Starts polling for intersection changes if the polling is not already
  294. * happening, and if the page's visibility state is visible.
  295. * @param {!Document} doc
  296. * @private
  297. */
  298. IntersectionObserver.prototype._monitorIntersections = function(doc) {
  299. var win = doc.defaultView;
  300. if (!win) {
  301. // Already destroyed.
  302. return;
  303. }
  304. if (this._monitoringDocuments.indexOf(doc) != -1) {
  305. // Already monitoring.
  306. return;
  307. }
  308. // Private state for monitoring.
  309. var callback = this._checkForIntersections;
  310. var monitoringInterval = null;
  311. var domObserver = null;
  312. // If a poll interval is set, use polling instead of listening to
  313. // resize and scroll events or DOM mutations.
  314. if (this.POLL_INTERVAL) {
  315. monitoringInterval = win.setInterval(callback, this.POLL_INTERVAL);
  316. } else {
  317. addEvent(win, 'resize', callback, true);
  318. addEvent(doc, 'scroll', callback, true);
  319. if (this.USE_MUTATION_OBSERVER && 'MutationObserver' in win) {
  320. domObserver = new win.MutationObserver(callback);
  321. domObserver.observe(doc, {
  322. attributes: true,
  323. childList: true,
  324. characterData: true,
  325. subtree: true
  326. });
  327. }
  328. }
  329. this._monitoringDocuments.push(doc);
  330. this._monitoringUnsubscribes.push(function() {
  331. // Get the window object again. When a friendly iframe is destroyed, it
  332. // will be null.
  333. var win = doc.defaultView;
  334. if (win) {
  335. if (monitoringInterval) {
  336. win.clearInterval(monitoringInterval);
  337. }
  338. removeEvent(win, 'resize', callback, true);
  339. }
  340. removeEvent(doc, 'scroll', callback, true);
  341. if (domObserver) {
  342. domObserver.disconnect();
  343. }
  344. });
  345. // Also monitor the parent.
  346. var rootDoc =
  347. (this.root && (this.root.ownerDocument || this.root)) || document;
  348. if (doc != rootDoc) {
  349. var frame = getFrameElement(doc);
  350. if (frame) {
  351. this._monitorIntersections(frame.ownerDocument);
  352. }
  353. }
  354. };
  355. /**
  356. * Stops polling for intersection changes.
  357. * @param {!Document} doc
  358. * @private
  359. */
  360. IntersectionObserver.prototype._unmonitorIntersections = function(doc) {
  361. var index = this._monitoringDocuments.indexOf(doc);
  362. if (index == -1) {
  363. return;
  364. }
  365. var rootDoc =
  366. (this.root && (this.root.ownerDocument || this.root)) || document;
  367. // Check if any dependent targets are still remaining.
  368. var hasDependentTargets =
  369. this._observationTargets.some(function(item) {
  370. var itemDoc = item.element.ownerDocument;
  371. // Target is in this context.
  372. if (itemDoc == doc) {
  373. return true;
  374. }
  375. // Target is nested in this context.
  376. while (itemDoc && itemDoc != rootDoc) {
  377. var frame = getFrameElement(itemDoc);
  378. itemDoc = frame && frame.ownerDocument;
  379. if (itemDoc == doc) {
  380. return true;
  381. }
  382. }
  383. return false;
  384. });
  385. if (hasDependentTargets) {
  386. return;
  387. }
  388. // Unsubscribe.
  389. var unsubscribe = this._monitoringUnsubscribes[index];
  390. this._monitoringDocuments.splice(index, 1);
  391. this._monitoringUnsubscribes.splice(index, 1);
  392. unsubscribe();
  393. // Also unmonitor the parent.
  394. if (doc != rootDoc) {
  395. var frame = getFrameElement(doc);
  396. if (frame) {
  397. this._unmonitorIntersections(frame.ownerDocument);
  398. }
  399. }
  400. };
  401. /**
  402. * Stops polling for intersection changes.
  403. * @param {!Document} doc
  404. * @private
  405. */
  406. IntersectionObserver.prototype._unmonitorAllIntersections = function() {
  407. var unsubscribes = this._monitoringUnsubscribes.slice(0);
  408. this._monitoringDocuments.length = 0;
  409. this._monitoringUnsubscribes.length = 0;
  410. for (var i = 0; i < unsubscribes.length; i++) {
  411. unsubscribes[i]();
  412. }
  413. };
  414. /**
  415. * Scans each observation target for intersection changes and adds them
  416. * to the internal entries queue. If new entries are found, it
  417. * schedules the callback to be invoked.
  418. * @private
  419. */
  420. IntersectionObserver.prototype._checkForIntersections = function() {
  421. if (!this.root && crossOriginUpdater && !crossOriginRect) {
  422. // Cross origin monitoring, but no initial data available yet.
  423. return;
  424. }
  425. var rootIsInDom = this._rootIsInDom();
  426. var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect();
  427. this._observationTargets.forEach(function(item) {
  428. var target = item.element;
  429. var targetRect = getBoundingClientRect(target);
  430. var rootContainsTarget = this._rootContainsTarget(target);
  431. var oldEntry = item.entry;
  432. var intersectionRect = rootIsInDom && rootContainsTarget &&
  433. this._computeTargetAndRootIntersection(target, targetRect, rootRect);
  434. var rootBounds = null;
  435. if (!this._rootContainsTarget(target)) {
  436. rootBounds = getEmptyRect();
  437. } else if (!crossOriginUpdater || this.root) {
  438. rootBounds = rootRect;
  439. }
  440. var newEntry = item.entry = new IntersectionObserverEntry({
  441. time: now(),
  442. target: target,
  443. boundingClientRect: targetRect,
  444. rootBounds: rootBounds,
  445. intersectionRect: intersectionRect
  446. });
  447. if (!oldEntry) {
  448. this._queuedEntries.push(newEntry);
  449. } else if (rootIsInDom && rootContainsTarget) {
  450. // If the new entry intersection ratio has crossed any of the
  451. // thresholds, add a new entry.
  452. if (this._hasCrossedThreshold(oldEntry, newEntry)) {
  453. this._queuedEntries.push(newEntry);
  454. }
  455. } else {
  456. // If the root is not in the DOM or target is not contained within
  457. // root but the previous entry for this target had an intersection,
  458. // add a new record indicating removal.
  459. if (oldEntry && oldEntry.isIntersecting) {
  460. this._queuedEntries.push(newEntry);
  461. }
  462. }
  463. }, this);
  464. if (this._queuedEntries.length) {
  465. this._callback(this.takeRecords(), this);
  466. }
  467. };
  468. /**
  469. * Accepts a target and root rect computes the intersection between then
  470. * following the algorithm in the spec.
  471. * TODO(philipwalton): at this time clip-path is not considered.
  472. * https://w3c.github.io/IntersectionObserver/#calculate-intersection-rect-algo
  473. * @param {Element} target The target DOM element
  474. * @param {Object} targetRect The bounding rect of the target.
  475. * @param {Object} rootRect The bounding rect of the root after being
  476. * expanded by the rootMargin value.
  477. * @return {?Object} The final intersection rect object or undefined if no
  478. * intersection is found.
  479. * @private
  480. */
  481. IntersectionObserver.prototype._computeTargetAndRootIntersection =
  482. function(target, targetRect, rootRect) {
  483. // If the element isn't displayed, an intersection can't happen.
  484. if (window.getComputedStyle(target).display == 'none') return;
  485. var intersectionRect = targetRect;
  486. var parent = getParentNode(target);
  487. var atRoot = false;
  488. while (!atRoot && parent) {
  489. var parentRect = null;
  490. var parentComputedStyle = parent.nodeType == 1 ?
  491. window.getComputedStyle(parent) : {};
  492. // If the parent isn't displayed, an intersection can't happen.
  493. if (parentComputedStyle.display == 'none') return null;
  494. if (parent == this.root || parent.nodeType == /* DOCUMENT */ 9) {
  495. atRoot = true;
  496. if (parent == this.root || parent == document) {
  497. if (crossOriginUpdater && !this.root) {
  498. if (!crossOriginRect ||
  499. crossOriginRect.width == 0 && crossOriginRect.height == 0) {
  500. // A 0-size cross-origin intersection means no-intersection.
  501. parent = null;
  502. parentRect = null;
  503. intersectionRect = null;
  504. } else {
  505. parentRect = crossOriginRect;
  506. }
  507. } else {
  508. parentRect = rootRect;
  509. }
  510. } else {
  511. // Check if there's a frame that can be navigated to.
  512. var frame = getParentNode(parent);
  513. var frameRect = frame && getBoundingClientRect(frame);
  514. var frameIntersect =
  515. frame &&
  516. this._computeTargetAndRootIntersection(frame, frameRect, rootRect);
  517. if (frameRect && frameIntersect) {
  518. parent = frame;
  519. parentRect = convertFromParentRect(frameRect, frameIntersect);
  520. } else {
  521. parent = null;
  522. intersectionRect = null;
  523. }
  524. }
  525. } else {
  526. // If the element has a non-visible overflow, and it's not the <body>
  527. // or <html> element, update the intersection rect.
  528. // Note: <body> and <html> cannot be clipped to a rect that's not also
  529. // the document rect, so no need to compute a new intersection.
  530. var doc = parent.ownerDocument;
  531. if (parent != doc.body &&
  532. parent != doc.documentElement &&
  533. parentComputedStyle.overflow != 'visible') {
  534. parentRect = getBoundingClientRect(parent);
  535. }
  536. }
  537. // If either of the above conditionals set a new parentRect,
  538. // calculate new intersection data.
  539. if (parentRect) {
  540. intersectionRect = computeRectIntersection(parentRect, intersectionRect);
  541. }
  542. if (!intersectionRect) break;
  543. parent = parent && getParentNode(parent);
  544. }
  545. return intersectionRect;
  546. };
  547. /**
  548. * Returns the root rect after being expanded by the rootMargin value.
  549. * @return {ClientRect} The expanded root rect.
  550. * @private
  551. */
  552. IntersectionObserver.prototype._getRootRect = function() {
  553. var rootRect;
  554. if (this.root && !isDoc(this.root)) {
  555. rootRect = getBoundingClientRect(this.root);
  556. } else {
  557. // Use <html>/<body> instead of window since scroll bars affect size.
  558. var doc = isDoc(this.root) ? this.root : document;
  559. var html = doc.documentElement;
  560. var body = doc.body;
  561. rootRect = {
  562. top: 0,
  563. left: 0,
  564. right: html.clientWidth || body.clientWidth,
  565. width: html.clientWidth || body.clientWidth,
  566. bottom: html.clientHeight || body.clientHeight,
  567. height: html.clientHeight || body.clientHeight
  568. };
  569. }
  570. return this._expandRectByRootMargin(rootRect);
  571. };
  572. /**
  573. * Accepts a rect and expands it by the rootMargin value.
  574. * @param {DOMRect|ClientRect} rect The rect object to expand.
  575. * @return {ClientRect} The expanded rect.
  576. * @private
  577. */
  578. IntersectionObserver.prototype._expandRectByRootMargin = function(rect) {
  579. var margins = this._rootMarginValues.map(function(margin, i) {
  580. return margin.unit == 'px' ? margin.value :
  581. margin.value * (i % 2 ? rect.width : rect.height) / 100;
  582. });
  583. var newRect = {
  584. top: rect.top - margins[0],
  585. right: rect.right + margins[1],
  586. bottom: rect.bottom + margins[2],
  587. left: rect.left - margins[3]
  588. };
  589. newRect.width = newRect.right - newRect.left;
  590. newRect.height = newRect.bottom - newRect.top;
  591. return newRect;
  592. };
  593. /**
  594. * Accepts an old and new entry and returns true if at least one of the
  595. * threshold values has been crossed.
  596. * @param {?IntersectionObserverEntry} oldEntry The previous entry for a
  597. * particular target element or null if no previous entry exists.
  598. * @param {IntersectionObserverEntry} newEntry The current entry for a
  599. * particular target element.
  600. * @return {boolean} Returns true if a any threshold has been crossed.
  601. * @private
  602. */
  603. IntersectionObserver.prototype._hasCrossedThreshold =
  604. function(oldEntry, newEntry) {
  605. // To make comparing easier, an entry that has a ratio of 0
  606. // but does not actually intersect is given a value of -1
  607. var oldRatio = oldEntry && oldEntry.isIntersecting ?
  608. oldEntry.intersectionRatio || 0 : -1;
  609. var newRatio = newEntry.isIntersecting ?
  610. newEntry.intersectionRatio || 0 : -1;
  611. // Ignore unchanged ratios
  612. if (oldRatio === newRatio) return;
  613. for (var i = 0; i < this.thresholds.length; i++) {
  614. var threshold = this.thresholds[i];
  615. // Return true if an entry matches a threshold or if the new ratio
  616. // and the old ratio are on the opposite sides of a threshold.
  617. if (threshold == oldRatio || threshold == newRatio ||
  618. threshold < oldRatio !== threshold < newRatio) {
  619. return true;
  620. }
  621. }
  622. };
  623. /**
  624. * Returns whether or not the root element is an element and is in the DOM.
  625. * @return {boolean} True if the root element is an element and is in the DOM.
  626. * @private
  627. */
  628. IntersectionObserver.prototype._rootIsInDom = function() {
  629. return !this.root || containsDeep(document, this.root);
  630. };
  631. /**
  632. * Returns whether or not the target element is a child of root.
  633. * @param {Element} target The target element to check.
  634. * @return {boolean} True if the target element is a child of root.
  635. * @private
  636. */
  637. IntersectionObserver.prototype._rootContainsTarget = function(target) {
  638. var rootDoc =
  639. (this.root && (this.root.ownerDocument || this.root)) || document;
  640. return (
  641. containsDeep(rootDoc, target) &&
  642. (!this.root || rootDoc == target.ownerDocument)
  643. );
  644. };
  645. /**
  646. * Adds the instance to the global IntersectionObserver registry if it isn't
  647. * already present.
  648. * @private
  649. */
  650. IntersectionObserver.prototype._registerInstance = function() {
  651. if (registry.indexOf(this) < 0) {
  652. registry.push(this);
  653. }
  654. };
  655. /**
  656. * Removes the instance from the global IntersectionObserver registry.
  657. * @private
  658. */
  659. IntersectionObserver.prototype._unregisterInstance = function() {
  660. var index = registry.indexOf(this);
  661. if (index != -1) registry.splice(index, 1);
  662. };
  663. /**
  664. * Returns the result of the performance.now() method or null in browsers
  665. * that don't support the API.
  666. * @return {number} The elapsed time since the page was requested.
  667. */
  668. function now() {
  669. return window.performance && performance.now && performance.now();
  670. }
  671. /**
  672. * Throttles a function and delays its execution, so it's only called at most
  673. * once within a given time period.
  674. * @param {Function} fn The function to throttle.
  675. * @param {number} timeout The amount of time that must pass before the
  676. * function can be called again.
  677. * @return {Function} The throttled function.
  678. */
  679. function throttle(fn, timeout) {
  680. var timer = null;
  681. return function () {
  682. if (!timer) {
  683. timer = setTimeout(function() {
  684. fn();
  685. timer = null;
  686. }, timeout);
  687. }
  688. };
  689. }
  690. /**
  691. * Adds an event handler to a DOM node ensuring cross-browser compatibility.
  692. * @param {Node} node The DOM node to add the event handler to.
  693. * @param {string} event The event name.
  694. * @param {Function} fn The event handler to add.
  695. * @param {boolean} opt_useCapture Optionally adds the even to the capture
  696. * phase. Note: this only works in modern browsers.
  697. */
  698. function addEvent(node, event, fn, opt_useCapture) {
  699. if (typeof node.addEventListener == 'function') {
  700. node.addEventListener(event, fn, opt_useCapture || false);
  701. }
  702. else if (typeof node.attachEvent == 'function') {
  703. node.attachEvent('on' + event, fn);
  704. }
  705. }
  706. /**
  707. * Removes a previously added event handler from a DOM node.
  708. * @param {Node} node The DOM node to remove the event handler from.
  709. * @param {string} event The event name.
  710. * @param {Function} fn The event handler to remove.
  711. * @param {boolean} opt_useCapture If the event handler was added with this
  712. * flag set to true, it should be set to true here in order to remove it.
  713. */
  714. function removeEvent(node, event, fn, opt_useCapture) {
  715. if (typeof node.removeEventListener == 'function') {
  716. node.removeEventListener(event, fn, opt_useCapture || false);
  717. }
  718. else if (typeof node.detatchEvent == 'function') {
  719. node.detatchEvent('on' + event, fn);
  720. }
  721. }
  722. /**
  723. * Returns the intersection between two rect objects.
  724. * @param {Object} rect1 The first rect.
  725. * @param {Object} rect2 The second rect.
  726. * @return {?Object|?ClientRect} The intersection rect or undefined if no
  727. * intersection is found.
  728. */
  729. function computeRectIntersection(rect1, rect2) {
  730. var top = Math.max(rect1.top, rect2.top);
  731. var bottom = Math.min(rect1.bottom, rect2.bottom);
  732. var left = Math.max(rect1.left, rect2.left);
  733. var right = Math.min(rect1.right, rect2.right);
  734. var width = right - left;
  735. var height = bottom - top;
  736. return (width >= 0 && height >= 0) && {
  737. top: top,
  738. bottom: bottom,
  739. left: left,
  740. right: right,
  741. width: width,
  742. height: height
  743. } || null;
  744. }
  745. /**
  746. * Shims the native getBoundingClientRect for compatibility with older IE.
  747. * @param {Element} el The element whose bounding rect to get.
  748. * @return {DOMRect|ClientRect} The (possibly shimmed) rect of the element.
  749. */
  750. function getBoundingClientRect(el) {
  751. var rect;
  752. try {
  753. rect = el.getBoundingClientRect();
  754. } catch (err) {
  755. // Ignore Windows 7 IE11 "Unspecified error"
  756. // https://github.com/w3c/IntersectionObserver/pull/205
  757. }
  758. if (!rect) return getEmptyRect();
  759. // Older IE
  760. if (!(rect.width && rect.height)) {
  761. rect = {
  762. top: rect.top,
  763. right: rect.right,
  764. bottom: rect.bottom,
  765. left: rect.left,
  766. width: rect.right - rect.left,
  767. height: rect.bottom - rect.top
  768. };
  769. }
  770. return rect;
  771. }
  772. /**
  773. * Returns an empty rect object. An empty rect is returned when an element
  774. * is not in the DOM.
  775. * @return {ClientRect} The empty rect.
  776. */
  777. function getEmptyRect() {
  778. return {
  779. top: 0,
  780. bottom: 0,
  781. left: 0,
  782. right: 0,
  783. width: 0,
  784. height: 0
  785. };
  786. }
  787. /**
  788. * Ensure that the result has all of the necessary fields of the DOMRect.
  789. * Specifically this ensures that `x` and `y` fields are set.
  790. *
  791. * @param {?DOMRect|?ClientRect} rect
  792. * @return {?DOMRect}
  793. */
  794. function ensureDOMRect(rect) {
  795. // A `DOMRect` object has `x` and `y` fields.
  796. if (!rect || 'x' in rect) {
  797. return rect;
  798. }
  799. // A IE's `ClientRect` type does not have `x` and `y`. The same is the case
  800. // for internally calculated Rect objects. For the purposes of
  801. // `IntersectionObserver`, it's sufficient to simply mirror `left` and `top`
  802. // for these fields.
  803. return {
  804. top: rect.top,
  805. y: rect.top,
  806. bottom: rect.bottom,
  807. left: rect.left,
  808. x: rect.left,
  809. right: rect.right,
  810. width: rect.width,
  811. height: rect.height
  812. };
  813. }
  814. /**
  815. * Inverts the intersection and bounding rect from the parent (frame) BCR to
  816. * the local BCR space.
  817. * @param {DOMRect|ClientRect} parentBoundingRect The parent's bound client rect.
  818. * @param {DOMRect|ClientRect} parentIntersectionRect The parent's own intersection rect.
  819. * @return {ClientRect} The local root bounding rect for the parent's children.
  820. */
  821. function convertFromParentRect(parentBoundingRect, parentIntersectionRect) {
  822. var top = parentIntersectionRect.top - parentBoundingRect.top;
  823. var left = parentIntersectionRect.left - parentBoundingRect.left;
  824. return {
  825. top: top,
  826. left: left,
  827. height: parentIntersectionRect.height,
  828. width: parentIntersectionRect.width,
  829. bottom: top + parentIntersectionRect.height,
  830. right: left + parentIntersectionRect.width
  831. };
  832. }
  833. /**
  834. * Checks to see if a parent element contains a child element (including inside
  835. * shadow DOM).
  836. * @param {Node} parent The parent element.
  837. * @param {Node} child The child element.
  838. * @return {boolean} True if the parent node contains the child node.
  839. */
  840. function containsDeep(parent, child) {
  841. var node = child;
  842. while (node) {
  843. if (node == parent) return true;
  844. node = getParentNode(node);
  845. }
  846. return false;
  847. }
  848. /**
  849. * Gets the parent node of an element or its host element if the parent node
  850. * is a shadow root.
  851. * @param {Node} node The node whose parent to get.
  852. * @return {Node|null} The parent node or null if no parent exists.
  853. */
  854. function getParentNode(node) {
  855. var parent = node.parentNode;
  856. if (node.nodeType == /* DOCUMENT */ 9 && node != document) {
  857. // If this node is a document node, look for the embedding frame.
  858. return getFrameElement(node);
  859. }
  860. // If the parent has element that is assigned through shadow root slot
  861. if (parent && parent.assignedSlot) {
  862. parent = parent.assignedSlot.parentNode
  863. }
  864. if (parent && parent.nodeType == 11 && parent.host) {
  865. // If the parent is a shadow root, return the host element.
  866. return parent.host;
  867. }
  868. return parent;
  869. }
  870. /**
  871. * Returns true if `node` is a Document.
  872. * @param {!Node} node
  873. * @returns {boolean}
  874. */
  875. function isDoc(node) {
  876. return node && node.nodeType === 9;
  877. }
  878. // Exposes the constructors globally.
  879. window.IntersectionObserver = IntersectionObserver;
  880. window.IntersectionObserverEntry = IntersectionObserverEntry;
  881. }());