"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _propTypes = _interopRequireDefault(require("prop-types"));

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _reactDom = require("react-dom");

var _util = require("../util");

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var NOOP = function NOOP() {};

var MAX_SYNC_UPDATES = 100;

var isEqualSubset = function isEqualSubset(a, b) {
  for (var key in b) {
    if (a[key] !== b[key]) {
      return false;
    }
  }

  return true;
};
/** VirtualList */


var VirtualList =
/*#__PURE__*/
function (_Component) {
  _inherits(VirtualList, _Component);

  function VirtualList(props) {
    var _this;

    _classCallCheck(this, VirtualList);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(VirtualList).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "scrollTo", function (index) {
      _this.setScroll(_this.getSpaceBefore(index));
    });

    var jumpIndex = props.jumpIndex;

    var _this$constrain = _this.constrain(jumpIndex, 0, props),
        from = _this$constrain.from,
        size = _this$constrain.size;

    _this.state = {
      from: from,
      size: size
    };
    _this.cache = {};
    _this.cachedScroll = null;
    _this.unstable = false;
    _this.updateCounter = 0;
    return _this;
  }

  _createClass(VirtualList, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var jumpIndex = this.props.jumpIndex;
      this.updateFrameAndClearCache = this.updateFrameAndClearCache.bind(this);

      _util.events.on(window, 'resize', this.updateFrameAndClearCache);

      this.updateFrame(this.scrollTo.bind(this, jumpIndex));
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(next) {
      var _this$state = this.state,
          from = _this$state.from,
          size = _this$state.size;
      var oldIndex = this.props.jumpIndex;
      var newIndex = next.jumpIndex;

      if (oldIndex !== newIndex) {
        this.updateFrame(this.scrollTo.bind(this, newIndex));
      }

      this.maybeSetState(this.constrain(from, size, next), NOOP);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this2 = this;

      // If the list has reached an unstable state, prevent an infinite loop.
      if (this.unstable) {
        return;
      }

      if (++this.updateCounter > MAX_SYNC_UPDATES) {
        this.unstable = true;
      }

      if (!this.updateCounterTimeoutId) {
        this.updateCounterTimeoutId = setTimeout(function () {
          _this2.updateCounter = 0;
          delete _this2.updateCounterTimeoutId;
        }, 0);
      }

      this.updateFrame();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      _util.events.off(window, 'resize', this.updateFrameAndClearCache);

      _util.events.off(this.scrollParent, 'scroll', this.updateFrameAndClearCache);

      _util.events.off(this.scrollParent, 'mousewheel', NOOP);
    }
  }, {
    key: "maybeSetState",
    value: function maybeSetState(b, cb) {
      if (isEqualSubset(this.state, b)) {
        return cb();
      }

      this.setState(b, cb);
    }
  }, {
    key: "getOffset",
    value: function getOffset(el) {
      var offset = el.clientLeft || 0;

      do {
        offset += el.offsetTop || 0;
        el = el.offsetParent;
      } while (el);

      return offset;
    }
  }, {
    key: "getEl",
    value: function getEl() {
      return this.el || this.items || {};
    }
  }, {
    key: "getScrollParent",
    value: function getScrollParent() {
      var el = this.getEl();
      el = el.parentElement;

      switch (window.getComputedStyle(el).overflowY) {
        case 'auto':
        case 'scroll':
        case 'overlay':
        case 'visible':
          return el;
      }

      return window;
    }
  }, {
    key: "getScroll",
    value: function getScroll() {
      // Cache scroll position as this causes a forced synchronous layout.
      // if (typeof this.cachedScroll === 'number') {
      //     return this.cachedScroll;
      // }
      var scrollParent = this.scrollParent;
      var scrollKey = 'scrollTop';
      var actual = scrollParent === window ? // Firefox always returns document.body[scrollKey] as 0 and Chrome/Safari
      // always return document.documentElement[scrollKey] as 0, so take
      // whichever has a value.
      document.body[scrollKey] || document.documentElement[scrollKey] : scrollParent[scrollKey];
      var max = this.getScrollSize() - this.getViewportSize();
      var scroll = Math.max(0, Math.min(actual, max));
      var el = this.getEl();
      this.cachedScroll = this.getOffset(scrollParent) + scroll - this.getOffset(el);
      return this.cachedScroll;
    }
  }, {
    key: "setScroll",
    value: function setScroll(offset) {
      var scrollParent = this.scrollParent;
      offset += this.getOffset(this.getEl());

      if (scrollParent === window) {
        return window.scrollTo(0, offset);
      }

      offset -= this.getOffset(this.scrollParent);
      scrollParent.scrollTop = offset;
    }
  }, {
    key: "getViewportSize",
    value: function getViewportSize() {
      var scrollParent = this.scrollParent;
      return scrollParent === window ? window.innerHeight : scrollParent.clientHeight;
    }
  }, {
    key: "getScrollSize",
    value: function getScrollSize() {
      var scrollParent = this.scrollParent;
      var _document = document,
          body = _document.body,
          documentElement = _document.documentElement;
      var key = 'scrollHeight';
      return scrollParent === window ? Math.max(body[key], documentElement[key]) : scrollParent[key];
    }
  }, {
    key: "getStartAndEnd",
    value: function getStartAndEnd() {
      var threshold = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.threshold;
      var scroll = this.getScroll();
      var trueScroll = scroll;
      var start = Math.max(0, trueScroll - threshold);
      var end = trueScroll + this.getViewportSize() + threshold;
      return {
        start: start,
        end: end
      };
    } // Called by 'scroll' and 'resize' events, clears scroll position cache.

  }, {
    key: "updateFrameAndClearCache",
    value: function updateFrameAndClearCache(cb) {
      this.cachedScroll = null;
      return this.updateFrame(cb);
    }
  }, {
    key: "updateFrame",
    value: function updateFrame(cb) {
      this.updateScrollParent();

      if (typeof cb !== 'function') {
        cb = NOOP;
      }

      return this.updateVariableFrame(cb);
    }
  }, {
    key: "updateScrollParent",
    value: function updateScrollParent() {
      var prev = this.scrollParent;
      this.scrollParent = this.getScrollParent();

      if (prev === this.scrollParent) {
        return;
      }

      if (prev) {
        _util.events.off(prev, 'scroll', this.updateFrameAndClearCache);

        _util.events.off(prev, 'mousewheel', NOOP);
      }

      _util.events.on(this.scrollParent, 'scroll', this.updateFrameAndClearCache);

      _util.events.on(this.scrollParent, 'mousewheel', NOOP); // You have to attach mousewheel listener to the scrollable element.
      // Just an empty listener. After that onscroll events will be fired synchronously.

    }
  }, {
    key: "updateVariableFrame",
    value: function updateVariableFrame(cb) {
      if (!this.props.itemSizeGetter) {
        this.cacheSizes();
      }

      var _this$getStartAndEnd = this.getStartAndEnd(),
          start = _this$getStartAndEnd.start,
          end = _this$getStartAndEnd.end;

      var _this$props = this.props,
          pageSize = _this$props.pageSize,
          children = _this$props.children;
      var length = children.length;
      var space = 0;
      var from = 0;
      var size = 0;
      var maxFrom = length - 1;

      while (from < maxFrom) {
        var itemSize = this.getSizeOf(from);

        if (itemSize === null || itemSize === undefined || space + itemSize > start) {
          break;
        }

        space += itemSize;
        ++from;
      }

      var maxSize = length - from;

      while (size < maxSize && space < end) {
        var _itemSize = this.getSizeOf(from + size);

        if (_itemSize === null || _itemSize === undefined) {
          size = Math.min(size + pageSize, maxSize);
          break;
        }

        space += _itemSize;
        ++size;
      }

      this.maybeSetState({
        from: from,
        size: size
      }, cb);
    }
  }, {
    key: "getSpaceBefore",
    value: function getSpaceBefore(index) {
      var cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!index) {
        return 0;
      }

      if (cache[index] !== null && cache[index] !== undefined) {
        return cache[index] || 0;
      } // Find the closest space to index there is a cached value for.


      var from = index;

      while (from > 0 && (cache[from] === null || cache[from] === undefined)) {
        from--;
      } // Finally, accumulate sizes of items from - index.


      var space = cache[from] || 0;

      for (var i = from; i < index; ++i) {
        cache[i] = space;
        var itemSize = this.getSizeOf(i);

        if (itemSize === null || itemSize === undefined) {
          break;
        }

        space += itemSize;
      }

      cache[index] = space;
      return cache[index] || 0;
    }
  }, {
    key: "cacheSizes",
    value: function cacheSizes() {
      var cache = this.cache;
      var from = this.state.from;
      var _this$items = this.items,
          children = _this$items.children,
          _this$items$props = _this$items.props,
          props = _this$items$props === void 0 ? {} : _this$items$props;
      var itemEls = children || props.children || [];

      for (var i = 0, l = itemEls.length; i < l; ++i) {
        var ulRef = (0, _reactDom.findDOMNode)(this.items);
        var height = ulRef.children[i].offsetHeight;

        if (height > 0) {
          cache[from + i] = height;
        }
      }
    }
  }, {
    key: "getSizeOf",
    value: function getSizeOf(index) {
      var _this3 = this;

      var cache = this.cache;
      var _this$props2 = this.props,
          itemSizeGetter = _this$props2.itemSizeGetter,
          jumpIndex = _this$props2.jumpIndex; // Try the cache.

      if (index in cache) {
        return cache[index];
      }

      if (itemSizeGetter) {
        return itemSizeGetter(index);
      }

      var height = Object.keys(this.cache).map(function (key) {
        return _this3.cache[key];
      }).pop();

      if (!this.defaultItemHeight && jumpIndex > -1 && height) {
        this.defaultItemHeight = height;
      }

      if (this.defaultItemHeight) {
        return this.defaultItemHeight;
      }
    }
  }, {
    key: "constrain",
    value: function constrain(from, size, _ref) {
      var children = _ref.children,
          minSize = _ref.minSize;
      var length = children && children.length;
      size = Math.max(size, minSize);

      if (size > length) {
        size = length;
      }

      from = from ? Math.max(Math.min(from, length - size), 0) : 0;
      return {
        from: from,
        size: size
      };
    }
  }, {
    key: "renderMenuItems",
    value: function renderMenuItems() {
      var _this4 = this;

      var _this$props3 = this.props,
          children = _this$props3.children,
          itemsRenderer = _this$props3.itemsRenderer;
      var _this$state2 = this.state,
          from = _this$state2.from,
          size = _this$state2.size;
      var items = [];

      for (var i = 0; i < size; ++i) {
        items.push(children[from + i]);
      }

      return itemsRenderer(items, function (c) {
        _this4.items = c;
        return _this4.items;
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _cx,
          _this5 = this;

      var _this$props4 = this.props,
          _this$props4$children = _this$props4.children,
          children = _this$props4$children === void 0 ? [] : _this$props4$children,
          prefix = _this$props4.prefix,
          className = _this$props4.className;
      var length = children.length;
      var from = this.state.from;
      var items = this.renderMenuItems();
      var style = {
        position: 'relative'
      };
      var cache = {};
      var size = this.getSpaceBefore(length, cache);

      if (size) {
        style.height = size;
      }

      var offset = this.getSpaceBefore(from, cache);
      var transform = "translate(0px, ".concat(offset, "px)");
      var listStyle = {
        msTransform: transform,
        WebkitTransform: transform,
        transform: transform
      };
      var cls = (0, _classnames["default"])((_cx = {}, _defineProperty(_cx, "".concat(prefix, "virtual-list-wrapper"), true), _defineProperty(_cx, className, !!className), _cx));
      return _react["default"].createElement("div", {
        className: cls,
        style: style,
        ref: function ref(c) {
          _this5.el = c;
          return _this5.el;
        }
      }, _react["default"].createElement("div", {
        style: listStyle
      }, items));
    }
  }]);

  return VirtualList;
}(_react.Component);

exports["default"] = VirtualList;

_defineProperty(VirtualList, "displayName", 'VirtualList');

_defineProperty(VirtualList, "propTypes", {
  prefix: _propTypes["default"].string,

  /**
   * 渲染的子节点
   */
  children: _propTypes["default"].any,

  /**
   * 最小加载数量
   */
  minSize: _propTypes["default"].number,

  /**
   * 一屏数量
   */
  pageSize: _propTypes["default"].number,

  /**
   * 父渲染函数，默认为 (items, ref) => <ul ref={ref}>{items}</ul>
   */
  itemsRenderer: _propTypes["default"].func,

  /**
   * 缓冲区高度
   */
  threshold: _propTypes["default"].number,

  /**
   * 获取item高度的函数
   */
  itemSizeGetter: _propTypes["default"].func,

  /**
   * 设置跳转位置，需要设置 itemSizeGetter 才能生效, 不设置认为元素等高并取第一个元素高度作为默认高
   */
  jumpIndex: _propTypes["default"].number,
  className: _propTypes["default"].string
});

_defineProperty(VirtualList, "defaultProps", {
  prefix: 'next-',
  itemsRenderer: function itemsRenderer(items, ref) {
    return _react["default"].createElement("ul", {
      ref: ref
    }, items);
  },
  minSize: 1,
  pageSize: 10,
  jumpIndex: 0,
  threshold: 100
});