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 { CSSTransition } from 'react-transition-group';
import { FocusLock } from '../../internal/react-focus-lock/index.js';
import { isNonNullable, isReactUIInstance } from '../../lib/utils.js';
import { isKeyEscape } from '../../lib/events/keyboard/identifiers.js';
import * as LayoutEvents from '../../lib/LayoutEvents.js';
import { HideBodyVerticalScroll } from '../../internal/HideBodyVerticalScroll/index.js';
import { ModalStack } from '../../lib/ModalStack.js';
import { RenderContainer } from '../../internal/RenderContainer/index.js';
import { RenderLayer } from '../../internal/RenderLayer/index.js';
import { ZIndex } from '../../internal/ZIndex/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { isTestEnv } from '../../lib/currentEnvironment.js';
import { ResponsiveLayout } from '../ResponsiveLayout/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { isInstanceOf } from '../../lib/isInstanceOf.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { SidePageBody } from './SidePageBody.js';
import { SidePageContainer } from './SidePageContainer.js';
import { SidePageContext } from './SidePageContext.js';
import { SidePageFooter } from './SidePageFooter.js';
import { SidePageHeader } from './SidePageHeader.js';
import { getStyles } from './SidePage.styles.js';
export var SidePageDataTids = {
    root: 'SidePage__root',
    container: 'SidePage__container',
};
var TRANSITION_TIMEOUT = 200;
/**
 * `SidePage` — это модальное окно, которое открывается поверх основной страницы и занимает всю высоту окна браузера.
 *
 * Используйте его, когда нужно сохранить контекст и показать большое количество данных.
 *
 * Содержит в себе три компоненты: `SidePage.Header`, `SidePage.Body` и `SidePage.Footer`.
 *
 * Для отображения серой плашки в футере в компонент `Footer` необходимо передать пропс `panel`.
 */
var SidePage = /** @class */ (function (_super) {
    __extends(SidePage, _super);
    function SidePage() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            hasHeader: false,
            hasFooter: false,
            hasPanel: false,
        };
        _this.stackSubscription = null;
        _this.layout = null;
        _this.header = null;
        _this.footer = null;
        _this.rootRef = React.createRef();
        /**
         * Обновляет разметку компонента.
         * @public
         */
        _this.updateLayout = function () {
            var _a, _b;
            (_a = _this.header) === null || _a === void 0 ? void 0 : _a.update();
            (_b = _this.footer) === null || _b === void 0 ? void 0 : _b.update();
        };
        _this.getProps = createPropsGetter(SidePage_1.defaultProps);
        _this.getSidePageContextProps = function () {
            return {
                hasHeader: _this.state.hasHeader,
                hasFooter: _this.state.hasFooter,
                hasPanel: _this.state.hasPanel,
                requestClose: _this.requestClose,
                getWidth: _this.getWidth,
                updateLayout: _this.updateLayout,
                headerRef: _this.headerRef,
                footerRef: _this.footerRef,
                setHasHeader: _this.setHasHeader,
                setHasFooter: _this.setHasFooter,
                setHasPanel: _this.setHasPanel,
            };
        };
        _this.getWidth = function () {
            if (!_this.layout) {
                return 'auto';
            }
            return _this.layout.clientWidth;
        };
        _this.handleStackChange = function (stack) {
            var sidePages = stack.filter(function (x) { return isReactUIInstance(x, 'SidePage') && x.props.fromLeft === _this.props.fromLeft; });
            var currentSidePagePosition = sidePages.indexOf(_this);
            var hasMargin = sidePages.length > 1 && currentSidePagePosition === sidePages.length - 1;
            var hasShadow = sidePages.length < 3 || currentSidePagePosition > sidePages.length - 3;
            var hasBackground = ModalStack.isBlocking(_this, _this.globalObject);
            _this.setState({
                stackPosition: stack.indexOf(_this),
                hasMargin: hasMargin,
                hasShadow: hasShadow,
                hasBackground: hasBackground,
            });
        };
        _this.handleClickOutside = function (e) {
            if (_this.state.stackPosition === 0 && !(_this.props.ignoreBackgroundClick || _this.props.ignoreOutsideClick)) {
                // ignore mousedown on window scrollbar
                if (isInstanceOf(e, _this.globalObject.MouseEvent) &&
                    _this.globalObject.document &&
                    e.clientX > _this.globalObject.document.documentElement.clientWidth) {
                    return;
                }
                if (_this.props.onOutsideClick) {
                    _this.props.onOutsideClick(e);
                    if (e.defaultPrevented) {
                        return;
                    }
                }
                _this.requestClose();
            }
        };
        _this.handleKeyDown = function (e) {
            if (_this.state.stackPosition !== 0) {
                return;
            }
            if (isKeyEscape(e)) {
                e.stopPropagation();
                _this.requestClose();
            }
        };
        _this.requestClose = function () {
            if (_this.props.disableClose) {
                return;
            }
            if (_this.props.onClose) {
                _this.props.onClose();
            }
        };
        _this.headerRef = function (ref) {
            _this.header = ref;
        };
        _this.footerRef = function (ref) {
            _this.footer = ref;
        };
        _this.layoutRef = function (ref) {
            _this.layout = ref;
        };
        _this.setHasHeader = function (hasHeader) {
            if (hasHeader === void 0) { hasHeader = true; }
            _this.state.hasHeader !== hasHeader && _this.setState({ hasHeader: hasHeader });
        };
        _this.setHasFooter = function (hasFooter) {
            if (hasFooter === void 0) { hasFooter = true; }
            _this.state.hasFooter !== hasFooter && _this.setState({ hasFooter: hasFooter });
        };
        _this.setHasPanel = function (hasPanel) {
            if (hasPanel === void 0) { hasPanel = false; }
            _this.state.hasPanel !== hasPanel && _this.setState({ hasPanel: hasPanel });
        };
        return _this;
    }
    SidePage_1 = SidePage;
    SidePage.prototype.componentDidMount = function () {
        var _a, _b;
        (_b = (_a = this.globalObject).addEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, 'keydown', this.handleKeyDown);
        this.stackSubscription = ModalStack.add(this, this.handleStackChange, this.globalObject);
    };
    SidePage.prototype.componentDidUpdate = function (prevProps) {
        if (prevProps.blockBackground !== this.props.blockBackground) {
            ModalStack.rerender(this.globalObject);
            this.setState({
                hasBackground: ModalStack.isBlocking(this, this.globalObject),
            });
        }
    };
    SidePage.prototype.componentWillUnmount = function () {
        var _a, _b;
        (_b = (_a = this.globalObject).removeEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, 'keydown', this.handleKeyDown);
        if (isNonNullable(this.stackSubscription)) {
            this.stackSubscription.remove();
        }
        ModalStack.remove(this, this.globalObject);
    };
    SidePage.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return _this.renderMain();
        }));
    };
    SidePage.prototype.renderMain = function () {
        var _this = this;
        var _a = this.props, blockBackground = _a.blockBackground, onOpened = _a.onOpened;
        var disableAnimations = this.getProps().disableAnimations;
        return (React.createElement(ResponsiveLayout, null, function (_a) {
            var isMobile = _a.isMobile;
            return (React.createElement(RenderContainer, null,
                React.createElement(CommonWrapper, __assign({ rootNodeRef: _this.setRootNode }, _this.props),
                    React.createElement(ZIndex, { priority: 'Sidepage', onScroll: LayoutEvents.emit, createStackingContext: true, style: { position: 'absolute' } },
                        !isMobile && blockBackground && _this.renderShadow(),
                        React.createElement(CSSTransition, { in: true, classNames: _this.getTransitionNames(), appear: !disableAnimations, enter: !disableAnimations, exit: false, timeout: {
                                enter: TRANSITION_TIMEOUT,
                                exit: TRANSITION_TIMEOUT,
                            }, nodeRef: _this.rootRef, onEntered: onOpened }, _this.renderContainer(isMobile)),
                        isMobile && React.createElement(HideBodyVerticalScroll, null)))));
        }));
    };
    Object.defineProperty(SidePage.prototype, "isFocusLockDisabled", {
        get: function () {
            var disableFocusLock = this.getProps().disableFocusLock;
            var blockBackground = this.props.blockBackground;
            if (!blockBackground) {
                return true;
            }
            if (disableFocusLock !== undefined) {
                return disableFocusLock;
            }
            return false;
        },
        enumerable: false,
        configurable: true
    });
    SidePage.prototype.renderContainer = function (isMobile) {
        var _a, _b;
        var _c = this.props, mobileWidth = _c.mobileWidth, blockBackground = _c.blockBackground, fromLeft = _c.fromLeft, ariaLabel = _c["aria-label"];
        var _d = this.getProps(), offset = _d.offset, role = _d.role;
        var widthDesktop = this.props.width || (blockBackground ? 800 : 500);
        var widthMobile = mobileWidth || '100%';
        var width = isMobile ? widthMobile : widthDesktop;
        return (React.createElement("div", { "aria-modal": true, role: role, "aria-label": ariaLabel, "data-tid": SidePageDataTids.root, className: this.cx((_a = {},
                _a[this.styles.root()] = true,
                _a)), ref: this.rootRef, onScroll: LayoutEvents.emit, style: {
                width: width,
                right: fromLeft ? 'auto' : offset,
                left: fromLeft ? offset : 'auto',
            } },
            React.createElement(FocusLock, { disabled: this.isFocusLockDisabled, autoFocus: false, className: this.styles.focusLock() },
                React.createElement(RenderLayer, { onClickOutside: this.handleClickOutside, active: true },
                    React.createElement("div", { "data-tid": SidePageDataTids.container, className: this.cx(this.styles.wrapper(this.theme), (_b = {},
                            _b[this.styles.wrapperLeft()] = fromLeft,
                            _b[this.styles.wrapperMarginLeft()] = this.state.hasMargin && fromLeft,
                            _b[this.styles.wrapperMarginRight()] = this.state.hasMargin && !fromLeft,
                            _b[this.styles.shadow(this.theme)] = this.state.hasShadow,
                            _b)), ref: this.layoutRef },
                        React.createElement(SidePageContext.Provider, { value: this.getSidePageContextProps() }, this.props.children))))));
    };
    SidePage.prototype.renderShadow = function () {
        var _a;
        return (React.createElement("div", { className: this.styles.overlay(), onScroll: LayoutEvents.emit },
            React.createElement(HideBodyVerticalScroll, { key: "hbvs" }),
            React.createElement("div", { key: "overlay", className: this.cx((_a = {},
                    _a[this.styles.background()] = true,
                    _a[this.styles.backgroundGray(this.theme)] = this.state.hasBackground,
                    _a)) })));
    };
    SidePage.prototype.getTransitionNames = function () {
        var transition = this.props.fromLeft ? this.styles.transitionRight : this.styles.transitionLeft;
        return {
            enter: transition(),
            enterActive: this.styles.transitionActive(),
            exit: this.styles.transitionLeave(),
            exitActive: this.styles.transitionLeaveActive(),
            appear: transition(),
            appearActive: this.styles.transitionActive(),
        };
    };
    var SidePage_1;
    SidePage.__KONTUR_REACT_UI__ = 'SidePage';
    SidePage.displayName = 'SidePage';
    SidePage.Header = SidePageHeader;
    SidePage.Body = SidePageBody;
    SidePage.Footer = SidePageFooter;
    SidePage.Container = SidePageContainer;
    SidePage.defaultProps = {
        disableAnimations: isTestEnv,
        offset: 0,
        role: 'dialog',
    };
    SidePage = SidePage_1 = __decorate([
        withRenderEnvironment,
        rootNode
    ], SidePage);
    return SidePage;
}(React.Component));
export { SidePage };
//# sourceMappingURL=SidePage.js.map