2015-08-30 21:29:19 +02:00
|
|
|
var React = require('react');
|
|
|
|
|
2015-09-02 14:26:23 +02:00
|
|
|
var _listeners = [];
|
|
|
|
|
2015-08-30 21:29:19 +02:00
|
|
|
module.exports = {
|
|
|
|
|
|
|
|
isInViewport: function() {
|
|
|
|
|
|
|
|
var el = React.findDOMNode(this);
|
|
|
|
|
|
|
|
if(!el) return false;
|
|
|
|
|
|
|
|
var rect = el.getBoundingClientRect();
|
|
|
|
|
2015-09-02 14:26:23 +02:00
|
|
|
var viewportHeight = global.window.innerHeight || global.document.documentElement.clientHeight;
|
|
|
|
var viewportWidth = global.window.innerWidth || global.document.documentElement.clientWidth;
|
|
|
|
|
2015-08-30 21:29:19 +02:00
|
|
|
return (
|
2015-09-02 14:26:23 +02:00
|
|
|
rect.bottom >= 0 &&
|
|
|
|
rect.right >= 0 &&
|
|
|
|
rect.top <= viewportHeight &&
|
|
|
|
rect.left <= viewportWidth
|
2015-08-30 21:29:19 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
componentDidMount: function() {
|
|
|
|
|
2015-09-02 14:26:23 +02:00
|
|
|
if(typeof this.onInViewport === 'function') {
|
|
|
|
|
|
|
|
_listeners.push(this);
|
|
|
|
|
2015-08-30 21:29:19 +02:00
|
|
|
if( this.isInViewport() ) {
|
|
|
|
this.onInViewport();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-09-02 14:26:23 +02:00
|
|
|
},
|
2015-08-30 21:29:19 +02:00
|
|
|
|
2015-09-02 14:26:23 +02:00
|
|
|
componentWillUnmount: function() {
|
|
|
|
var index = _listeners.indexOf(this);
|
|
|
|
if(index !== -1) return _listeners.splice(index, 1);
|
2015-08-30 21:29:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
2015-09-02 14:26:23 +02:00
|
|
|
|
2015-09-11 16:25:45 +02:00
|
|
|
var computeComponentsVisibilityDebounced = debounce(computeComponentsVisibility, 100);
|
2015-09-02 14:26:23 +02:00
|
|
|
|
|
|
|
// Start listening for changes
|
|
|
|
window.document.addEventListener('scroll', computeComponentsVisibilityDebounced, true);
|
|
|
|
window.addEventListener('resize', computeComponentsVisibilityDebounced);
|
|
|
|
|
|
|
|
function computeComponentsVisibility() {
|
|
|
|
_listeners.forEach(function(listener) {
|
|
|
|
if( listener.isInViewport() ) {
|
|
|
|
listener.onInViewport();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2015-08-30 21:29:19 +02:00
|
|
|
function debounce(func, wait, immediate) {
|
|
|
|
var timeout;
|
|
|
|
return function() {
|
|
|
|
var context = this, args = arguments;
|
|
|
|
var later = function() {
|
|
|
|
timeout = null;
|
|
|
|
if (!immediate) func.apply(context, args);
|
|
|
|
};
|
|
|
|
var callNow = immediate && !timeout;
|
|
|
|
clearTimeout(timeout);
|
|
|
|
timeout = setTimeout(later, wait);
|
|
|
|
if (callNow) func.apply(context, args);
|
|
|
|
};
|
|
|
|
}
|