import { isServer } from "../index";

function isWindow(val) {
  return val === window;
}

var overflowScrollReg = /scroll|auto/i;
export default {
  // get nearest scroll element
  getScrollEventTarget: function getScrollEventTarget(element, root) {
    if (root === void 0) {
      root = window;
    }

    var node = element;

    while (node && node.tagName !== "HTML" && node.nodeType === 1 && node !== root) {
      var _window$getComputedSt = window.getComputedStyle(node),
          overflowY = _window$getComputedSt.overflowY;

      if (overflowScrollReg.test(overflowY)) {
        if (node.tagName !== "BODY") {
          return node;
        } // see: https://github.com/youzan/vant/issues/3823


        var _window$getComputedSt2 = window.getComputedStyle(node.parentNode),
            htmlOverflowY = _window$getComputedSt2.overflowY;

        if (overflowScrollReg.test(htmlOverflowY)) {
          return node;
        }
      }

      node = node.parentNode;
    }

    return root;
  },
  getScrollTop: function getScrollTop(element) {
    var top = "scrollTop" in element ? element.scrollTop : element.pageYOffset; // iOS scroll bounce cause minus scrollTop

    return Math.max(top, 0);
  },
  setScrollTop: function setScrollTop(element, value) {
    "scrollTop" in element ? element.scrollTop = value : element.scrollTo(element.scrollX, value);
  },
  // get distance from element top to page top
  getElementTop: function getElementTop(element) {
    return (element === window ? 0 : element.getBoundingClientRect().top) + this.getScrollTop(window);
  },
  getVisibleHeight: function getVisibleHeight(element) {
    return element === window ? element.innerHeight : element.getBoundingClientRect().height;
  },
  getVisibleTop: function getVisibleTop(element) {
    if (isWindow(element)) {
      return 0;
    }

    return element.getBoundingClientRect().top;
  },
  setRootScrollTop: function setRootScrollTop(value) {
    this.setScrollTop(window, value);
    this.setScrollTop(document.body, value);
  },
  getRootScrollTop: function getRootScrollTop() {
    return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  },
  getComputedStyle: !isServer && document.defaultView.getComputedStyle.bind(document.defaultView)
};