/** * 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() { 'use strict'; // exit early if we're not running in a browser. if (typeof window !== 'object') { return; } // exit early if all intersectionobserver and intersectionobserverentry // features are natively supported. if ('intersectionobserver' in window && 'intersectionobserverentry' in window && 'intersectionratio' in window.intersectionobserverentry.prototype) { // minimal polyfill for edge 15's lack of `isintersecting` // see: https://github.com/w3c/intersectionobserver/issues/211 if (!('isintersecting' in window.intersectionobserverentry.prototype)) { object.defineproperty(window.intersectionobserverentry.prototype, 'isintersecting', { get: function () { return this.intersectionratio > 0; } }); } return; } /** * returns the embedding frame element, if any. * @param {!document} doc * @return {!element} */ function getframeelement(doc) { try { return doc.defaultview && doc.defaultview.frameelement || null; } catch (e) { // ignore the error. return null; } } /** * a local reference to the root document. */ var document = (function(startdoc) { var doc = startdoc; var frame = getframeelement(doc); while (frame) { doc = frame.ownerdocument; frame = getframeelement(doc); } return doc; })(window.document); /** * 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 = []; /** * the signal updater for cross-origin intersection. when not null, it means * that the polyfill is configured to work in a cross-origin mode. * @type {function(domrect|clientrect, domrect|clientrect)} */ var crossoriginupdater = null; /** * the current cross-origin intersection. only used in the cross-origin mode. * @type {domrect|clientrect} */ var crossoriginrect = null; /** * 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 = ensuredomrect(entry.rootbounds); this.boundingclientrect = ensuredomrect(entry.boundingclientrect); this.intersectionrect = ensuredomrect(entry.intersectionrect || getemptyrect()); this.isintersecting = !!entry.intersectionrect; // 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 && options.root.nodetype != 9 ) { throw new error('root must be a document or 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(' '); /** @private @const {!array} */ this._monitoringdocuments = []; /** @private @const {!array} */ this._monitoringunsubscribes = []; } /** * 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; /** * sets up the polyfill in the cross-origin mode. the result is the * updater function that accepts two arguments: `boundingclientrect` and * `intersectionrect` - just as these fields would be available to the * parent via `intersectionobserverentry`. this function should be called * each time the iframe receives intersection information from the parent * window, e.g. via messaging. * @return {function(domrect|clientrect, domrect|clientrect)} */ intersectionobserver._setupcrossoriginupdater = function() { if (!crossoriginupdater) { /** * @param {domrect|clientrect} boundingclientrect * @param {domrect|clientrect} intersectionrect */ crossoriginupdater = function(boundingclientrect, intersectionrect) { if (!boundingclientrect || !intersectionrect) { crossoriginrect = getemptyrect(); } else { crossoriginrect = convertfromparentrect(boundingclientrect, intersectionrect); } registry.foreach(function(observer) { observer._checkforintersections(); }); }; } return crossoriginupdater; }; /** * resets the cross-origin mode. */ intersectionobserver._resetcrossoriginupdater = function() { crossoriginupdater = null; crossoriginrect = null; }; /** * 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(target.ownerdocument); 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; }); this._unmonitorintersections(target.ownerdocument); if (this._observationtargets.length == 0) { this._unregisterinstance(); } }; /** * stops observing all target elements for intersection changes. */ intersectionobserver.prototype.disconnect = function() { this._observationtargets = []; this._unmonitorallintersections(); 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. * @param {!document} doc * @private */ intersectionobserver.prototype._monitorintersections = function(doc) { var win = doc.defaultview; if (!win) { // already destroyed. return; } if (this._monitoringdocuments.indexof(doc) != -1) { // already monitoring. return; } // private state for monitoring. var callback = this._checkforintersections; var monitoringinterval = null; var domobserver = null; // if a poll interval is set, use polling instead of listening to // resize and scroll events or dom mutations. if (this.poll_interval) { monitoringinterval = win.setinterval(callback, this.poll_interval); } else { addevent(win, 'resize', callback, true); addevent(doc, 'scroll', callback, true); if (this.use_mutation_observer && 'mutationobserver' in win) { domobserver = new win.mutationobserver(callback); domobserver.observe(doc, { attributes: true, childlist: true, characterdata: true, subtree: true }); } } this._monitoringdocuments.push(doc); this._monitoringunsubscribes.push(function() { // get the window object again. when a friendly iframe is destroyed, it // will be null. var win = doc.defaultview; if (win) { if (monitoringinterval) { win.clearinterval(monitoringinterval); } removeevent(win, 'resize', callback, true); } removeevent(doc, 'scroll', callback, true); if (domobserver) { domobserver.disconnect(); } }); // also monitor the parent. var rootdoc = (this.root && (this.root.ownerdocument || this.root)) || document; if (doc != rootdoc) { var frame = getframeelement(doc); if (frame) { this._monitorintersections(frame.ownerdocument); } } }; /** * stops polling for intersection changes. * @param {!document} doc * @private */ intersectionobserver.prototype._unmonitorintersections = function(doc) { var index = this._monitoringdocuments.indexof(doc); if (index == -1) { return; } var rootdoc = (this.root && (this.root.ownerdocument || this.root)) || document; // check if any dependent targets are still remaining. var hasdependenttargets = this._observationtargets.some(function(item) { var itemdoc = item.element.ownerdocument; // target is in this context. if (itemdoc == doc) { return true; } // target is nested in this context. while (itemdoc && itemdoc != rootdoc) { var frame = getframeelement(itemdoc); itemdoc = frame && frame.ownerdocument; if (itemdoc == doc) { return true; } } return false; }); if (hasdependenttargets) { return; } // unsubscribe. var unsubscribe = this._monitoringunsubscribes[index]; this._monitoringdocuments.splice(index, 1); this._monitoringunsubscribes.splice(index, 1); unsubscribe(); // also unmonitor the parent. if (doc != rootdoc) { var frame = getframeelement(doc); if (frame) { this._unmonitorintersections(frame.ownerdocument); } } }; /** * stops polling for intersection changes. * @param {!document} doc * @private */ intersectionobserver.prototype._unmonitorallintersections = function() { var unsubscribes = this._monitoringunsubscribes.slice(0); this._monitoringdocuments.length = 0; this._monitoringunsubscribes.length = 0; for (var i = 0; i < unsubscribes.length; i++) { unsubscribes[i](); } }; /** * 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() { if (!this.root && crossoriginupdater && !crossoriginrect) { // cross origin monitoring, but no initial data available yet. return; } 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, targetrect, rootrect); var rootbounds = null; if (!this._rootcontainstarget(target)) { rootbounds = getemptyrect(); } else if (!crossoriginupdater || this.root) { rootbounds = rootrect; } var newentry = item.entry = new intersectionobserverentry({ time: now(), target: target, boundingclientrect: targetrect, rootbounds: rootbounds, 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} targetrect the bounding rect of the target. * @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, targetrect, rootrect) { // if the element isn't displayed, an intersection can't happen. if (window.getcomputedstyle(target).display == 'none') return; var intersectionrect = targetrect; var parent = getparentnode(target); var atroot = false; while (!atroot && parent) { 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 null; if (parent == this.root || parent.nodetype == /* document */ 9) { atroot = true; if (parent == this.root || parent == document) { if (crossoriginupdater && !this.root) { if (!crossoriginrect || crossoriginrect.width == 0 && crossoriginrect.height == 0) { // a 0-size cross-origin intersection means no-intersection. parent = null; parentrect = null; intersectionrect = null; } else { parentrect = crossoriginrect; } } else { parentrect = rootrect; } } else { // check if there's a frame that can be navigated to. var frame = getparentnode(parent); var framerect = frame && getboundingclientrect(frame); var frameintersect = frame && this._computetargetandrootintersection(frame, framerect, rootrect); if (framerect && frameintersect) { parent = frame; parentrect = convertfromparentrect(framerect, frameintersect); } else { parent = null; intersectionrect = null; } } } 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. var doc = parent.ownerdocument; if (parent != doc.body && parent != doc.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 = parent && getparentnode(parent); } return intersectionrect; }; /** * returns the root rect after being expanded by the rootmargin value. * @return {clientrect} the expanded root rect. * @private */ intersectionobserver.prototype._getrootrect = function() { var rootrect; if (this.root && !isdoc(this.root)) { rootrect = getboundingclientrect(this.root); } else { // use / instead of window since scroll bars affect size. var doc = isdoc(this.root) ? this.root : document; var html = doc.documentelement; var body = doc.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 {domrect|clientrect} rect the rect object to expand. * @return {clientrect} 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) { var rootdoc = (this.root && (this.root.ownerdocument || this.root)) || document; return ( containsdeep(rootdoc, target) && (!this.root || rootdoc == target.ownerdocument) ); }; /** * 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|?clientrect} 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 } || null; } /** * shims the native getboundingclientrect for compatibility with older ie. * @param {element} el the element whose bounding rect to get. * @return {domrect|clientrect} 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 {clientrect} the empty rect. */ function getemptyrect() { return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 }; } /** * ensure that the result has all of the necessary fields of the domrect. * specifically this ensures that `x` and `y` fields are set. * * @param {?domrect|?clientrect} rect * @return {?domrect} */ function ensuredomrect(rect) { // a `domrect` object has `x` and `y` fields. if (!rect || 'x' in rect) { return rect; } // a ie's `clientrect` type does not have `x` and `y`. the same is the case // for internally calculated rect objects. for the purposes of // `intersectionobserver`, it's sufficient to simply mirror `left` and `top` // for these fields. return { top: rect.top, y: rect.top, bottom: rect.bottom, left: rect.left, x: rect.left, right: rect.right, width: rect.width, height: rect.height }; } /** * inverts the intersection and bounding rect from the parent (frame) bcr to * the local bcr space. * @param {domrect|clientrect} parentboundingrect the parent's bound client rect. * @param {domrect|clientrect} parentintersectionrect the parent's own intersection rect. * @return {clientrect} the local root bounding rect for the parent's children. */ function convertfromparentrect(parentboundingrect, parentintersectionrect) { var top = parentintersectionrect.top - parentboundingrect.top; var left = parentintersectionrect.left - parentboundingrect.left; return { top: top, left: left, height: parentintersectionrect.height, width: parentintersectionrect.width, bottom: top + parentintersectionrect.height, right: left + parentintersectionrect.width }; } /** * 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 (node.nodetype == /* document */ 9 && node != document) { // if this node is a document node, look for the embedding frame. return getframeelement(node); } // if the parent has element that is assigned through shadow root slot if (parent && parent.assignedslot) { parent = parent.assignedslot.parentnode } if (parent && parent.nodetype == 11 && parent.host) { // if the parent is a shadow root, return the host element. return parent.host; } return parent; } /** * returns true if `node` is a document. * @param {!node} node * @returns {boolean} */ function isdoc(node) { return node && node.nodetype === 9; } // exposes the constructors globally. window.intersectionobserver = intersectionobserver; window.intersectionobserverentry = intersectionobserverentry; }());