'use strict';

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.Popup = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

var _reactDom = require("react-dom");

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

var _classnames = _interopRequireDefault(require("classnames"));

var _Modal = _interopRequireDefault(require("react-bootstrap/lib/Modal"));

var _utils = require("../utils");

var _constants = require("../../../utils/constants");

var _tabbable = _interopRequireDefault(require("tabbable"));

var Popup =
/*#__PURE__*/
function (_React$Component) {
  (0, _inheritsLoose2.default)(Popup, _React$Component);

  Popup.close = function close() {
    if (Popup.stack.length) {
      var popup = Popup.stack[Popup.stack.length - 1];

      if (popup.props.onHide) {
        popup.props.onHide();
        return;
      }
    }

    (0, _utils.closePopup)();
  };

  Popup.addStyleSheet = function addStyleSheet() {
    var width = (0, _utils.getScrollbarWidth)();
    Popup.styleSheet = document.createElement('style');
    Popup.styleSheet.innerHTML = "\n            body.rc-modal-open {\n                padding-right: " + width + "px !important;\n            }\n            [aria-hidden=\"true\"] [role=\"dialog\"] {\n                padding-right: " + width + "px !important;\n            }\n        ";
    document.head.appendChild(Popup.styleSheet);
  };

  Popup.updateBodyClass = function updateBodyClass() {
    var length = Popup.stack.length;
    var regexp = /\s*rc-modal-open/g;

    if (length) {
      if (!regexp.test(document.body.className)) {
        document.body.className += document.body.className.length ? ' rc-modal-open' : 'rc-modal-open';
      }
    } else {
      document.body.className = document.body.className.replace(regexp, '');
    }
  };

  function Popup(props, context) {
    var _this;

    if (!Popup.styleSheet) {
      Popup.addStyleSheet();
    }

    _this = _React$Component.call(this, props, context) || this;
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleHeaderRef", function (ref) {
      if (!ref) {
        return;
      }

      var $modalHeader = (0, _reactDom.findDOMNode)(ref);

      if (!$modalHeader) {
        return;
      }

      var $closeButton = $modalHeader.querySelector("button[class = 'close']");

      if ($closeButton) {
        $closeButton.setAttribute('data-test-automation-id', 'closeButton');
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "trapFocus", function (event) {
      if (event.keyCode === _constants.KeyCodes.TAB) {
        var activeElement = document.activeElement;
        var modalContentNode = _this.modalContentRef.current;
        var tabbableNodes = (0, _tabbable.default)(modalContentNode);
        event.stopPropagation();

        if (tabbableNodes.length === 0) {
          return event.preventDefault();
        }

        if (event.shiftKey) {
          var isDispatchedOnModalWrapper = activeElement.contains(modalContentNode);

          if (isDispatchedOnModalWrapper || tabbableNodes[0] === activeElement) {
            event.preventDefault();
            tabbableNodes[tabbableNodes.length - 1].focus();
          }
        } else {
          if (tabbableNodes[tabbableNodes.length - 1] === activeElement) {
            event.preventDefault();
            tabbableNodes[0].focus();
          }
        }
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "hideModal", function () {
      if (_this.props.onClose) {
        _this.props.onClose();
      } else {
        Popup.close();
      }
    });
    Popup.stack.push((0, _assertThisInitialized2.default)(_this));
    Popup.updateBodyClass();
    _this.modalContentRef = _react.default.createRef();
    _this.hideModal = _this.hideModal.bind((0, _assertThisInitialized2.default)(_this));
    return _this;
  }

  var _proto = Popup.prototype;

  _proto.componentWillUnmount = function componentWillUnmount() {
    var index = Popup.stack.indexOf(this);

    if (index !== -1) {
      Popup.stack.splice(index, 1);
      Popup.updateBodyClass();
      setImmediate(_utils.restorePopupVisibility);
    }
  };

  _proto.render = function render() {
    // Extract own props to make it safe to pass Modal props down
    var _this$props = this.props,
        testAutomationId = _this$props.testAutomationId,
        stackable = _this$props.stackable,
        noPadding = _this$props.noPadding,
        noBottomPadding = _this$props.noBottomPadding,
        noHeaderPadding = _this$props.noHeaderPadding,
        borderedTitle = _this$props.borderedTitle,
        closeButton = _this$props.closeButton,
        keyboard = _this$props.keyboard,
        closeLabel = _this$props.closeLabel,
        className = _this$props.className,
        header = _this$props.header,
        footer = _this$props.footer,
        title = _this$props.title,
        onClose = _this$props.onClose,
        children = _this$props.children,
        ariaLabelledBy = _this$props['aria-labelledby'],
        ariaDescribedBy = _this$props['aria-describedby'],
        shouldDeriveDescFromBody = _this$props.shouldDeriveDescFromBody,
        props = (0, _objectWithoutPropertiesLoose2.default)(_this$props, ["testAutomationId", "stackable", "noPadding", "noBottomPadding", "noHeaderPadding", "borderedTitle", "closeButton", "keyboard", "closeLabel", "className", "header", "footer", "title", "onClose", "children", "aria-labelledby", "aria-describedby", "shouldDeriveDescFromBody"]);
    var titleId = "dlg-title-" + testAutomationId;
    var contentId = "dlg-content-" + testAutomationId;

    if (!ariaLabelledBy) {
      ariaLabelledBy = titleId;
    }

    if (!ariaDescribedBy && shouldDeriveDescFromBody) {
      ariaDescribedBy = contentId;
    }

    if (this.props.footer) {
      footer = _react.default.createElement(_Modal.default.Footer, {
        "data-test-automation-id": "popupFooter"
      }, footer);
    }

    if (title) {
      title = _react.default.createElement(_Modal.default.Title, {
        role: "presentation",
        "data-test-automation-id": "title",
        className: (0, _classnames.default)({
          'bordered-modal-title': borderedTitle
        })
      }, _react.default.createElement("span", {
        id: titleId
      }, title));
    }

    if (!title && header) {
      header = (0, _react.cloneElement)(header, {
        id: titleId
      });
    }

    var supportEscClose = keyboard || closeButton;
    return _react.default.createElement(_Modal.default, (0, _extends2.default)({
      keyboard: supportEscClose,
      onKeyDown: this.trapFocus,
      show: true,
      "data-test-automation-id": testAutomationId,
      container: document.getElementById(_utils.popupContainerId)
    }, props, {
      "aria-labelledby": ariaLabelledBy,
      "aria-describedby": ariaDescribedBy,
      role: "document",
      enforceFocus: false,
      onHide: this.hideModal,
      className: (0, _classnames.default)('static-modal', {
        'rc-popup-noPadding': noPadding,
        'rc-popup-noBottomPadding': noBottomPadding,
        'rc-popup-noHeaderPadding': noHeaderPadding,
        // we have a technical difficulties for close button manipulations during closeButton prop changes
        // Modal calls componentDidUpdate in incorrect order, so we have to render it always and manage
        // visibility via CSS
        'rc-popup-noCloseButton': !closeButton
      }, className)
    }), _react.default.createElement("div", {
      ref: this.modalContentRef
    }, _react.default.createElement(_Modal.default.Header, {
      ref: this.handleHeaderRef,
      "data-test-automation-id": "popupHeader",
      closeButton: true,
      closeLabel: closeLabel
    }, title, header), _react.default.createElement(_Modal.default.Body, {
      id: contentId,
      "data-test-automation-id": "popupContent"
    }, children), footer));
  };

  return Popup;
}(_react.default.Component);

exports.Popup = Popup;
(0, _defineProperty2.default)(Popup, "stack", []);
(0, _defineProperty2.default)(Popup, "propTypes", {
  children: _propTypes.default.node,
  className: _propTypes.default.string,
  stackable: _propTypes.default.bool,
  borderedTitle: _propTypes.default.bool,
  noPadding: _propTypes.default.bool,
  noBottomPadding: _propTypes.default.bool,
  noHeaderPadding: _propTypes.default.bool,
  closeButton: _propTypes.default.bool,
  closeLabel: _propTypes.default.string,
  title: _propTypes.default.string,
  testAutomationId: _propTypes.default.string,
  header: _propTypes.default.node,
  footer: _propTypes.default.node,
  onClose: _propTypes.default.func,
  'aria-labelledby': _propTypes.default.string,
  'aria-describedby': _propTypes.default.string,
  shouldDeriveDescFromBody: _propTypes.default.bool,
  keyboard: _propTypes.default.bool
});
(0, _defineProperty2.default)(Popup, "defaultProps", {
  children: null,
  className: null,
  testAutomationId: 'popup',
  borderedTitle: false,
  noPadding: false,
  noBottomPadding: false,
  noHeaderPadding: false,
  title: '',
  closeButton: true,
  closeLabel: 'TRANSLATE:CLOSE',
  header: null,
  footer: null,
  stackable: false,
  backdrop: 'static',
  onClose: null,
  'aria-labelledby': null,
  'aria-describedby': null,
  shouldDeriveDescFromBody: false,
  keyboard: false
});