// intersectionobserver /** * copyright 2016 google inc. all rights reserved. * * licensed under the w3c software and document notice and license. * * https://www.w3.org/consortium/legal/2015/copyright-software-and-document * */ (function(window, document) { 'use strict'; var supportednatively = 'intersectionobserver' in window && 'intersectionobserverentry' in window && 'intersectionratio' in window.intersectionobserverentry.prototype; if (supportednatively) { return; } /** * an intersectionobserver registry. this registry exists to hold a strong * reference to intersectionobserver instances currently observing a target * element. without this registry, instances without another reference may be * garbage collected. */ var registry = []; /** * creates the global intersectionobserverentry constructor. * https://w3c.github.io/intersectionobserver/#intersection-observer-entry * @param {object} entry a dictionary of instance properties. * @constructor */ function intersectionobserverentry(entry) { this.time = entry.time; this.target = entry.target; this.rootbounds = entry.rootbounds; this.boundingclientrect = entry.boundingclientrect; this.intersectionrect = entry.intersectionrect || getemptyrect(); try { this.isintersecting = !!entry.intersectionrect; } catch (err) { // this means we are using the intersectionobserverentry polyfill which has only defined a getter } // calculates the intersection ratio. var targetrect = this.boundingclientrect; var targetarea = targetrect.width * targetrect.height; var intersectionrect = this.intersectionrect; var intersectionarea = intersectionrect.width * intersectionrect.height; // sets intersection ratio. if (targetarea) { // round the intersection ratio to avoid floating point math issues: // https://github.com/w3c/intersectionobserver/issues/324 this.intersectionratio = number((intersectionarea / targetarea).tofixed(4)); } else { // if area is zero and is intersecting, sets to 1, otherwise to 0 this.intersectionratio = this.isintersecting ? 1 : 0; } } /** * creates the global intersectionobserver constructor. * https://w3c.github.io/intersectionobserver/#intersection-observer-interface * @param {function} callback the function to be invoked after intersection * changes have queued. the function is not invoked if the queue has * been emptied by calling the `takerecords` method. * @param {object=} opt_options optional configuration options. * @constructor */ function intersectionobserver(callback, opt_options) { var options = opt_options || {}; if (typeof callback != 'function') { throw new error('callback must be a function'); } if (options.root && options.root.nodetype != 1) { throw new error('root must be an element'); } // binds and throttles `this._checkforintersections`. this._checkforintersections = throttle( this._checkforintersections.bind(this), this.throttle_timeout); // private properties. this._callback = callback; this._observationtargets = []; this._queuedentries = []; this._rootmarginvalues = this._parserootmargin(options.rootmargin); // public properties. this.thresholds = this._initthresholds(options.threshold); this.root = options.root || null; this.rootmargin = this._rootmarginvalues.map(function(margin) { return margin.value + margin.unit; }).join(' '); } /** * the minimum interval within which the document will be checked for * intersection changes. */ intersectionobserver.prototype.throttle_timeout = 100; /** * the frequency in which the polyfill polls for intersection changes. * this can be updated on a per instance basis and must be set prior to * calling `observe` on the first target. */ intersectionobserver.prototype.poll_interval = null; /** * use a mutation observer on the root element * to detect intersection changes. */ intersectionobserver.prototype.use_mutation_observer = true; /** * starts observing a target element for intersection changes based on * the thresholds values. * @param {element} target the dom element to observe. */ intersectionobserver.prototype.observe = function(target) { var istargetalreadyobserved = this._observationtargets.some(function(item) { return item.element == target; }); if (istargetalreadyobserved) { return; } if (!(target && target.nodetype == 1)) { throw new error('target must be an element'); } this._registerinstance(); this._observationtargets.push({element: target, entry: null}); this._monitorintersections(); this._checkforintersections(); }; /** * stops observing a target element for intersection changes. * @param {element} target the dom element to observe. */ intersectionobserver.prototype.unobserve = function(target) { this._observationtargets = this._observationtargets.filter(function(item) { return item.element != target; }); if (!this._observationtargets.length) { this._unmonitorintersections(); this._unregisterinstance(); } }; /** * stops observing all target elements for intersection changes. */ intersectionobserver.prototype.disconnect = function() { this._observationtargets = []; this._unmonitorintersections(); this._unregisterinstance(); }; /** * returns any queue entries that have not yet been reported to the * callback and clears the queue. this can be used in conjunction with the * callback to obtain the absolute most up-to-date intersection information. * @return {array} the currently queued entries. */ intersectionobserver.prototype.takerecords = function() { var records = this._queuedentries.slice(); this._queuedentries = []; return records; }; /** * accepts the threshold value from the user configuration object and * returns a sorted array of unique threshold values. if a value is not * between 0 and 1 and error is thrown. * @private * @param {array|number=} opt_threshold an optional threshold value or * a list of threshold values, defaulting to [0]. * @return {array} a sorted list of unique and valid threshold values. */ intersectionobserver.prototype._initthresholds = function(opt_threshold) { var threshold = opt_threshold || [0]; if (!array.isarray(threshold)) threshold = [threshold]; return threshold.sort().filter(function(t, i, a) { if (typeof t != 'number' || isnan(t) || t < 0 || t > 1) { throw new error('threshold must be a number between 0 and 1 inclusively'); } return t !== a[i - 1]; }); }; /** * accepts the rootmargin value from the user configuration object * and returns an array of the four margin values as an object containing * the value and unit properties. if any of the values are not properly * formatted or use a unit other than px or %, and error is thrown. * @private * @param {string=} opt_rootmargin an optional rootmargin value, * defaulting to '0px'. * @return {array} an array of margin objects with the keys * value and unit. */ intersectionobserver.prototype._parserootmargin = function(opt_rootmargin) { var marginstring = opt_rootmargin || '0px'; var margins = marginstring.split(/\s+/).map(function(margin) { var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin); if (!parts) { throw new error('rootmargin must be specified in pixels or percent'); } return {value: parsefloat(parts[1]), unit: parts[2]}; }); // handles shorthand. margins[1] = margins[1] || margins[0]; margins[2] = margins[2] || margins[0]; margins[3] = margins[3] || margins[1]; return margins; }; /** * starts polling for intersection changes if the polling is not already * happening, and if the page's visibility state is visible. * @private */ intersectionobserver.prototype._monitorintersections = function() { if (!this._monitoringintersections) { this._monitoringintersections = true; // if a poll interval is set, use polling instead of listening to // resize and scroll events or dom mutations. if (this.poll_interval) { this._monitoringinterval = setinterval( this._checkforintersections, this.poll_interval); } else { addevent(window, 'resize', this._checkforintersections, true); addevent(document, 'scroll', this._checkforintersections, true); if (this.use_mutation_observer && 'mutationobserver' in window) { this._domobserver = new mutationobserver(this._checkforintersections); this._domobserver.observe(document, { attributes: true, childlist: true, characterdata: true, subtree: true }); } } } }; /** * stops polling for intersection changes. * @private */ intersectionobserver.prototype._unmonitorintersections = function() { if (this._monitoringintersections) { this._monitoringintersections = false; clearinterval(this._monitoringinterval); this._monitoringinterval = null; removeevent(window, 'resize', this._checkforintersections, true); removeevent(document, 'scroll', this._checkforintersections, true); if (this._domobserver) { this._domobserver.disconnect(); this._domobserver = null; } } }; /** * scans each observation target for intersection changes and adds them * to the internal entries queue. if new entries are found, it * schedules the callback to be invoked. * @private */ intersectionobserver.prototype._checkforintersections = function() { var rootisindom = this._rootisindom(); var rootrect = rootisindom ? this._getrootrect() : getemptyrect(); this._observationtargets.foreach(function(item) { var target = item.element; var targetrect = getboundingclientrect(target); var rootcontainstarget = this._rootcontainstarget(target); var oldentry = item.entry; var intersectionrect = rootisindom && rootcontainstarget && this._computetargetandrootintersection(target, rootrect); var newentry = item.entry = new intersectionobserverentry({ time: now(), target: target, boundingclientrect: targetrect, rootbounds: rootrect, intersectionrect: intersectionrect }); if (!oldentry) { this._queuedentries.push(newentry); } else if (rootisindom && rootcontainstarget) { // if the new entry intersection ratio has crossed any of the // thresholds, add a new entry. if (this._hascrossedthreshold(oldentry, newentry)) { this._queuedentries.push(newentry); } } else { // if the root is not in the dom or target is not contained within // root but the previous entry for this target had an intersection, // add a new record indicating removal. if (oldentry && oldentry.isintersecting) { this._queuedentries.push(newentry); } } }, this); if (this._queuedentries.length) { this._callback(this.takerecords(), this); } }; /** * accepts a target and root rect computes the intersection between then * following the algorithm in the spec. * todo(philipwalton): at this time clip-path is not considered. * https://w3c.github.io/intersectionobserver/#calculate-intersection-rect-algo * @param {element} target the target dom element * @param {object} rootrect the bounding rect of the root after being * expanded by the rootmargin value. * @return {?object} the final intersection rect object or undefined if no * intersection is found. * @private */ intersectionobserver.prototype._computetargetandrootintersection = function(target, rootrect) { // if the element isn't displayed, an intersection can't happen. if (window.getcomputedstyle(target).display == 'none') return; var targetrect = getboundingclientrect(target); var intersectionrect = targetrect; var parent = getparentnode(target); var atroot = false; while (!atroot) { var parentrect = null; var parentcomputedstyle = parent.nodetype == 1 ? window.getcomputedstyle(parent) : {}; // if the parent isn't displayed, an intersection can't happen. if (parentcomputedstyle.display == 'none') return; if (parent == this.root || parent == document) { atroot = true; parentrect = rootrect; } else { // if the element has a non-visible overflow, and it's not the // or element, update the intersection rect. // note: and cannot be clipped to a rect that's not also // the document rect, so no need to compute a new intersection. if (parent != document.body && parent != document.documentelement && parentcomputedstyle.overflow != 'visible') { parentrect = getboundingclientrect(parent); } } // if either of the above conditionals set a new parentrect, // calculate new intersection data. if (parentrect) { intersectionrect = computerectintersection(parentrect, intersectionrect); if (!intersectionrect) break; } parent = getparentnode(parent); } return intersectionrect; }; /** * returns the root rect after being expanded by the rootmargin value. * @return {object} the expanded root rect. * @private */ intersectionobserver.prototype._getrootrect = function() { var rootrect; if (this.root) { rootrect = getboundingclientrect(this.root); } else { // use / instead of window since scroll bars affect size. var html = document.documentelement; var body = document.body; rootrect = { top: 0, left: 0, right: html.clientwidth || body.clientwidth, width: html.clientwidth || body.clientwidth, bottom: html.clientheight || body.clientheight, height: html.clientheight || body.clientheight }; } return this._expandrectbyrootmargin(rootrect); }; /** * accepts a rect and expands it by the rootmargin value. * @param {object} rect the rect object to expand. * @return {object} the expanded rect. * @private */ intersectionobserver.prototype._expandrectbyrootmargin = function(rect) { var margins = this._rootmarginvalues.map(function(margin, i) { return margin.unit == 'px' ? margin.value : margin.value * (i % 2 ? rect.width : rect.height) / 100; }); var newrect = { top: rect.top - margins[0], right: rect.right + margins[1], bottom: rect.bottom + margins[2], left: rect.left - margins[3] }; newrect.width = newrect.right - newrect.left; newrect.height = newrect.bottom - newrect.top; return newrect; }; /** * accepts an old and new entry and returns true if at least one of the * threshold values has been crossed. * @param {?intersectionobserverentry} oldentry the previous entry for a * particular target element or null if no previous entry exists. * @param {intersectionobserverentry} newentry the current entry for a * particular target element. * @return {boolean} returns true if a any threshold has been crossed. * @private */ intersectionobserver.prototype._hascrossedthreshold = function(oldentry, newentry) { // to make comparing easier, an entry that has a ratio of 0 // but does not actually intersect is given a value of -1 var oldratio = oldentry && oldentry.isintersecting ? oldentry.intersectionratio || 0 : -1; var newratio = newentry.isintersecting ? newentry.intersectionratio || 0 : -1; // ignore unchanged ratios if (oldratio === newratio) return; for (var i = 0; i < this.thresholds.length; i++) { var threshold = this.thresholds[i]; // return true if an entry matches a threshold or if the new ratio // and the old ratio are on the opposite sides of a threshold. if (threshold == oldratio || threshold == newratio || threshold < oldratio !== threshold < newratio) { return true; } } }; /** * returns whether or not the root element is an element and is in the dom. * @return {boolean} true if the root element is an element and is in the dom. * @private */ intersectionobserver.prototype._rootisindom = function() { return !this.root || containsdeep(document, this.root); }; /** * returns whether or not the target element is a child of root. * @param {element} target the target element to check. * @return {boolean} true if the target element is a child of root. * @private */ intersectionobserver.prototype._rootcontainstarget = function(target) { return containsdeep(this.root || document, target); }; /** * adds the instance to the global intersectionobserver registry if it isn't * already present. * @private */ intersectionobserver.prototype._registerinstance = function() { if (registry.indexof(this) < 0) { registry.push(this); } }; /** * removes the instance from the global intersectionobserver registry. * @private */ intersectionobserver.prototype._unregisterinstance = function() { var index = registry.indexof(this); if (index != -1) registry.splice(index, 1); }; /** * returns the result of the performance.now() method or null in browsers * that don't support the api. * @return {number} the elapsed time since the page was requested. */ function now() { return window.performance && performance.now && performance.now(); } /** * throttles a function and delays its execution, so it's only called at most * once within a given time period. * @param {function} fn the function to throttle. * @param {number} timeout the amount of time that must pass before the * function can be called again. * @return {function} the throttled function. */ function throttle(fn, timeout) { var timer = null; return function () { if (!timer) { timer = settimeout(function() { fn(); timer = null; }, timeout); } }; } /** * adds an event handler to a dom node ensuring cross-browser compatibility. * @param {node} node the dom node to add the event handler to. * @param {string} event the event name. * @param {function} fn the event handler to add. * @param {boolean} opt_usecapture optionally adds the even to the capture * phase. note: this only works in modern browsers. */ function addevent(node, event, fn, opt_usecapture) { if (typeof node.addeventlistener == 'function') { node.addeventlistener(event, fn, opt_usecapture || false); } else if (typeof node.attachevent == 'function') { node.attachevent('on' + event, fn); } } /** * removes a previously added event handler from a dom node. * @param {node} node the dom node to remove the event handler from. * @param {string} event the event name. * @param {function} fn the event handler to remove. * @param {boolean} opt_usecapture if the event handler was added with this * flag set to true, it should be set to true here in order to remove it. */ function removeevent(node, event, fn, opt_usecapture) { if (typeof node.removeeventlistener == 'function') { node.removeeventlistener(event, fn, opt_usecapture || false); } else if (typeof node.detatchevent == 'function') { node.detatchevent('on' + event, fn); } } /** * returns the intersection between two rect objects. * @param {object} rect1 the first rect. * @param {object} rect2 the second rect. * @return {?object} the intersection rect or undefined if no intersection * is found. */ function computerectintersection(rect1, rect2) { var top = math.max(rect1.top, rect2.top); var bottom = math.min(rect1.bottom, rect2.bottom); var left = math.max(rect1.left, rect2.left); var right = math.min(rect1.right, rect2.right); var width = right - left; var height = bottom - top; return (width >= 0 && height >= 0) && { top: top, bottom: bottom, left: left, right: right, width: width, height: height }; } /** * shims the native getboundingclientrect for compatibility with older ie. * @param {element} el the element whose bounding rect to get. * @return {object} the (possibly shimmed) rect of the element. */ function getboundingclientrect(el) { var rect; try { rect = el.getboundingclientrect(); } catch (err) { // ignore windows 7 ie11 "unspecified error" // https://github.com/w3c/intersectionobserver/pull/205 } if (!rect) return getemptyrect(); // older ie if (!(rect.width && rect.height)) { rect = { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.right - rect.left, height: rect.bottom - rect.top }; } return rect; } /** * returns an empty rect object. an empty rect is returned when an element * is not in the dom. * @return {object} the empty rect. */ function getemptyrect() { return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 }; } /** * checks to see if a parent element contains a child element (including inside * shadow dom). * @param {node} parent the parent element. * @param {node} child the child element. * @return {boolean} true if the parent node contains the child node. */ function containsdeep(parent, child) { var node = child; while (node) { if (node == parent) return true; node = getparentnode(node); } return false; } /** * gets the parent node of an element or its host element if the parent node * is a shadow root. * @param {node} node the node whose parent to get. * @return {node|null} the parent node or null if no parent exists. */ function getparentnode(node) { var parent = node.parentnode; if (parent && parent.nodetype == 11 && parent.host) { // if the parent is a shadow root, return the host element. return parent.host; } if (parent && parent.assignedslot) { // if the parent is distributed in a , return the parent of a slot. return parent.assignedslot.parentnode; } return parent; } // exposes the constructors globally. window.intersectionobserver = intersectionobserver; window.intersectionobserverentry = intersectionobserverentry; }(window, document));