import { getScrollEventTarget, getScrollTop, getVisibleHeight, getElementTop } from "../../es5/utils/scroll";
import throttle from 'lodash/throttle';
var DISTANCE = 300;
/**
 * handle the scroll event
 */

function handleScrollEvent(el, binding) {
  var scrollEventTarget = el._onInfiniteScroll.target;

  if (el._onInfiniteScroll.disabled) {
    return;
  }

  var targetScrollTop = getScrollTop(scrollEventTarget);
  var targetBottom = targetScrollTop + getVisibleHeight(scrollEventTarget);
  var targetVisibleHeight = getVisibleHeight(scrollEventTarget); // return when the targetElement has no height (treat as hidden)

  if (!targetVisibleHeight) {
    return;
  }

  var needLoadMore = false;

  if (scrollEventTarget === el) {
    needLoadMore = scrollEventTarget.scrollHeight - targetBottom < el._onInfiniteScroll.distance;
  } else {
    var elementBottom = getElementTop(el) - getElementTop(scrollEventTarget) + getVisibleHeight(el);
    needLoadMore = elementBottom - targetVisibleHeight < el._onInfiniteScroll.distance;
  }

  if (needLoadMore && binding.value) {
    binding.value();
  }
}

var infiniteScroll = {
  inserted: function inserted(el, binding, vnode) {
    vnode.context.$nextTick(function () {
      var target = getScrollEventTarget(el);
      var listener = throttle(handleScrollEvent.bind(null, el, binding), 200);
      var disabledExpr = el.getAttribute('infinite-scroll-disabled');
      var disabled = false;

      if (disabledExpr) {
        vnode.context.$watch(disabledExpr, function (value) {
          el._onInfiniteScroll.disabled = value;
          listener();
        });
        disabled = Boolean(disabledExpr);
      }

      var distance = Number(el.getAttribute('infinite-scroll-distance')) || DISTANCE;
      target.addEventListener('scroll', listener, true);
      var immediateCheckExpr = el.getAttribute('infinite-scroll-immediate-check');
      var immediateCheck = immediateCheckExpr ? Boolean(vnode.context[immediateCheckExpr]) : true;

      if (immediateCheck && !disabled) {
        binding.value();
      }

      el._onInfiniteScroll = {
        listener: listener,
        target: target,
        disabled: disabled,
        distance: distance
      };
    });
  },
  unbind: function unbind(el) {
    /* istanbul ignore next */
    if (!el._onInfiniteScroll) {
      return;
    }

    if (el._onInfiniteScroll.target) {
      el._onInfiniteScroll.target.removeEventListener('scroll', el._onInfiniteScroll.listener);
    }

    delete el._onInfiniteScroll;
  }
};
export { infiniteScroll };
export default infiniteScroll;
//# sourceMappingURL=infinite-scroll.js.map