"use strict";var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule = true;exports.ModalZIndexPriority = exports.ModalDataTids = exports.Modal = void 0;var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireDefault(require("react"));
var _reactFocusLock = _interopRequireDefault(require("react-focus-lock"));
var _lodash = _interopRequireDefault(require("lodash.throttle"));
var _globalObject = require("@skbkontur/global-object");

var _utils = require("../../lib/utils");
var _identifiers = require("../../lib/events/keyboard/identifiers");
var LayoutEvents = _interopRequireWildcard(require("../../lib/LayoutEvents"));
var _RenderContainer = require("../../internal/RenderContainer");
var _ZIndex = require("../../internal/ZIndex");
var _stopPropagation = require("../../lib/events/stopPropagation");
var _HideBodyVerticalScroll = require("../../internal/HideBodyVerticalScroll");

var _ModalStack = require("../../lib/ModalStack");
var _ResizeDetector = require("../../internal/ResizeDetector");
var _ThemeContext = require("../../lib/theming/ThemeContext");

var _client = require("../../lib/client");

var _CommonWrapper = require("../../internal/CommonWrapper");
var _Emotion = require("../../lib/theming/Emotion");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _ResponsiveLayout = require("../ResponsiveLayout");
var _ThemeHelpers = require("../../lib/theming/ThemeHelpers");
var _typeGuards = require("../../lib/typeGuards");


var _ModalContext = require("./ModalContext");
var _ModalFooter = require("./ModalFooter");
var _ModalHeader = require("./ModalHeader");
var _ModalBody = require("./ModalBody");
var _ModalClose = require("./ModalClose");
var _Modal2 = require("./Modal.styles");
var _getModalTheme = require("./getModalTheme");

var mountedModalsCount = 0;

























































var ModalDataTids = exports.ModalDataTids = {
  container: 'modal-container',
  content: 'modal-content',
  close: 'modal-close'
};

var ModalZIndexPriority = exports.ModalZIndexPriority = {
  Cross: 2,
  Content: 1
};



/** Модальное окно — это эмуляция диалогового окна браузера, оно появляется поверх страницы в ответ на действия пользователя и блокирует доступ к основному содержимому страницы.
 *
 * Составной компонент, включает в себя:
 * - «шапку» [Modal.Header](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_overlay-modal-modalheader--docs), состоящую из заголовка и крестика закрытия окна;
 * - контент-зону [Modal.Body](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_overlay-modal-modalbody--docs);
 * - футер [Modal.Footer](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_overlay-modal-modalfooter--docs).
 */var
Modal = exports.Modal = /*#__PURE__*/function (_React$Component) {function Modal() {var _this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;_this.














    getProps = (0, _createPropsGetter.createPropsGetter)(Modal.defaultProps);_this.

    state = {
      stackPosition: 0,
      hasBackground: true,
      horizontalScroll: false,
      hasHeader: false,
      hasFooter: false,
      hasPanel: false
    };_this.


    stackSubscription = null;_this.
    containerNode = null;_this.
    mouseDownTarget = null;_this.
    mouseUpTarget = null;_this.













































    getMobileContainerClassName = function () {
      var mobileAppearance = _this.getProps().mobileAppearance;
      switch (mobileAppearance) {
        case 'fullscreen-spacing':
          return;
        case 'auto':
          if (_this.state.hasFooter) {
            return;
          }
          return [_Modal2.styles.mobileContainerSmall5_2()];
        case 'fullscreen':
          return [_Modal2.styles.mobileContainerFullscreen5_2()];
        case 'center':
          return [_Modal2.styles.mobileContainerSmall5_2()];
        case 'bottom':
          return [_Modal2.styles.mobileContainerSmall5_2(), _Modal2.styles.mobileContainerSmallBottom5_2()];
        case 'top':
          return [_Modal2.styles.mobileContainerSmall5_2(), _Modal2.styles.mobileContainerSmallTop5_2()];
        default:
          return (0, _typeGuards.catchUnreachableWarning)(mobileAppearance, false);
      }
    };_this.


















































































































































    requestClose = function () {
      if (_this.props.disableClose) {
        return;
      }
      if (_this.props.onClose) {
        _this.props.onClose();
      }
    };_this.

    refContainer = function (center) {
      _this.containerNode = center;
    };_this.

    handleStackChange = function (stack) {
      _this.setState({ stackPosition: stack.indexOf(_this), hasBackground: _ModalStack.ModalStack.isBlocking(_this) });
    };_this.

    handleContainerMouseDown = function (event) {
      _this.mouseDownTarget = event.target;
    };_this.

    handleContainerMouseUp = function (event) {
      _this.mouseUpTarget = event.target;
    };_this.

    handleContainerClick = function (event) {
      if (!_this.props.ignoreBackgroundClick) {
        var target = event.target,currentTarget = event.currentTarget;
        if (target === currentTarget && _this.mouseDownTarget === currentTarget && _this.mouseUpTarget === currentTarget) {
          _this.requestClose();
        }
      }
    };_this.

    handleKeyDown = function (e) {
      if (_this.state.stackPosition !== 0) {
        return;
      }
      if ((0, _identifiers.isKeyEscape)(e)) {
        (0, _stopPropagation.stopPropagation)(e);
        _this.requestClose();
      }
    };_this.

    checkHorizontalScrollAppearance = function () {
      var hasScroll = false;

      if (_this.containerNode) {
        var containerClientWidth = _this.containerNode.clientWidth;
        var containerScrollWidth = _this.containerNode.scrollWidth;
        hasScroll = containerClientWidth < containerScrollWidth;
      }
      if (hasScroll && !_this.state.horizontalScroll) {
        _this.setState({ horizontalScroll: true });
      } else if (_this.state.horizontalScroll) {
        _this.setState({ horizontalScroll: false });
      }
    };_this.

    throttledCheckHorizontalScroll = (0, _lodash.default)(_this.checkHorizontalScrollAppearance, 100);_this.

    handleResize = function () {
      LayoutEvents.emit();
    };_this.

    setHasHeader = function (hasHeader) {
      _this.setState({ hasHeader: hasHeader });
    };_this.

    setHasFooter = function (hasFooter) {
      _this.setState({ hasFooter: hasFooter });
    };_this.

    setHasPanel = function (hasPanel) {
      _this.setState({ hasPanel: hasPanel });
    };return _this;}(0, _inheritsLoose2.default)(Modal, _React$Component);var _proto = Modal.prototype;_proto.componentDidMount = function componentDidMount() {this.stackSubscription = _ModalStack.ModalStack.add(this, this.handleStackChange);if (mountedModalsCount === 0) {_globalObject.globalObject.addEventListener == null || _globalObject.globalObject.addEventListener('resize', this.throttledCheckHorizontalScroll);}mountedModalsCount++;_globalObject.globalObject.addEventListener == null || _globalObject.globalObject.addEventListener('keydown', this.handleKeyDown);this.checkHorizontalScrollAppearance();if (this.containerNode) {this.containerNode.addEventListener('scroll', LayoutEvents.emit);}};_proto.componentWillUnmount = function componentWillUnmount() {if (--mountedModalsCount === 0) {_globalObject.globalObject.removeEventListener == null || _globalObject.globalObject.removeEventListener('resize', this.throttledCheckHorizontalScroll);LayoutEvents.emit();}_globalObject.globalObject.removeEventListener == null || _globalObject.globalObject.removeEventListener('keydown', this.handleKeyDown);if ((0, _utils.isNonNullable)(this.stackSubscription)) {this.stackSubscription.remove();}_ModalStack.ModalStack.remove(this);if (this.containerNode) {this.containerNode.removeEventListener('scroll', LayoutEvents.emit);}};_proto.render = function render() {var _this2 = this;return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = (0, _getModalTheme.getModalTheme)(theme, _this2.props.theme);return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Provider, { value: _this2.theme }, _this2.renderMain());});};_proto.renderMain = function renderMain() {var _this3 = this;var _this$props = this.props,noClose = _this$props.noClose,disableClose = _this$props.disableClose,width = _this$props.width,mobileAppearance = _this$props.mobileAppearance,alignTop = _this$props.alignTop,children = _this$props.children,ariaLabel = _this$props['aria-label'],ariaLabelledby = _this$props['aria-labelledby'];var _this$state = this.state,hasHeader = _this$state.hasHeader,hasFooter = _this$state.hasFooter,hasPanel = _this$state.hasPanel;var _this$getProps = this.getProps(),role = _this$getProps.role,disableFocusLock = _this$getProps.disableFocusLock;var modalContextProps = { hasHeader: hasHeader, horizontalScroll: this.state.horizontalScroll, setHasHeader: this.setHasHeader, setHasFooter: this.setHasFooter, setHasPanel: this.setHasPanel, mobileOnFullScreen: this.props.mobileAppearance === 'fullscreen' };if (!noClose) {modalContextProps.close = { disableClose: disableClose, requestClose: this.requestClose };}if (!hasFooter || hasPanel) {modalContextProps.additionalPadding = true;}var versionGTE5_2 = (0, _ThemeHelpers.isThemeGTE)(this.theme, '5.2');var style = {};var containerStyle = {};if (width) {style.width = width;} else {containerStyle.width = 'auto';}var getMobileCenterContainerClassNames = function getMobileCenterContainerClassNames() {if (versionGTE5_2) {var _cx;return (0, _Emotion.cx)(_Modal2.styles.mobileCenterContainer5_2(_this3.theme), (_cx = {}, _cx[_Modal2.styles.mobileCenterContainerBig5_2(_this3.theme)] = mobileAppearance === 'fullscreen-spacing' || mobileAppearance === 'auto' && hasFooter, _cx[_Modal2.styles.mobileCenterContainerFullscreen5_2()] = mobileAppearance === 'fullscreen', _cx));}return (0, _Emotion.cx)(_Modal2.styles.mobileCenterContainer());};return /*#__PURE__*/_react.default.createElement(_RenderContainer.RenderContainer, null, /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, this.props, /*#__PURE__*/_react.default.createElement(_ZIndex.ZIndex, { priority: 'Modal', className: _Modal2.styles.root() }, /*#__PURE__*/_react.default.createElement(_HideBodyVerticalScroll.HideBodyVerticalScroll, null), this.state.hasBackground && /*#__PURE__*/_react.default.createElement("div", { onMouseDown: this.handleContainerMouseDown, onMouseUp: this.handleContainerMouseUp, onClick: this.handleContainerClick, className: _Modal2.styles.bg(this.theme) }), /*#__PURE__*/_react.default.createElement(_ResponsiveLayout.ResponsiveLayout, null, function (_ref) {var _cx2, _cx3, _cx4, _cx5, _cx6;var isMobile = _ref.isMobile;return /*#__PURE__*/_react.default.createElement("div", { "aria-labelledby": ariaLabelledby, ref: _this3.refContainer, className: (0, _Emotion.cx)(_Modal2.styles.container(), versionGTE5_2 && _Modal2.styles.container5_2(), (!versionGTE5_2 || !isMobile) && _Modal2.styles.containerDesktop(), !versionGTE5_2 && isMobile && _Modal2.styles.containerMobile(_this3.theme), versionGTE5_2 && isMobile && _this3.getMobileContainerClassName()), onMouseDown: _this3.handleContainerMouseDown, onMouseUp: _this3.handleContainerMouseUp, onClick: _this3.handleContainerClick, "data-tid": ModalDataTids.container }, /*#__PURE__*/_react.default.createElement("div", { "aria-modal": true, "aria-label": ariaLabel, role: role, className: (0, _Emotion.cx)((_cx2 = {}, _cx2[_Modal2.styles.centerContainer()] = true, _cx2[getMobileCenterContainerClassNames()] = isMobile, _cx2[_Modal2.styles.alignTop()] = Boolean(alignTop), _cx2)), style: isMobile ? undefined : containerStyle, "data-tid": ModalDataTids.content }, /*#__PURE__*/_react.default.createElement("div", { className: (0, _Emotion.cx)((_cx3 = {}, _cx3[_Modal2.styles.window(_this3.theme)] = true, _cx3[_Modal2.styles.mobileWindow()] = isMobile, _cx3[_Modal2.styles.mobileWindowFullscreen5_2()] = versionGTE5_2 && isMobile && mobileAppearance === 'fullscreen', _cx3)), style: isMobile ? undefined : style }, /*#__PURE__*/_react.default.createElement(_ResizeDetector.ResizeDetector, { onResize: _this3.handleResize, fullHeight: isMobile }, /*#__PURE__*/_react.default.createElement(_reactFocusLock.default, { disabled: disableFocusLock, autoFocus: false, className: (0, _Emotion.cx)((_cx4 = {}, _cx4[_Modal2.styles.columnFlexContainer()] = isMobile, _cx4), 'focus-lock-container') }, !hasHeader && !noClose && /*#__PURE__*/_react.default.createElement(_ZIndex.ZIndex, { priority: ModalZIndexPriority.Cross, className: (0, _Emotion.cx)((_cx5 = {}, _cx5[_Modal2.styles.closeWrapper(_this3.theme)] = true, _cx5[_Modal2.styles.mobileCloseWrapper(_this3.theme)] = isMobile, _cx5[_Modal2.styles.mobileCloseWrapper5_2(_this3.theme)] = versionGTE5_2 && isMobile, _cx5)) }, /*#__PURE__*/_react.default.createElement(_ModalClose.ModalClose, { className: (0, _Emotion.cx)((_cx6 = {}, _cx6[_Modal2.styles.mobileCloseWithoutHeader()] = isMobile && !_this3.state.hasHeader, _cx6[_Modal2.styles.mobileCloseWithoutHeader5_2(_this3.theme)] = versionGTE5_2 && isMobile && !_this3.state.hasHeader, _cx6)), requestClose: _this3.requestClose, disableClose: disableClose })), /*#__PURE__*/_react.default.createElement(_ModalContext.ModalContext.Provider, { value: modalContextProps }, children))))));}))));};return Modal;}(_react.default.Component);Modal.__KONTUR_REACT_UI__ = 'Modal';Modal.displayName = 'Modal';Modal.Header = _ModalHeader.ModalHeader;Modal.Body = _ModalBody.ModalBody;Modal.Footer = _ModalFooter.ModalFooter;Modal.defaultProps = { // NOTE: в ie нормально не работает
  disableFocusLock: _client.isIE11, role: 'dialog', mobileAppearance: 'auto' };