PageSourceSearch

https://www.weaudition.com/blog/wp-content/themes/zoxpress/js/intersection-observer.js

js weaudition.com collected 2026-09-24 19:15:12 UTC 22,304 bytes, 732 lines download raw bytes

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
10(function(window, document) {
11'use strict';
12
13
14// Exits early if all IntersectionObserver and IntersectionObserverEntry
15// features are natively supported.
16if ('IntersectionObserver' in window &&
17    'IntersectionObserverEntry' in window &&
18    'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
19
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
34/**
35 * An IntersectionObserver registry. This registry exists to hold a strong
36 * reference to IntersectionObserver instances currently observing a target
37 * element. Without this registry, instances without another reference may be
38 * garbage collected.
39 */
40var registry = [];
41
42
43/**
44 * Creates the global IntersectionObserverEntry constructor.
45 * https://w3c.github.io/IntersectionObserver/#intersection-observer-entry
46 * @param {Object} entry A dictionary of instance properties.
47 * @constructor
48 */
49function IntersectionObserverEntry(entry) {
50  this.time = entry.time;
51  this.target = entry.target;
52  this.rootBounds = entry.rootBounds;
53  this.boundingClientRect = entry.boundingClientRect;
54  this.intersectionRect = entry.intersectionRect || getEmptyRect();
55  this.isIntersecting = !!entry.intersectionRect;
56
57  // Calculates the intersection ratio.
58  var targetRect = this.boundingClientRect;
59  var targetArea = targetRect.width * targetRect.height;
60  var intersectionRect = this.intersectionRect;
61  var intersectionArea = intersectionRect.width * intersectionRect.height;
62
63  // Sets intersection ratio.
64  if (targetArea) {
65    // Round the intersection ratio to avoid floating point math issues:
66    // https://github.com/w3c/IntersectionObserver/issues/324
67    this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4));
68  } else {
69    // If area is zero and is intersecting, sets to 1, otherwise to 0
70    this.intersectionRatio = this.isIntersecting ? 1 : 0;
71  }
72}
73
74
75/**
76 * Creates the global IntersectionObserver constructor.
77 * https://w3c.github.io/IntersectionObserver/#intersection-observer-interface
78 * @param {Function} callback The function to be invoked after intersection
79 *     changes have queued. The function is not invoked if the queue has
80 *     been emptied by calling the `takeRecords` method.
81 * @param {Object=} opt_options Optional configuration options.
82 * @constructor
83 */
84function IntersectionObserver(callback, opt_options) {
85
86  var options = opt_options || {};
87
88  if (typeof callback != 'function') {
89    throw new Error('callback must be a function');
90  }
91
92  if (options.root && options.root.nodeType != 1) {
93    throw new Error('root must be an Element');
94  }
95
96  // Binds and throttles `this._checkForIntersections`.
97  this._checkForIntersections = throttle(
98      this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT);
99
100  // Private properties.
101  this._callback = callback;
102  this._observationTargets = [];
103  this._queuedEntries = [];
104  this._rootMarginValues = this._parseRootMargin(options.rootMargin);
105
106  // Public properties.
107  this.thresholds = this._initThresholds(options.threshold);
108  this.root = options.root || null;
109  this.rootMargin = this._rootMarginValues.map(function(margin) {
110    return margin.value + margin.unit;
111  }).join(' ');
112}
113
114
115/**
116 * The minimum interval within which the document will be checked for
117 * intersection changes.
118 */
119IntersectionObserver.prototype.THROTTLE_TIMEOUT = 100;
120
121
122/**
123 * The frequency in which the polyfill polls for intersection changes.
124 * this can be updated on a per instance basis and must be set prior to
125 * calling `observe` on the first target.
126 */
127IntersectionObserver.prototype.POLL_INTERVAL = null;
128
129/**
130 * Use a mutation observer on the root element
131 * to detect intersection changes.
132 */
133IntersectionObserver.prototype.USE_MUTATION_OBSERVER = true;
134
135
136/**
137 * Starts observing a target element for intersection changes based on
138 * the thresholds values.
139 * @param {Element} target The DOM element to observe.
140 */
141IntersectionObserver.prototype.observe = function(target) {
142  var isTargetAlreadyObserved = this._observationTargets.some(function(item) {
143    return item.element == target;
144  });
145
146  if (isTargetAlreadyObserved) {
147    return;
148  }
149
vendor: 2,303 bytes, lines 150-225
150  if (!(target && target.nodeType == 1)) {
151    throw new Error('target must be an Element');
152  }
153
154  this._registerInstance();
155  this._observationTargets.push({element: target, entry: null});
156  this._monitorIntersections();
157  this._checkForIntersections();
158};
159
160
161/**
162 * Stops observing a target element for intersection changes.
163 * @param {Element} target The DOM element to observe.
164 */
165IntersectionObserver.prototype.unobserve = function(target) {
166  this._observationTargets =
167      this._observationTargets.filter(function(item) {
168
169    return item.element != target;
170  });
171  if (!this._observationTargets.length) {
172    this._unmonitorIntersections();
173    this._unregisterInstance();
174  }
175};
176
177
178/**
179 * Stops observing all target elements for intersection changes.
180 */
181IntersectionObserver.prototype.disconnect = function() {
182  this._observationTargets = [];
183  this._unmonitorIntersections();
184  this._unregisterInstance();
185};
186
187
188/**
189 * Returns any queue entries that have not yet been reported to the
190 * callback and clears the queue. This can be used in conjunction with the
191 * callback to obtain the absolute most up-to-date intersection information.
192 * @return {Array} The currently queued entries.
193 */
194IntersectionObserver.prototype.takeRecords = function() {
195  var records = this._queuedEntries.slice();
196  this._queuedEntries = [];
197  return records;
198};
199
200
201/**
202 * Accepts the threshold value from the user configuration object and
203 * returns a sorted array of unique threshold values. If a value is not
204 * between 0 and 1 and error is thrown.
205 * @private
206 * @param {Array|number=} opt_threshold An optional threshold value or
207 *     a list of threshold values, defaulting to [0].
208 * @return {Array} A sorted list of unique and valid threshold values.
209 */
210IntersectionObserver.prototype._initThresholds = function(opt_threshold) {
211  var threshold = opt_threshold || [0];
212  if (!Array.isArray(threshold)) threshold = [threshold];
213
214  return threshold.sort().filter(function(t, i, a) {
215    if (typeof t != 'number' || isNaN(t) || t < 0 || t > 1) {
216      throw new Error('threshold must be a number between 0 and 1 inclusively');
217    }
218    return t !== a[i - 1];
219  });
220};
221
222
223/**
224 * Accepts the rootMargin value from the user configuration object
225 * and returns an array of the four margin values as an object c
225ontaining
226 * the value and unit properties. If any of the values are not properly
227 * formatted or use a unit other than px or %, and error is thrown.
228 * @private
229 * @param {string=} opt_rootMargin An optional rootMargin value,
230 *     defaulting to '0px'.
231 * @return {Array<Object>} An array of margin objects with the keys
232 *     value and unit.
233 */
234IntersectionObserver.prototype._parseRootMargin = function(opt_rootMargin) {
235  var marginString = opt_rootMargin || '0px';
236  var margins = marginString.split(/\s+/).map(function(margin) {
237    var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin);
238    if (!parts) {
239      throw new Error('rootMargin must be specified in pixels or percent');
240    }
241    return {value: parseFloat(parts[1]), unit: parts[2]};
242  });
243
244  // Handles shorthand.
245  margins[1] = margins[1] || margins[0];
246  margins[2] = margins[2] || margins[0];
247  margins[3] = margins[3] || margins[1];
248
249  return margins;
250};
251
252
253/**
254 * Starts polling for intersection changes if the polling is not already
255 * happening, and if the page's visibility state is visible.
256 * @private
257 */
258IntersectionObserver.prototype._monitorIntersections = function() {
259  if (!this._monitoringIntersections) {
260    this._monitoringIntersections = true;
261
262    // If a poll interval is set, use polling instead of listening to
263    // resize and scroll events or DOM mutations.
264    if (this.POLL_INTERVAL) {
265      this._monitoringInterval = setInterval(
266          this._checkForIntersections, this.POLL_INTERVAL);
267    }
268    else {
269      addEvent(window, 'resize', this._checkForIntersections, true);
270      addEvent(document, 'scroll', this._checkForIntersections, true);
271
272      if (this.USE_MUTATION_OBSERVER && 'MutationObserver' in window) {
273        this._domObserver = new MutationObserver(this._checkForIntersections);
274        this._domObserver.observe(document, {
275          attributes: true,
276          childList: true,
277          characterData: true,
278          subtree: true
279        });
280      }
281    }
282  }
283};
284
285
286/**
287 * Stops polling for intersection changes.
288 * @private
289 */
290IntersectionObserver.prototype._unmonitorIntersections = function() {
291  if (this._monitoringIntersections) {
292    this._monitoringIntersections = false;
293
294    clearInterval(this._monitoringInterval);
295    this._monitoringInterval = null;
296
297    removeEvent(window, 'resize', this._checkForIntersections, true);
298    removeEvent(document, 'scroll', this._checkForIntersections, true);
299
300    if (this._domObserver) {
301      this._domObserver.disconnect();
302      this._domObserver = null;
303    }
304  }
305};
306
307
308/**
309 * Scans each observation target for intersection changes and adds them
310 * to the internal entries queue. If new entries are found, it
311 * schedules the callback to be invoked.
312 * @private
313 */
314IntersectionObserver.prototype._checkForIntersections = function() {
315  var rootIsInDom = this._rootIsInDom();
316  var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect();
317
318  this._observationTargets.forEach(function(item) {
319    var target = item.element;
320    var targetRect = getBoundingClientRect(target);
321    var rootContainsTarget = this._rootContainsTarget(target);
322    var oldEntry = item.entry;
323    var intersectionRect = rootIsInDom && rootContainsTarget &&
324        this._computeTargetAndRootIntersection(target, rootRect);
325
326    var newEntry = item.entry = new IntersectionObserverEntry({
327      time: now(),
328      target: target,
329      boundingClientRect: targetRect,
330      rootBounds: rootRect,
331      intersectionRect: intersectionRect
332    });
333
334    if (!oldEntry) {
335      this._queuedEntries.push(newEntry);
336    } else if (rootIsInDom && rootContainsTarget) {
337      // If the new entry intersection ratio has crossed any of the
338      // thresholds, add a new entry.
339      if (this._hasCrossedThreshold(oldEntry, newEntry)) {
340        this._queuedEntries.push(newEntry);
341      }
342    } else {
343      // If the root is not in the DOM or target is not contained within
344      // root but the previous entry for this target had an intersection,
345      // add a new record indicating removal.
346      if (oldEntry && oldEntry.isIntersecting) {
347        this._queuedEntries.push(newEntry);
348      }
349    }
350  }, this);
351
352  if (this._queuedEntries.length) {
353    this._callback(this.takeRecords(), this);
354  }
355};
356
357
358/**
359 * Accepts a target and root rect computes the intersection between then
360 * following the algorithm in the spec.
361 * TODO(philipwalton): at this time clip-path is not considered.
362 * https://w3c.github.io/IntersectionObserver/#calculate-intersection-rect-algo
363 * @param {Element} target The target DOM element
364 * @param {Object} rootRect The bounding rect of the root after being
365 *     expanded by the rootMargin value.
366 * @return {?Object} The final intersection rect object or undefined if no
367 *     intersection is found.
368 * @private
369 */
370IntersectionObserver.prototype._computeTargetAndRootIntersection =
371    function(target, rootRect) {
372
373  // If the element isn't displayed, an intersection can't happen.
374  if (window.getComputedStyle(target).display == 'none') return;
375
376  var targetRect = getBoundingClientRect(target);
377  var intersectionRect = targetRect;
378  var parent = getParentNode(target);
379  var atRoot = false;
vendor: 8,268 bytes, lines 380-650
380
381  while (!atRoot) {
382    var parentRect = null;
383    var parentComputedStyle = parent.nodeType == 1 ?
384        window.getComputedStyle(parent) : {};
385
386    // If the parent isn't displayed, an intersection can't happen.
387    if (parentComputedStyle.display == 'none') return;
388
389    if (parent == this.root || parent == document) {
390      atRoot = true;
391      parentRect = rootRect;
392    } else {
393      // If the element has a non-visible overflow, and it's not the <body>
394      // or <html> element, update the intersection rect.
395      // Note: <body> and <html> cannot be clipped to a rect that's not also
396      // the document rect, so no need to compute a new intersection.
397      if (parent != document.body &&
398          parent != document.documentElement &&
399          parentComputedStyle.overflow != 'visible') {
400        parentRect = getBoundingClientRect(parent);
401      }
402    }
403
404    // If either of the above conditionals set a new parentRect,
405    // calculate new intersection data.
406    if (parentRect) {
407      intersectionRect = computeRectIntersection(parentRect, intersectionRect);
408
409      if (!intersectionRect) break;
410    }
411    parent = getParentNode(parent);
412  }
413  return intersectionRect;
414};
415
416
417/**
418 * Returns the root rect after being expanded by the rootMargin value.
419 * @return {Object} The expanded root rect.
420 * @private
421 */
422IntersectionObserver.prototype._getRootRect = function() {
423  var rootRect;
424  if (this.root) {
425    rootRect = getBoundingClientRect(this.root);
426  } else {
427    // Use <html>/<body> instead of window since scroll bars affect size.
428    var html = document.documentElement;
429    var body = document.body;
430    rootRect = {
431      top: 0,
432      left: 0,
433      right: html.clientWidth || body.clientWidth,
434      width: html.clientWidth || body.clientWidth,
435      bottom: html.clientHeight || body.clientHeight,
436      height: html.clientHeight || body.clientHeight
437    };
438  }
439  return this._expandRectByRootMargin(rootRect);
440};
441
442
443/**
444 * Accepts a rect and expands it by the rootMargin value.
445 * @param {Object} rect The rect object to expand.
446 * @return {Object} The expanded rect.
447 * @private
448 */
449IntersectionObserver.prototype._expandRectByRootMargin = function(rect) {
450  var margins = this._rootMarginValues.map(function(margin, i) {
451    return margin.unit == 'px' ? margin.value :
452        margin.value * (i % 2 ? rect.width : rect.height) / 100;
453  });
454  var newRect = {
455    top: rect.top - margins[0],
456    right: rect.right + margins[1],
457    bottom: rect.bottom + margins[2],
458    left: rect.left - margins[3]
459  };
460  newRect.width = newRect.right - newRect.left;
461  newRect.height = newRect.bottom - newRect.top;
462
463  return newRect;
464};
465
466
467/**
468 * Accepts an old and new entry and returns true if at least one of the
469 * threshold values has been crossed.
470 * @param {?IntersectionObserverEntry} oldEntry The previous entry for a
471 *    particular target element or null if no previous entry exists.
472 * @param {IntersectionObserverEntry} newEntry The current entry for a
473 *    particular target element.
474 * @return {boolean} Returns true if a any threshold has been crossed.
475 * @private
476 */
477IntersectionObserver.prototype._hasCrossedThreshold =
478    function(oldEntry, newEntry) {
479
480  // To make comparing easier, an entry that has a ratio of 0
481  // but does not actually intersect is given a value of -1
482  var oldRatio = oldEntry && oldEntry.isIntersecting ?
483      oldEntry.intersectionRatio || 0 : -1;
484  var newRatio = newEntry.isIntersecting ?
485      newEntry.intersectionRatio || 0 : -1;
486
487  // Ignore unchanged ratios
488  if (oldRatio === newRatio) return;
489
490  for (var i = 0; i < this.thresholds.length; i++) {
491    var threshold = this.thresholds[i];
492
493    // Return true if an entry matches a threshold or if the new ratio
494    // and the old ratio are on the opposite sides of a threshold.
495    if (threshold == oldRatio || threshold == newRatio ||
496        threshold < oldRatio !== threshold < newRatio) {
497      return true;
498    }
499  }
500};
501
502
503/**
504 * Returns whether or not the root element is an element and is in the DOM.
505 * @return {boolean} True if the root element is an element and is in the DOM.
506 * @private
507 */
508IntersectionObserver.prototype._rootIsInDom = function() {
509  return !this.root || containsDeep(document, this.root);
510};
511
512
513/**
514 * Returns whether or not the target element is a child of root.
515 * @param {Element} target The target element to check.
516 * @return {boolean} True if the target element is a child of root.
517 * @private
518 */
519IntersectionObserver.prototype._rootContainsTarget = function(target) {
520  return containsDeep(this.root || document, target);
521};
522
523
524/**
525 * Adds the instance to the global IntersectionObserver registry if it isn't
526 * already present.
527 * @private
528 */
529IntersectionObserver.prototype._registerInstance = function() {
530  if (registry.indexOf(this) < 0) {
531    registry.push(this);
532  }
533};
534
535
536/**
537 * Removes the instance from the global IntersectionObserver registry.
538 * @private
539 */
540IntersectionObserver.prototype._unregisterInstance = function() {
541  var index = registry.indexOf(this);
542  if (index != -1) registry.splice(index, 1);
543};
544
545
546/**
547 * Returns the result of the performance.now() method or null in browsers
548 * that don't support the API.
549 * @return {number} The elapsed time since the page was requested.
550 */
551function now() {
552  return window.performance && performance.now && performance.now();
553}
554
555
556/**
557 * Throttles a function and delays its execution, so it's only called at most
558 * once within a given time period.
559 * @param {Function} fn The function to throttle.
560 * @param {number} timeout The amount of time that must pass before the
561 *     function can be called again.
562 * @return {Function} The throttled function.
563 */
564function throttle(fn, timeout) {
565  var timer = null;
566  return function () {
567    if (!timer) {
568      timer = setTimeout(function() {
569        fn();
570        timer = null;
571      }, timeout);
572    }
573  };
574}
575
576
577/**
578 * Adds an event handler to a DOM node ensuring cross-browser compatibility.
579 * @param {Node} node The DOM node to add the event handler to.
580 * @param {string} event The event name.
581 * @param {Function} fn The event handler to add.
582 * @param {boolean} opt_useCapture Optionally adds the even to the capture
583 *     phase. Note: this only works in modern browsers.
584 */
585function addEvent(node, event, fn, opt_useCapture) {
586  if (typeof node.addEventListener == 'function') {
587    node.addEventListener(event, fn, opt_useCapture || false);
588  }
589  else if (typeof node.attachEvent == 'function') {
590    node.attachEvent('on' + event, fn);
591  }
592}
593
594
595/**
596 * Removes a previously added event handler from a DOM node.
597 * @param {Node} node The DOM node to remove the event handler from.
598 * @param {string} event The event name.
599 * @param {Function} fn The event handler to remove.
600 * @param {boolean} opt_useCapture If the event handler was added with this
601 *     flag set to true, it should be set to true here in order to remove it.
602 */
603function removeEvent(node, event, fn, opt_useCapture) {
604  if (typeof node.removeEventListener == 'function') {
605    node.removeEventListener(event, fn, opt_useCapture || false);
606  }
607  else if (typeof node.detatchEvent == 'function') {
608    node.detatchEvent('on' + event, fn);
609  }
610}
611
612
613/**
614 * Returns the intersection between two rect objects.
615 * @param {Object} rect1 The first rect.
616 * @param {Object} rect2 The second rect.
617 * @return {?Object} The intersection rect or undefined if no intersection
618 *     is found.
619 */
620function computeRectIntersection(rect1, rect2) {
621  var top = Math.max(rect1.top, rect2.top);
622  var bottom = Math.min(rect1.bottom, rect2.bottom);
623  var left = Math.max(rect1.left, rect2.left);
624  var right = Math.min(rect1.right, rect2.right);
625  var width = right - left;
626  var height = bottom - top;
627
628  return (width >= 0 && height >= 0) && {
629    top: top,
630    bottom: bottom,
631    left: left,
632    right: right,
633    width: width,
634    height: height
635  };
636}
637
638
639/**
640 * Shims the native getBoundingClientRect for compatibility with older IE.
641 * @param {Element} el The element whose bounding rect to get.
642 * @return {Object} The (possibly shimmed) rect of the element.
643 */
644function getBoundingClientRect(el) {
645  var rect;
646
647  try {
648    rect = el.getBoundingClientRect();
649  } catch (err) {
650    // Ignore Windows 7 IE11 "Unspecified error"
651    // https://github.com/w3c/IntersectionObserver/pull/205
652  }
653
654  if (!rect) return getEmptyRect();
655
656  // Older IE
657  if (!(rect.width && rect.height)) {
658    rect = {
659      top: rect.top,
660      right: rect.right,
661      bottom: rect.bottom,
662      left: rect.left,
663      width: rect.right - rect.left,
664      height: rect.bottom - rect.top
665    };
666  }
667  return rect;
668}
669
670
671/**
672 * Returns an empty rect object. An empty rect is returned when an element
673 * is not in the DOM.
674 * @return {Object} The empty rect.
675 */
676function getEmptyRect() {
677  return {
678    top: 0,
679    bottom: 0,
680    left: 0,
681    right: 0,
682    width: 0,
683    height: 0
684  };
685}
686
687/**
688 * Checks to see if a parent element contains a child element (including inside
689 * shadow DOM).
690 * @param {Node} parent The parent element.
691 * @param {Node} child The child element.
692 * @return {boolean} True if the parent node contains the child node.
693 */
694function containsDeep(parent, child) {
695  var node = child;
696  while (node) {
697    if (node == parent) return true;
698
699    node = getParentNode(node);
700  }
701  return false;
702}
703
704
705/**
706 * Gets the parent node of an element or its host element if the parent node
707 * is a shadow root.
708 * @param {Node} node The node whose parent to get.
709 * @return {Node|null} The parent node or null if no parent exists.
710 */
711function getParentNode(node) {
712  var parent = node.parentNode;
713
714  if (parent && parent.nodeType == 11 && parent.host) {
715    // If the parent is a shadow root, return the host element.
716    return parent.host;
717  }
718
719  if (parent && parent.assignedSlot) {
720    // If the parent is distributed in a <slot>, return the parent of a slot.
721    return parent.assignedSlot.parentNode;
722  }
723
724  return parent;
725}
726
727
728// Exposes the constructors globally.
729window.IntersectionObserver = IntersectionObserver;
730window.IntersectionObserverEntry = IntersectionObserverEntry;
731
732}(window, document));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.