"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;

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

var _Modal = _interopRequireDefault(require("./Modal.FocusTrap"));

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

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; }

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 listOfWrapperElementsToFloatingUI = [];
var pageElementReference;
var isKeyDownEventListenerConfigured = false;

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

  var _super = _createSuper(Modal);

  function Modal(props) {
    var _this;

    _classCallCheck(this, Modal);

    _this = _super.call(this, props); // Create a div that we'll render the modal into. Because each
    // Modal component has its own element, we can render multiple
    // modal components into the modal container.

    _this.el = document.createElement('div'); // this.el = props.modalContainerNode;

    _this.el.className = 'floatingcontainer_' + new Date().getTime();
    _this.renderProps = {};
    _this.bindKeyDownEventToDocument = _this.bindKeyDownEventToDocument.bind(_assertThisInitialized(_this));
    _this.handleKeyPressEvent = _this.handleKeyPressEvent.bind(_assertThisInitialized(_this));
    _this.checkStatusOfKeyDownEventBoundToDocument = _this.checkStatusOfKeyDownEventBoundToDocument.bind(_assertThisInitialized(_this));
    _this.setKeyDownEventBoundToDocumentStatusToTrue = _this.setKeyDownEventBoundToDocumentStatusToTrue.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(Modal, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.props.modalrootNode.appendChild(this.el);
      this.mapFloatingContainerWithDIalogElement();
      this.applyFocusToFloatingDialogElement(this.el.className);
      this.persistPageElementReference();
      this.bindKeyDownEventToDocument();
    }
  }, {
    key: "mapFloatingContainerWithDIalogElement",
    value: function mapFloatingContainerWithDIalogElement() {
      listOfWrapperElementsToFloatingUI.push(_defineProperty({}, this.el.className, {
        modalroot: this.props.modalrootNode,
        floatinguicontainerelement: this.el,
        functionReferenceToFocus: this.props.focusDialogReference ? this.props.focusDialogReference : false,
        functionReferenceToClose: this.props.closeDialogReference,
        isOverlayNeeded: !!this.props.freezeLayer
      }));
    }
  }, {
    key: "applyFocusToFloatingDialogElement",
    value: function applyFocusToFloatingDialogElement(refClass) {
      var indexOfContainerElement = this.getIndexOfContainerElement(refClass);
      var floatingContainerObj = listOfWrapperElementsToFloatingUI[indexOfContainerElement][refClass];
      floatingContainerObj.functionReferenceToFocus && floatingContainerObj.functionReferenceToFocus();
    }
  }, {
    key: "bindKeyDownEventToDocument",
    value: function bindKeyDownEventToDocument() {
      if (!this.checkStatusOfKeyDownEventBoundToDocument()) {
        document.addEventListener('keydown', this.handleKeyPressEvent, true);
        this.setKeyDownEventBoundToDocumentStatusToTrue();
      }
    }
  }, {
    key: "checkStatusOfKeyDownEventBoundToDocument",
    value: function checkStatusOfKeyDownEventBoundToDocument() {
      return isKeyDownEventListenerConfigured;
    }
  }, {
    key: "setKeyDownEventBoundToDocumentStatusToTrue",
    value: function setKeyDownEventBoundToDocumentStatusToTrue() {
      isKeyDownEventListenerConfigured = true;
    }
  }, {
    key: "handleKeyPressEvent",
    value: function handleKeyPressEvent(event) {
      if (event.eventPhase === 3) {
        return false;
      }

      if (event.key === 'Escape' && this.props.isCloseOnEscapeNeeded) {
        var floatingDialogContinerClassName = this.getClassNameOfClosestContainerElement(event.target);
        var indexOfContainerElement = floatingDialogContinerClassName === undefined ? listOfWrapperElementsToFloatingUI.length - 1 : this.getIndexOfContainerElement(floatingDialogContinerClassName);

        if (floatingDialogContinerClassName === undefined) {
          floatingDialogContinerClassName = this.getClassNameOfContainerElement(indexOfContainerElement);
        }

        this.invokeCloseCallBackFunctionOfDialogElement(indexOfContainerElement, floatingDialogContinerClassName);
      } else if (event.key === 'Tab') {
        this.isTabKeyPressed = true;

        var _floatingDialogContinerClassName = this.getClassNameOfClosestContainerElement(event.target);

        if (_floatingDialogContinerClassName !== undefined) {
          var _indexOfContainerElement = this.getIndexOfContainerElement(_floatingDialogContinerClassName);

          if (this.props.isTrapFocusNeeded) {
            (0, _Modal["default"])(event, listOfWrapperElementsToFloatingUI[_indexOfContainerElement][_floatingDialogContinerClassName].floatinguicontainerelement);
          }
        }
      }
    }
  }, {
    key: "getClassNameOfClosestContainerElement",
    value: function getClassNameOfClosestContainerElement(elemObj) {
      if (elemObj.closest('div[class^=floatingcontainer_]') !== null) {
        return elemObj.closest('div[class^=floatingcontainer_]').className;
      }
    }
  }, {
    key: "getClassNameOfContainerElement",
    value: function getClassNameOfContainerElement(index) {
      var containerObj = listOfWrapperElementsToFloatingUI[index];
      return Object.keys(containerObj)[0];
    }
  }, {
    key: "getContainerElement",
    value: function getContainerElement(index) {
      var containerObj = listOfWrapperElementsToFloatingUI[index];
      return containerObj[Object.keys(containerObj)[0]];
    }
  }, {
    key: "getIndexOfContainerElement",
    value: function getIndexOfContainerElement(valueToMatch) {
      var that = this;
      return listOfWrapperElementsToFloatingUI.findIndex(function (element) {
        return that.findIndexOfContainerElement(element, valueToMatch);
      });
    }
  }, {
    key: "findIndexOfContainerElement",
    value: function findIndexOfContainerElement(element, floatingDialogContinerClassName) {
      return Object.keys(element)[0] == floatingDialogContinerClassName;
    }
  }, {
    key: "removeFloatingUIContainerElement",
    value: function removeFloatingUIContainerElement(index, refClass) {
      if (Object.keys(listOfWrapperElementsToFloatingUI[index])[0] === refClass) {
        var floatingContainerObj = listOfWrapperElementsToFloatingUI[index][refClass];
        var floatingContainerElem = floatingContainerObj.floatinguicontainerelement;
        var modalRoot = floatingContainerObj.modalroot;
        modalRoot.removeChild(floatingContainerElem);
        listOfWrapperElementsToFloatingUI.splice(index, 1);

        if (listOfWrapperElementsToFloatingUI.length === 0) {
          this.resetModalBoxValues();
        } else {
          var topElem = this.getContainerElement(listOfWrapperElementsToFloatingUI.length - 1);
          topElem.functionReferenceToFocus && topElem.functionReferenceToFocus();
        }
      }
    }
  }, {
    key: "invokeCloseCallBackFunctionOfDialogElement",
    value: function invokeCloseCallBackFunctionOfDialogElement(indexOfDialogElement, refClass) {
      listOfWrapperElementsToFloatingUI[indexOfDialogElement][refClass].functionReferenceToClose();
    }
  }, {
    key: "getTopMostFloatingUIContainerElement",
    value: function getTopMostFloatingUIContainerElement(refClass) {
      var lengthOfUIContainerElement = listOfWrapperElementsToFloatingUI.length;
      return listOfWrapperElementsToFloatingUI[lengthOfUIContainerElement - 1][refClass].floatinguicontainerelement;
    }
  }, {
    key: "getFloatingUIContainerElement",
    value: function getFloatingUIContainerElement(index, refClass) {
      return listOfWrapperElementsToFloatingUI[index][refClass].floatinguicontainerelement;
    }
  }, {
    key: "persistPageElementReference",
    value: function persistPageElementReference() {
      if (typeof this.props.pageElementNode !== 'undefined') {
        pageElementReference = this.props.pageElementNode;
      }
    }
  }, {
    key: "applyFocusToPageElementReference",
    value: function applyFocusToPageElementReference() {
      pageElementReference.current.focus();
    }
  }, {
    key: "resetPageElementReference",
    value: function resetPageElementReference() {
      pageElementReference = null;
    }
  }, {
    key: "resetisEventListenerAddedProperty",
    value: function resetisEventListenerAddedProperty() {
      isKeyDownEventListenerConfigured = false;
    }
  }, {
    key: "unbindKeyDownEventListener",
    value: function unbindKeyDownEventListener() {
      document.removeEventListener('keydown', this.handleKeyPressEvent);
    }
  }, {
    key: "resetModalBoxValues",
    value: function resetModalBoxValues() {
      this.applyFocusToPageElementReference();
      this.resetPageElementReference();
      this.resetisEventListenerAddedProperty();
      this.unbindKeyDownEventListener();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var indexOfContainerElement = this.getIndexOfContainerElement(this.el.className);
      this.removeFloatingUIContainerElement(indexOfContainerElement, this.el.className);
    }
  }, {
    key: "render",
    value: function render() {
      var skeletonOfModal = /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, this.props.freezeLayer ? this.props.freezeLayer(this.props) : this.props.children);

      return ReactDOM.createPortal( // Any valid React child: JSX, strings, arrays, etc.
      skeletonOfModal, // A DOM element
      this.el);
    }
  }]);

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

exports["default"] = Modal;