"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

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

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

var _hoistNonReactStatics = _interopRequireDefault(require("hoist-non-react-statics"));

var _viewport = _interopRequireDefault(require("./__viewport"));

var _popupconstants = require("./__popupconstants.json");

var _resizeObserver = _interopRequireDefault(require("./__resizeObserver"));

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

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

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

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

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

var lastOpenedGroup = [];
var popups = {};

var debounce = function debounce(func, wait) {
  var interval;
  return function (e) {
    clearTimeout(interval);
    interval = setTimeout(func.bind(undefined, e), wait);
  };
};

function isDescendant(parent, child) {
  var node = child.parentNode;

  while (node !== null) {
    if (node === parent) {
      return true;
    }

    node = node.parentNode;
  }

  return false;
}

global.closeGroupPopups = function (groupName) {
  var groupPopups = popups[groupName] || [];
  groupPopups.forEach(function (popup) {
    popup.state.isPopupOpen && popup.setState({
      isPopupOpen: false,
      isPopupReady: false
    });
  });
};

var defaultState = {
  position: "bottomCenter",
  height: "0px",
  positions: {},
  //{bottomCenter: true, bottomLeft: false, ...}
  positionsOffset: {},
  //{bottomCenter: {left: ‘’,top: ‘’ }, .....}
  targetOffset: {},
  //{height: ‘’, width: ‘’,}
  popupOffset: {},
  //{height: ‘’, width: ‘’,}
  isAbsolutePositioningNeeded: true
};
/* eslint-disable react/no-deprecated */

/* eslint-disable react/prop-types */

var Popup = function Popup(Component) {
  var group = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global";
  var needResizeHandling = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

  var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
      _ref$isAbsolutePositi = _ref.isAbsolutePositioningNeeded,
      isAbsolutePopup = _ref$isAbsolutePositi === void 0 ? true : _ref$isAbsolutePositi,
      _ref$isArrow = _ref.isArrow,
      needPopupArrow = _ref$isArrow === void 0 ? false : _ref$isArrow,
      _ref$customOrder = _ref.customOrder,
      customPositionOrder = _ref$customOrder === void 0 ? [] : _ref$customOrder,
      _ref$scrollDebounceTi = _ref.scrollDebounceTime,
      popupScrollDebounceTime = _ref$scrollDebounceTi === void 0 ? 0 : _ref$scrollDebounceTi,
      _ref$closeOnScroll = _ref.closeOnScroll,
      closeOnScrollPopup = _ref$closeOnScroll === void 0 ? false : _ref$closeOnScroll;

  var Popup = /*#__PURE__*/function (_React$Component) {
    _inherits(Popup, _React$Component);

    var _super = _createSuper(Popup);

    function Popup(props) {
      var _this;

      _classCallCheck(this, Popup);

      _this = _super.call(this, props);
      _this.state = {
        isPopupOpen: props.isPopupOpen || false,
        position: "bottomCenter",
        height: "0px",
        isPopupReady: props.isPopupOpen || false,
        positions: {},
        //{bottomCenter: true, bottomLeft: false, ...}
        positionsOffset: {},
        //{bottomCenter: {left: ‘’,top: ‘’ }, .....}
        targetOffset: {},
        //{height: ‘’, width: ‘’,}
        popupOffset: {},
        //{height: ‘’, width: ‘’,}
        isAbsolutePositioningNeeded: true
      };
      _this.togglePopup = _this.togglePopup.bind(_assertThisInitialized(_this));
      _this.documentClickHandler = _this.documentClickHandler.bind(_assertThisInitialized(_this));
      _this.documentClickHandler1 = _this.documentClickHandler1.bind(_assertThisInitialized(_this));
      _this.removeClose = _this.removeClose.bind(_assertThisInitialized(_this));
      _this.documentKeyupHandler = _this.documentKeyupHandler.bind(_assertThisInitialized(_this));
      _this.openPopupOnly = _this.openPopupOnly.bind(_assertThisInitialized(_this));
      _this.closePopupOnly = _this.closePopupOnly.bind(_assertThisInitialized(_this));
      _this.getTargetRef = _this.getTargetRef.bind(_assertThisInitialized(_this));
      _this.getContainerRef = _this.getContainerRef.bind(_assertThisInitialized(_this));
      _this.handlePopupPosition = _this.handlePopupPosition.bind(_assertThisInitialized(_this));
      _this.handleResize = debounce(_this.handleResize.bind(_assertThisInitialized(_this)), 300);
      _this.handlePopupResize = _this.handlePopupResize.bind(_assertThisInitialized(_this));
      _this.getIsAbsolutePopup = _this.getIsAbsolutePopup.bind(_assertThisInitialized(_this));
      _this.getNeedArrow = _this.getNeedArrow.bind(_assertThisInitialized(_this));
      _this.getCustomPositionOrder = _this.getCustomPositionOrder.bind(_assertThisInitialized(_this));
      _this.handleOpenPopupPositionChange = _this.handleOpenPopupPositionChange.bind(_assertThisInitialized(_this));
      _this.getScrollDebounceTime = _this.getScrollDebounceTime.bind(_assertThisInitialized(_this));
      _this.getCloseOnScrollPopup = _this.getCloseOnScrollPopup.bind(_assertThisInitialized(_this));
      _this.handleCloseLastOpenedGroup = _this.handleCloseLastOpenedGroup.bind(_assertThisInitialized(_this));
      _this.handleDocumentMouseDown = _this.handleDocumentMouseDown.bind(_assertThisInitialized(_this));
      _this.handleDocumentFocus = _this.handleDocumentFocus.bind(_assertThisInitialized(_this));
      _this.handleGetNeedPrevent = _this.handleGetNeedPrevent.bind(_assertThisInitialized(_this));
      _this.popupObserver = new _resizeObserver["default"](_this.handlePopupResize); //dropBoxSize

      _this.size = null;
      _this.isAbsolutePopup = isAbsolutePopup;
      _this.needPopupArrow = needPopupArrow;
      _this.customPositionOrder = customPositionOrder;
      _this.scrollDebounceTime = popupScrollDebounceTime;
      _this.closeOnScroll = closeOnScrollPopup;

      var _this$getScrollDeboun = _this.getScrollDebounceTime(_assertThisInitialized(_this)),
          scrollDebounceTime = _this$getScrollDeboun.scrollDebounceTime;

      _this.handleScroll = debounce(_this.handleScroll.bind(_assertThisInitialized(_this)), scrollDebounceTime);
      return _this;
    }

    _createClass(Popup, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        var group = this.getGroup();
        var groupPopups = popups[group] || [];
        groupPopups.push(this);
        popups[group] = groupPopups;

        if (Object.keys(popups).length === 1 && groupPopups.length === 1) {
          document.addEventListener("click", this.documentClickHandler, false);
          document.addEventListener("keyup", this.documentKeyupHandler, false); // document.addEventListener('scroll', this.handleScroll, true);

          window.addEventListener("resize", this.handleResize);
          document.addEventListener("click", this.documentClickHandler1, true);
          document.addEventListener("mousedown", this.handleDocumentMouseDown, true);
          document.addEventListener("focus", this.handleDocumentFocus, true);
        }
      }
    }, {
      key: "componentWillReceiveProps",
      value: function componentWillReceiveProps(nextProps) {
        var isPopupOpen = this.state.isPopupOpen;

        if (typeof nextProps.isPopupOpen !== "undefined" && nextProps.isPopupOpen !== isPopupOpen) {
          this.setState({
            isPopupOpen: nextProps.isPopupOpen,
            isPopupReady: nextProps.isPopupOpen
          });
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps, prevState) {
        var isPopupReady = this.state.isPopupReady;

        var _ref2 = prevState || {},
            _ref2$isPopupReady = _ref2.isPopupReady,
            oldStateOpen = _ref2$isPopupReady === void 0 ? false : _ref2$isPopupReady;

        var dropElement = this.dropElement;
        var propResizeHandling = this.props.needResizeHandling;

        if (oldStateOpen !== isPopupReady) {
          if (isPopupReady && dropElement && (propResizeHandling !== undefined ? propResizeHandling : needResizeHandling)) {
            this.popupObserver.replaceObservationElement(dropElement);
          } else if (!isPopupReady) {
            this.size = null;
            this.popupObserver.disconnect();
          }
        }
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        var _this2 = this;

        var group = this.getGroup();
        popups = Object.keys(popups).reduce(function (res, groupName) {
          if (groupName === group) {
            var groupPopups = popups[group];
            var newGroupPopups = groupPopups.filter(function (popup) {
              return popup !== _this2;
            });
            newGroupPopups.length === 0 && lastOpenedGroup.indexOf(group) >= 0 && lastOpenedGroup.splice(lastOpenedGroup.indexOf(group), 1);
            res[group] = newGroupPopups;
          }

          return res;
        }, popups);
        var noPopups = true;

        for (var i in popups) {
          if (popups[i].length >= 1) {
            noPopups = false;
            break;
          }
        }

        if (this.popupObserver) {
          this.popupObserver.disconnect();
        }

        if (noPopups) {
          document.removeEventListener("click", this.documentClickHandler);
          document.removeEventListener("keyup", this.documentKeyupHandler); // document.removeEventListener('scroll', this.handleScroll);

          window.removeEventListener("resize", this.handleResize);
          document.removeEventListener("click", this.documentClickHandler1, true);
          document.removeEventListener("mousedown", this.handleDocumentMouseDown, true);
          document.removeEventListener("focus", this.handleDocumentFocus, true);
        }
      }
    }, {
      key: "getGroup",
      value: function getGroup() {
        var popupGroup = this.props.popupGroup;
        return popupGroup || group;
      }
    }, {
      key: "getNeedArrow",
      value: function getNeedArrow(popup) {
        var isArrow = popup.props.isArrow;
        var needPopupArrow = popup.needPopupArrow;
        return isArrow !== undefined ? isArrow : needPopupArrow;
      }
    }, {
      key: "getScrollDebounceTime",
      value: function getScrollDebounceTime(popup) {
        var scrollDebounceTime = popup.props.scrollDebounceTime;
        var popupScrollDebounceTime = popup.scrollDebounceTime;
        return scrollDebounceTime !== undefined ? scrollDebounceTime : popupScrollDebounceTime;
      }
    }, {
      key: "getCloseOnScrollPopup",
      value: function getCloseOnScrollPopup(popup) {
        var closeOnScroll = popup.props.closeOnScroll;
        var closeOnScrollPopup = popup.closeOnScroll;
        return closeOnScroll !== undefined ? closeOnScroll : closeOnScrollPopup;
      }
    }, {
      key: "getIsAbsolutePopup",
      value: function getIsAbsolutePopup(popup) {
        var isAbsolutePositioningNeeded = popup.props.isAbsolutePositioningNeeded;
        var isAbsolutePopup = popup.isAbsolutePopup;
        return isAbsolutePositioningNeeded !== undefined ? isAbsolutePositioningNeeded : isAbsolutePopup;
      }
    }, {
      key: "getCustomPositionOrder",
      value: function getCustomPositionOrder(popup) {
        var _popup$props$customOr = popup.props.customOrder,
            customOrder = _popup$props$customOr === void 0 ? [] : _popup$props$customOr;
        var customPositionOrder = popup.customPositionOrder;
        return customOrder.length !== 0 ? customOrder : customPositionOrder;
      }
    }, {
      key: "togglePopup",
      value: function togglePopup(e, defaultPosition) {
        var _this3 = this;

        var group = this.getGroup();
        this.removeClose(e);
        var isPopupOpen = this.state.isPopupOpen;
        var groupPopups = popups[group] || [];
        lastOpenedGroup = !isPopupOpen && lastOpenedGroup.indexOf(group) === -1 ? [group].concat(_toConsumableArray(lastOpenedGroup)) : lastOpenedGroup;
        isPopupOpen && lastOpenedGroup.splice(0, 1);
        groupPopups.forEach(function (popup) {
          if (popup !== _this3 && popup.state.isPopupOpen) {
            popup.setState({
              isPopupOpen: false,
              isPopupReady: false
            });
          }
        });

        if (isPopupOpen) {
          this.setState({
            isPopupOpen: false,
            isPopupReady: false
          });
        } else {
          this.handlePopupPosition(defaultPosition);
        }
      }
    }, {
      key: "openPopupOnly",
      value: function openPopupOnly(e, defaultPosition) {
        var group = this.getGroup();
        this.removeClose(e);
        lastOpenedGroup = lastOpenedGroup.indexOf(group) === -1 ? [group].concat(_toConsumableArray(lastOpenedGroup)) : lastOpenedGroup;
        this.handlePopupPosition(defaultPosition);
      }
    }, {
      key: "closePopupOnly",
      value: function closePopupOnly(e) {
        this.removeClose(e);
        lastOpenedGroup.splice(0, 1);
        var isPopupOpen = this.state.isPopupOpen;

        if (isPopupOpen) {
          this.setState({
            isPopupOpen: false,
            isPopupReady: false
          });
        }
      }
    }, {
      key: "handleCloseLastOpenedGroup",
      value: function handleCloseLastOpenedGroup() {
        var groupPopups = lastOpenedGroup.length ? popups[lastOpenedGroup[0]] || [] : [];
        lastOpenedGroup.splice(0, 1);
        groupPopups.forEach(function (popup) {
          popup.state.isPopupOpen && popup.setState({
            isPopupOpen: false,
            isPopupReady: false
          });
        });
      }
    }, {
      key: "handleDocumentMouseDown",
      value: function handleDocumentMouseDown(e) {
        var needPrevent = this.handleGetNeedPrevent(e);

        if (needPrevent) {
          this.removeClose(e);
        }
      }
    }, {
      key: "handleDocumentFocus",
      value: function handleDocumentFocus(e) {
        var needPrevent = this.handleGetNeedPrevent(e);

        if (needPrevent) {
          this.removeClose(e);
        }
      }
    }, {
      key: "handleGetNeedPrevent",
      value: function handleGetNeedPrevent(e) {
        var needPrevent = false;

        if (lastOpenedGroup.length > 1) {
          var target = e.target;
          var groupPopups = lastOpenedGroup.length ? popups[lastOpenedGroup[0]] : [];
          var openedPopup = null; // eslint-disable-next-line guard-for-in

          for (var i in groupPopups) {
            var isPopupOpen = groupPopups[i].state.isPopupOpen;

            if (isPopupOpen) {
              openedPopup = groupPopups[i];
              break;
            }
          }

          if (openedPopup) {
            var _openedPopup = openedPopup,
                dropElement = _openedPopup.dropElement,
                placeHolderElement = _openedPopup.placeHolderElement;
            var isDropBoxChild = isDescendant(dropElement, target);
            var isTargetChild = isDescendant(placeHolderElement, target); // const massUpdateParent = document.querySelector(
            //   '[data-id=massUpdatePopup]'
            // );
            // const isPopupMassUpdateChild = isDescendant(
            //   massUpdateParent,
            //   dropElement
            // );

            if (!isDropBoxChild && !isTargetChild // && isPopupMassUpdateChild
            ) {
              needPrevent = true;
            }
          }
        }

        return needPrevent;
      }
    }, {
      key: "documentClickHandler1",
      value: function documentClickHandler1(e) {
        var needPrevent = this.handleGetNeedPrevent(e);

        if (needPrevent) {
          this.removeClose(e);
          this.handleCloseLastOpenedGroup();
        }
      }
    }, {
      key: "documentClickHandler",
      value: function documentClickHandler() {
        try {
          Object.keys(popups).forEach(function (groupName) {
            var groupPopups = popups[groupName] || [];
            groupPopups.forEach(function (popup) {
              popup.state.isPopupOpen && (!popup.props.checkBeforeClose || popup.props.checkBeforeClose && popup.props.checkBeforeClose()) && popup.setState({
                isPopupOpen: false,
                isPopupReady: false
              });
            });
          });
          lastOpenedGroup = [];
        } catch (e) {// eslint-disable-next-line no-console
          //console.error('popup component not unmounted properly', e);
        }
      }
    }, {
      key: "documentKeyupHandler",
      value: function documentKeyupHandler(e) {
        try {
          if (e.keyCode === 27) {
            this.handleCloseLastOpenedGroup();
          }
        } catch (e) {// eslint-disable-next-line no-console
          //console.log('error', e);
        }
      }
    }, {
      key: "removeClose",
      value: function removeClose(e) {
        // e && e.preventDefault && e.preventDefault();
        e && e.stopPropagation && e.stopPropagation();
        e && e.nativeEvent && e.nativeEvent.stopImmediatePropagation && e.nativeEvent.stopImmediatePropagation();
      }
    }, {
      key: "handlePopupPosition",
      value: function handlePopupPosition() {
        var _this4 = this;

        var defaultPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "bottomCenter";
        var isResizeHandling = arguments.length > 1 ? arguments[1] : undefined;
        // isResizeHandling --->>> Window resize and dropBox resize
        var direction = this.context.direction;
        var placeHolderElement = this.placeHolderElement,
            dropElement = this.dropElement;
        var needArrow = this.getNeedArrow(this);
        var isAbsolute = this.getIsAbsolutePopup(this);
        var customOrder = this.getCustomPositionOrder(this);

        if (direction === "rtl") {
          defaultPosition = isAbsolute ? _popupconstants.rtlAbsolutePositionMapping[defaultPosition] : _popupconstants.rtlFixedPositionMapping[defaultPosition];
        } else {
          defaultPosition = isAbsolute ? _popupconstants.absolutePositionMapping[defaultPosition] : defaultPosition;
        }

        if (!placeHolderElement && !dropElement) {
          this.setState({
            isPopupOpen: true,
            isPopupReady: true
          });
          return;
        }

        var setPosition = function setPosition() {
          requestAnimationFrame(function () {
            var placeHolderElement = _this4.placeHolderElement,
                dropElement = _this4.dropElement;
            var _this4$state = _this4.state,
                position = _this4$state.position,
                isPopupReady = _this4$state.isPopupReady;
            var scrollContainer = placeHolderElement.closest("[data-scroll=true]") || document.body;

            var betterPosition = _viewport["default"].betterView(dropElement, placeHolderElement, defaultPosition, scrollContainer, {
              needArrow: needArrow,
              isAbsolute: isAbsolute,
              customOrder: customOrder
            });

            var _ref3 = betterPosition || {},
                view = _ref3.view,
                views = _ref3.views,
                viewsOffset = _ref3.viewsOffset,
                targetOffset = _ref3.targetOffset,
                popupOffset = _ref3.popupOffset;

            if (position !== view || !isPopupReady) {
              _this4.setState({
                isPopupReady: true,
                position: view,
                positions: views,
                positionsOffset: viewsOffset,
                targetOffset: targetOffset,
                popupOffset: popupOffset,
                isAbsolutePositioningNeeded: isAbsolute
              });
            }
          });
        };

        if (isResizeHandling) {
          setPosition();
        } else {
          this.defaultPosition = defaultPosition;
          this.setState({
            isPopupOpen: true,
            isPopupReady: false
          }, setPosition);
        }
      }
    }, {
      key: "handleOpenPopupPositionChange",
      value: function handleOpenPopupPositionChange() {
        var _this5 = this;

        Object.keys(popups).forEach(function (groupName) {
          var groupPopups = popups[groupName] || [];
          groupPopups.forEach(function (popup) {
            if (popup.state.isPopupOpen) {
              var placeHolderElement = popup.placeHolderElement,
                  dropElement = popup.dropElement,
                  defaultPosition = popup.defaultPosition;
              var _popup$state = popup.state,
                  position = _popup$state.position,
                  _popup$state$position = _popup$state.positionsOffset,
                  positionsOffset = _popup$state$position === void 0 ? {} : _popup$state$position;

              if (placeHolderElement && dropElement) {
                var scrollContainer = placeHolderElement.closest("[data-scroll=true]") || document.body;
                requestAnimationFrame(function () {
                  var needArrow = _this5.getNeedArrow(popup);

                  var isAbsolute = _this5.getIsAbsolutePopup(popup);

                  var customOrder = _this5.getCustomPositionOrder(popup);

                  var betterPosition = _viewport["default"].betterView(dropElement, placeHolderElement, defaultPosition, scrollContainer, {
                    needArrow: needArrow,
                    isAbsolute: isAbsolute,
                    customOrder: customOrder
                  });

                  var _ref4 = betterPosition || {},
                      view = _ref4.view,
                      views = _ref4.views,
                      _ref4$viewsOffset = _ref4.viewsOffset,
                      viewsOffset = _ref4$viewsOffset === void 0 ? {} : _ref4$viewsOffset,
                      targetOffset = _ref4.targetOffset,
                      popupOffset = _ref4.popupOffset;

                  var _ref5 = positionsOffset[position] || {},
                      _ref5$left = _ref5.left,
                      oldLeft = _ref5$left === void 0 ? "" : _ref5$left,
                      _ref5$top = _ref5.top,
                      oldTop = _ref5$top === void 0 ? "" : _ref5$top;

                  var _ref6 = viewsOffset[view] || {},
                      _ref6$left = _ref6.left,
                      left = _ref6$left === void 0 ? "" : _ref6$left,
                      _ref6$top = _ref6.top,
                      top = _ref6$top === void 0 ? "" : _ref6$top;

                  var changeState = isAbsolute ? position !== view : oldLeft !== left || oldTop !== top; // let isInViewPort = viewPort.isInViewPort(
                  //   placeHolderElement,
                  //   scrollContainer
                  // );

                  if (changeState) {
                    popup.setState({
                      position: view,
                      positions: views,
                      positionsOffset: viewsOffset,
                      targetOffset: targetOffset,
                      popupOffset: popupOffset,
                      isAbsolutePositioningNeeded: isAbsolute
                    });
                  } // if (!isInViewPort && !isAbsolute) {
                  //   popup.setState({ isPopupOpen: false, isPopupReady: false });
                  // } else if (view && changeState) {
                  //   popup.setState({
                  //     position: view,
                  //     positions: views,
                  //     positionsOffset: viewsOffset,
                  //     targetOffset,
                  //     popupOffset,
                  //     isAbsolutePositioningNeeded: isAbsolute
                  //   });
                  // }

                });
              }
            }
          });
        });
      }
    }, {
      key: "handleResize",
      value: function handleResize() {
        this.handleOpenPopupPositionChange();
      }
    }, {
      key: "handleScroll",
      value: function handleScroll(e) {
        // this.handleOpenPopupPositionChange();
        var _this$getCloseOnScrol = this.getCloseOnScrollPopup(this),
            closeOnScroll = _this$getCloseOnScrol.closeOnScroll;

        var isPopupReady = this.state.isPopupReady;

        if (isPopupReady) {
          console.log("onscrollPopupREady");
        }

        if (isPopupReady && closeOnScroll) {
          console.log(this, "handle Scroll");
          this.togglePopup(e);
        }
      }
    }, {
      key: "handlePopupResize",
      value: function handlePopupResize(popupSize) {
        var height = popupSize.height,
            width = popupSize.width;

        var _ref7 = this.size || {},
            _ref7$height = _ref7.height,
            oldHeight = _ref7$height === void 0 ? 0 : _ref7$height,
            _ref7$width = _ref7.width,
            oldWidth = _ref7$width === void 0 ? 0 : _ref7$width;

        var _this$state = this.state,
            isPopupReady = _this$state.isPopupReady,
            position = _this$state.position;

        if (isPopupReady && this.size && (oldHeight !== height || width !== oldWidth)) {
          this.handlePopupPosition(position, true);
        }

        this.size = popupSize;
      }
    }, {
      key: "getTargetRef",
      value: function getTargetRef(el) {
        this.placeHolderElement = el;
      }
    }, {
      key: "getContainerRef",
      value: function getContainerRef(el) {
        this.dropElement = el;
      }
    }, {
      key: "render",
      value: function render() {
        var _this$state2 = this.state,
            isPopupReady = _this$state2.isPopupReady,
            isPopupOpen = _this$state2.isPopupOpen;
        var localState = isPopupReady ? this.state : {};
        return /*#__PURE__*/_react["default"].createElement(Component, _extends({}, this.props, this.state, {
          openPopupOnly: this.openPopupOnly,
          closePopupOnly: this.closePopupOnly,
          togglePopup: this.togglePopup,
          removeClose: this.removeClose,
          getTargetRef: this.getTargetRef,
          getContainerRef: this.getContainerRef
        }));
      }
    }]);

    return Popup;
  }(_react["default"].Component);

  Popup.displayName = Component.displayName || Component.name || Popup.name;
  Popup.contextTypes = {
    direction: _propTypes["default"].string
  };
  return (0, _hoistNonReactStatics["default"])(Popup, Component);
};

var _default = Popup;
exports["default"] = _default;