"use strict";exports.__esModule = true;exports.findNearestScrollableParent = findNearestScrollableParent;exports.scrollYCenterIntoNearestScrollable = scrollYCenterIntoNearestScrollable;var _globalObject = require("@skbkontur/global-object");

var _getParentOrShadowHost = require("./getParentOrShadowHost");

function scrollYCenterIntoNearestScrollable(element) {
  if (!(0, _globalObject.isBrowser)(_globalObject.globalObject)) {
    return;
  }

  var parent = findNearestScrollableParent(element);

  if (!parent) {
    return;
  }

  var elementRect = element.getBoundingClientRect();
  var parentRect = parent.getBoundingClientRect();

  var scrollTopPos = elementRect.top - parentRect.top;
  var scrollBottomPos = elementRect.bottom - parentRect.bottom;
  var scrollCenterPos = (scrollTopPos + scrollBottomPos) / 2;

  if (scrollCenterPos !== 0) {
    parent.scrollTo({ top: scrollCenterPos });
  }
}

function findNearestScrollableParent(element) {
  if (!(0, _globalObject.isBrowser)(_globalObject.globalObject)) {
    return;
  }

  var parent = (0, _getParentOrShadowHost.getParentOrShadowHost)(element);

  while (parent) {
    var _globalObject$getComp = _globalObject.globalObject.getComputedStyle(parent),overflow = _globalObject$getComp.overflow;
    var overflowValues = overflow.split(' ');
    var isScrollbale = overflowValues.every(function (val) {return val === 'auto' || val === 'scroll';});

    if (isScrollbale) {
      return parent;
    }

    parent = (0, _getParentOrShadowHost.getParentOrShadowHost)(parent);
  }

  return _globalObject.globalObject.document.documentElement;
}