var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import React from 'react';
import throttle from 'lodash.throttle';
import { FocusLock } from '../../internal/react-focus-lock/index.js';
import { isNonNullable } from '../../lib/utils.js';
import { isKeyEscape } from '../../lib/events/keyboard/identifiers.js';
import * as LayoutEvents from '../../lib/LayoutEvents.js';
import { RenderContainer } from '../../internal/RenderContainer/index.js';
import { ZIndex } from '../../internal/ZIndex/index.js';
import { HideBodyVerticalScroll } from '../../internal/HideBodyVerticalScroll/index.js';
import { ModalStack } from '../../lib/ModalStack.js';
import { ResizeDetector } from '../../internal/ResizeDetector/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { ResponsiveLayout } from '../ResponsiveLayout/index.js';
import { catchUnreachableWarning } from '../../lib/typeGuards.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { ModalContext } from './ModalContext.js';
import { ModalFooter } from './ModalFooter.js';
import { ModalHeader } from './ModalHeader.js';
import { ModalBody } from './ModalBody.js';
import { ModalClose } from './ModalClose.js';
import { getStyles } from './Modal.styles.js';
import { getModalTheme } from './getModalTheme.js';
var mountedModalsCount = 0;
export var ModalDataTids = {
    container: 'modal-container',
    content: 'modal-content',
    close: 'modal-close',
};
export var 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 = /** @class */ (function (_super) {
    __extends(Modal, _super);
    function Modal() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getProps = createPropsGetter(Modal_1.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 [_this.styles.mobileContainerSmall5_2()];
                case 'fullscreen':
                    return [_this.styles.mobileContainerFullscreen5_2()];
                case 'center':
                    return [_this.styles.mobileContainerSmall5_2()];
                case 'bottom':
                    return [_this.styles.mobileContainerSmall5_2(), _this.styles.mobileContainerSmallBottom5_2()];
                case 'top':
                    return [_this.styles.mobileContainerSmall5_2(), _this.styles.mobileContainerSmallTop5_2()];
                default:
                    return 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.isBlocking(_this, _this.globalObject),
            });
        };
        _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 (isKeyEscape(e)) {
                e.stopPropagation();
                _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 = throttle(_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;
    }
    Modal_1 = Modal;
    Modal.prototype.componentDidMount = function () {
        var _a, _b, _c, _d;
        this.stackSubscription = ModalStack.add(this, this.handleStackChange, this.globalObject);
        if (mountedModalsCount === 0) {
            (_b = (_a = this.globalObject).addEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, 'resize', this.throttledCheckHorizontalScroll);
        }
        mountedModalsCount++;
        (_d = (_c = this.globalObject).addEventListener) === null || _d === void 0 ? void 0 : _d.call(_c, 'keydown', this.handleKeyDown);
        this.checkHorizontalScrollAppearance();
        if (this.containerNode) {
            this.containerNode.addEventListener('scroll', LayoutEvents.emit);
        }
    };
    Modal.prototype.componentWillUnmount = function () {
        var _a, _b, _c, _d;
        if (--mountedModalsCount === 0) {
            (_b = (_a = this.globalObject).removeEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, 'resize', this.throttledCheckHorizontalScroll);
            LayoutEvents.emit();
        }
        (_d = (_c = this.globalObject).removeEventListener) === null || _d === void 0 ? void 0 : _d.call(_c, 'keydown', this.handleKeyDown);
        if (isNonNullable(this.stackSubscription)) {
            this.stackSubscription.remove();
        }
        ModalStack.remove(this, this.globalObject);
        if (this.containerNode) {
            this.containerNode.removeEventListener('scroll', LayoutEvents.emit);
        }
    };
    Modal.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = getModalTheme(theme, _this.props.theme);
            return React.createElement(ThemeContext.Provider, { value: _this.theme }, _this.renderMain());
        }));
    };
    Modal.prototype.renderMain = function () {
        var _this = this;
        var _a = this.props, noClose = _a.noClose, disableClose = _a.disableClose, width = _a.width, mobileAppearance = _a.mobileAppearance, alignTop = _a.alignTop, children = _a.children, ariaLabel = _a["aria-label"], ariaLabelledby = _a["aria-labelledby"];
        var _b = this.state, hasHeader = _b.hasHeader, hasFooter = _b.hasFooter, hasPanel = _b.hasPanel;
        var _c = this.getProps(), role = _c.role, disableFocusLock = _c.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 style = {};
        var containerStyle = {};
        if (width) {
            style.width = width;
        }
        else {
            containerStyle.width = 'auto';
        }
        var getMobileCenterContainerClassNames = function () {
            var _a;
            return _this.cx(_this.styles.mobileCenterContainer(_this.theme), (_a = {},
                _a[_this.styles.mobileCenterContainerBig(_this.theme)] = mobileAppearance === 'fullscreen-spacing' || (mobileAppearance === 'auto' && hasFooter),
                _a[_this.styles.mobileCenterContainerFullscreen()] = mobileAppearance === 'fullscreen',
                _a));
        };
        return (React.createElement(RenderContainer, null,
            React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
                React.createElement(ZIndex, { priority: 'Modal', className: this.styles.root() },
                    React.createElement(HideBodyVerticalScroll, null),
                    this.state.hasBackground && (React.createElement("div", { onMouseDown: this.handleContainerMouseDown, onMouseUp: this.handleContainerMouseUp, onClick: this.handleContainerClick, className: this.styles.bg(this.theme) })),
                    React.createElement(ResponsiveLayout, null, function (_a) {
                        var _b, _c, _d, _e, _f;
                        var isMobile = _a.isMobile;
                        return (React.createElement("div", { "aria-labelledby": ariaLabelledby, ref: _this.refContainer, className: _this.cx(_this.styles.container(), !isMobile && _this.styles.containerDesktop(), isMobile && _this.getMobileContainerClassName()), onMouseDown: _this.handleContainerMouseDown, onMouseUp: _this.handleContainerMouseUp, onClick: _this.handleContainerClick, "data-tid": ModalDataTids.container },
                            React.createElement("div", { "aria-modal": true, "aria-label": ariaLabel, role: role, className: _this.cx((_b = {},
                                    _b[_this.styles.centerContainer()] = true,
                                    _b[getMobileCenterContainerClassNames()] = isMobile,
                                    _b[_this.styles.alignTop()] = Boolean(alignTop),
                                    _b)), style: isMobile ? undefined : containerStyle, "data-tid": ModalDataTids.content },
                                React.createElement("div", { className: _this.cx((_c = {},
                                        _c[_this.styles.window(_this.theme)] = true,
                                        _c[_this.styles.mobileWindow()] = isMobile,
                                        _c[_this.styles.mobileWindowFullscreen()] = isMobile && mobileAppearance === 'fullscreen',
                                        _c)), style: isMobile ? undefined : style },
                                    React.createElement(ResizeDetector, { onResize: _this.handleResize, fullHeight: isMobile },
                                        React.createElement(FocusLock, { disabled: disableFocusLock, autoFocus: false, className: _this.cx((_d = {}, _d[_this.styles.columnFlexContainer()] = isMobile, _d), 'focus-lock-container') },
                                            !hasHeader && !noClose && (React.createElement(ZIndex, { priority: ModalZIndexPriority.Cross, className: _this.cx((_e = {},
                                                    _e[_this.styles.closeWrapper(_this.theme)] = true,
                                                    _e[_this.styles.mobileCloseWrapper(_this.theme)] = isMobile,
                                                    _e)) },
                                                React.createElement(ModalClose, { className: _this.cx((_f = {},
                                                        _f[_this.styles.mobileCloseWithoutHeader(_this.theme)] = isMobile && !_this.state.hasHeader,
                                                        _f)), requestClose: _this.requestClose, disableClose: disableClose }))),
                                            React.createElement(ModalContext.Provider, { value: modalContextProps }, children)))))));
                    })))));
    };
    var Modal_1;
    Modal.__KONTUR_REACT_UI__ = 'Modal';
    Modal.displayName = 'Modal';
    Modal.Header = ModalHeader;
    Modal.Body = ModalBody;
    Modal.Footer = ModalFooter;
    Modal.defaultProps = {
        disableFocusLock: false,
        role: 'dialog',
        mobileAppearance: 'auto',
    };
    Modal = Modal_1 = __decorate([
        withRenderEnvironment,
        rootNode
    ], Modal);
    return Modal;
}(React.Component));
export { Modal };
//# sourceMappingURL=Modal.js.map