all files / src/ index.js

94.08% Statements 159/169
76.86% Branches 93/121
100% Functions 19/19
95.83% Lines 138/144
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315                                        25×   25×                                                               37×   37×   37× 37×     37×   37×   37×                 43× 43×       43× 43×   43×   43×     25× 18×     18× 18×   18× 17×                 18× 18×                 25×   25×   25×   25×         25× 25×       25×           25×           25× 25× 24×         25×     25×         25×     22× 10× 10× 10×     10× 10×     10×         25× 25×                 25×           25× 25× 23×     25× 12× 12×           48×                                                  
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.forceCheck = exports.lazyload = undefined;
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Eif (protoProps) defineProperties(Constructor.prototype, protoProps); Iif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _react = require('react');
 
var _react2 = _interopRequireDefault(_react);
 
var _reactDom = require('react-dom');
 
var _reactDom2 = _interopRequireDefault(_reactDom);
 
var _event = require('./utils/event');
 
var _scrollParent = require('./utils/scrollParent');
 
var _scrollParent2 = _interopRequireDefault(_scrollParent);
 
var _debounce = require('./utils/debounce');
 
var _debounce2 = _interopRequireDefault(_debounce);
 
var _throttle = require('./utils/throttle');
 
var _throttle2 = _interopRequireDefault(_throttle);
 
var _decorator = require('./decorator');
 
var _decorator2 = _interopRequireDefault(_decorator);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
function _possibleConstructorReturn(self, call) { Iif (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
 
function _inherits(subClass, superClass) { Iif (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); Eif (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * react-lazyload
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
 
 
var LISTEN_FLAG = 'data-lazyload-listened';
var listeners = [];
var pending = [];
 
/**
 * Check if `component` is visible in overflow container `parent`
 * @param  {node} component React component
 * @param  {node} parent    component's scroll parent
 * @return {bool}
 */
var checkOverflowVisible = function checkOverflowVisible(component, parent) {
  var node = _reactDom2.default.findDOMNode(component);
 
  var _parent$getBoundingCl = parent.getBoundingClientRect();
 
  var parentTop = _parent$getBoundingCl.top;
  var parentHeight = _parent$getBoundingCl.height;
 
  var windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
 
  // calculate top and height of the intersection of the element's scrollParent and viewport
  var intersectionTop = Math.max(parentTop, 0); // intersection's top relative to viewport
  var intersectionHeight = Math.min(windowInnerHeight, parentTop + parentHeight) - intersectionTop; // height
 
  // check whether the element is visible in the intersection
 
  var _node$getBoundingClie = node.getBoundingClientRect();
 
  var top = _node$getBoundingClie.top;
  var height = _node$getBoundingClie.height;
 
  var offsetTop = top - intersectionTop; // element's top relative to intersection
 
  var offsets = Array.isArray(component.props.offset) ? component.props.offset : [component.props.offset, component.props.offset]; // Be compatible with previous API
 
  return offsetTop - offsets[0] <= intersectionHeight && offsetTop + height + offsets[1] >= 0;
};
 
/**
 * Check if `component` is visible in document
 * @param  {node} component React component
 * @return {bool}
 */
var checkNormalVisible = function checkNormalVisible(component) {
  var node = _reactDom2.default.findDOMNode(component);
 
  var _node$getBoundingClie2 = node.getBoundingClientRect();
 
  var top = _node$getBoundingClie2.top;
  var elementHeight = _node$getBoundingClie2.height;
 
 
  var windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
 
  var offsets = Array.isArray(component.props.offset) ? component.props.offset : [component.props.offset, component.props.offset]; // Be compatible with previous API
 
  return top - offsets[0] <= windowInnerHeight && top + elementHeight + offsets[1] >= 0;
};
 
/**
 * Detect if element is visible in viewport, if so, set `visible` state to true.
 * If `once` prop is provided true, remove component as listener after checkVisible
 *
 * @param  {React} component   React component that respond to scroll and resize
 */
var checkVisible = function checkVisible(component) {
  var node = _reactDom2.default.findDOMNode(component);
  Iif (!node) {
    return;
  }
 
  var parent = (0, _scrollParent2.default)(node);
  var isOverflow = parent !== node.ownerDocument && parent !== document && parent !== document.documentElement;
 
  var visible = isOverflow ? checkOverflowVisible(component, parent) : checkNormalVisible(component);
 
  if (visible) {
    // Avoid extra render if previously is visible, yeah I mean `render` call,
    // not actual DOM render
    if (!component.visible) {
      if (component.props.once) {
        pending.push(component);
      }
 
      component.visible = true;
      component.forceUpdate();
    }
  } else if (!(component.props.once && component.visible)) {
    component.visible = false;
  }
};
 
var purgePending = function purgePending() {
  pending.forEach(function (component) {
    var index = listeners.indexOf(component);
    Eif (index !== -1) {
      listeners.splice(index, 1);
    }
  });
 
  pending = [];
};
 
var lazyLoadHandler = function lazyLoadHandler() {
  for (var i = 0; i < listeners.length; ++i) {
    var listener = listeners[i];
    checkVisible(listener);
  }
 
  // Remove `once` component in listeners
  purgePending();
};
 
// Depending on component's props
var delayType = void 0;
var finalLazyLoadHandler = null;
 
var LazyLoad = function (_Component) {
  _inherits(LazyLoad, _Component);
 
  function LazyLoad(props) {
    _classCallCheck(this, LazyLoad);
 
    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(LazyLoad).call(this, props));
 
    _this.visible = false;
 
    return _this;
  }
 
  _createClass(LazyLoad, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      Eif (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {
        Iif (_react2.default.Children.count(this.props.children) > 1) {
          console.warn('[react-lazyload] Only one child is allowed to be passed to `LazyLoad`.');
        }
 
        Iif (this.props.wheel) {
          // eslint-disable-line
          console.warn('[react-lazyload] Props `wheel` is not supported anymore, try set `overflow` for lazy loading in overflow containers.');
        }
 
        // Warn the user if placeholder and height is not specified and the rendered height is 0
        if (!this.props.placeholder && this.props.height === undefined && _reactDom2.default.findDOMNode(this).offsetHeight === 0) {
          console.warn('[react-lazyload] Please add `height` props to <LazyLoad> for better performance.');
        }
      }
 
      // It's unlikely to change delay type on the fly, this is mainly
      // designed for tests
      var needResetFinalLazyLoadHandler = false;
      if (this.props.debounce !== undefined && delayType === 'throttle') {
        console.warn('[react-lazyload] Previous delay function is `throttle`, now switching to `debounce`, try setting them unanimously');
        needResetFinalLazyLoadHandler = true;
      } else Iif (delayType === 'debounce' && this.props.debounce === undefined) {
        console.warn('[react-lazyload] Previous delay function is `debounce`, now switching to `throttle`, try setting them unanimously');
        needResetFinalLazyLoadHandler = true;
      }
 
      if (needResetFinalLazyLoadHandler) {
        (0, _event.off)(window, 'scroll', finalLazyLoadHandler);
        (0, _event.off)(window, 'resize', finalLazyLoadHandler);
        finalLazyLoadHandler = null;
      }
 
      if (!finalLazyLoadHandler) {
        if (this.props.debounce !== undefined) {
          finalLazyLoadHandler = (0, _debounce2.default)(lazyLoadHandler, typeof this.props.debounce === 'number' ? this.props.debounce : 300);
          delayType = 'debounce';
        } else {
          finalLazyLoadHandler = (0, _throttle2.default)(lazyLoadHandler, typeof this.props.throttle === 'number' ? this.props.throttle : 300);
          delayType = 'throttle';
        }
      }
 
      if (this.props.overflow) {
        var parent = (0, _scrollParent2.default)(_reactDom2.default.findDOMNode(this));
        Eif (parent) {
          var listenerCount = 1 + +parent.getAttribute(LISTEN_FLAG);
          if (listenerCount === 1) {
            parent.addEventListener('scroll', finalLazyLoadHandler);
          }
          parent.setAttribute(LISTEN_FLAG, listenerCount);
        }
      } else if (listeners.length === 0 || needResetFinalLazyLoadHandler) {
        var _props = this.props;
        var scroll = _props.scroll;
        var resize = _props.resize;
 
 
        Eif (scroll) {
          (0, _event.on)(window, 'scroll', finalLazyLoadHandler);
        }
 
        Iif (resize) {
          (0, _event.on)(window, 'resize', finalLazyLoadHandler);
        }
      }
 
      listeners.push(this);
      checkVisible(this);
    }
  }, {
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate() {
      return this.visible;
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      if (this.props.overflow) {
        var parent = (0, _scrollParent2.default)(_reactDom2.default.findDOMNode(this));
        Eif (parent) {
          var listenerCount = +parent.getAttribute(LISTEN_FLAG) - 1;
          if (listenerCount === 0) {
            parent.removeEventListener('scroll', finalLazyLoadHandler);
            parent.removeAttribute(LISTEN_FLAG);
          } else {
            parent.setAttribute(LISTEN_FLAG, listenerCount);
          }
        }
      }
 
      var index = listeners.indexOf(this);
      if (index !== -1) {
        listeners.splice(index, 1);
      }
 
      if (listeners.length === 0) {
        (0, _event.off)(window, 'resize', finalLazyLoadHandler);
        (0, _event.off)(window, 'scroll', finalLazyLoadHandler);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return this.visible ? this.props.children : this.props.placeholder ? this.props.placeholder : _react2.default.createElement('div', { style: { height: this.props.height }, className: 'lazyload-placeholder' });
    }
  }]);
 
  return LazyLoad;
}(_react.Component);
 
LazyLoad.propTypes = {
  once: _react.PropTypes.bool,
  height: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),
  offset: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.arrayOf(_react.PropTypes.number)]),
  overflow: _react.PropTypes.bool,
  resize: _react.PropTypes.bool,
  scroll: _react.PropTypes.bool,
  children: _react.PropTypes.node,
  throttle: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.bool]),
  debounce: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.bool]),
  placeholder: _react.PropTypes.node
};
 
LazyLoad.defaultProps = {
  once: false,
  offset: 0,
  overflow: false,
  resize: false,
  scroll: true
};
 
var lazyload = exports.lazyload = _decorator2.default;
exports.default = LazyLoad;
exports.forceCheck = lazyLoadHandler;