"use strict";
/* eslint-disable jsx-a11y/control-has-associated-label */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
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 (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sidebar = void 0;
/* eslint-disable jsx-a11y/click-events-have-key-events */
var react_1 = __importDefault(require("react"));
var bem_react_classname_1 = require("bem-react-classname");
var icons_classic_1 = require("@alfalab/icons-classic");
var cn_1 = require("../cn");
var icon_button_1 = __importDefault(require("../icon-button"));
var popup_container_provider_1 = __importDefault(require("../popup-container-provider/popup-container-provider"));
var keyboard_code_1 = __importDefault(require("../lib/keyboard-code"));
var scrollbar_width_1 = __importDefault(require("../lib/scrollbar-width"));
var mq_1 = __importDefault(require("../mq"));
var SIDEBAR_WIDTH = 430;
var savedScrollPosition;
/**
 * Восстанавливает исходную позицию скролла
 * после закрытия сайдбара на мобильной версии.
 */
function setCurrentPosition() {
    document.body.style.top = "-" + savedScrollPosition + "px";
    document.body.scrollTop = savedScrollPosition;
    document.documentElement.scrollTop = savedScrollPosition;
}
/**
 * Изменяет класс для body. Нужен для управления скроллом
 * основного экрана при показе сайдбара.
 *
 * @param visible Управление видимостью сайдбара.
 * @param hasOverlay Управление наличием оверлея для сайдбара.
 */
function setBodyClass(_a) {
    var visible = _a.visible, hasOverlay = _a.hasOverlay;
    document.body.classList[visible ? 'add' : 'remove']('sidebar-visible');
    if (hasOverlay) {
        document.body.classList[visible ? 'add' : 'remove']('sidebar-overlay');
    }
}
/**
 * Обрабатывает событие скролла на body,
 * сохраняя scrollTop для последующего использования в сайдбаре.
 */
function handleBodyScroll() {
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop) {
        savedScrollPosition = scrollTop;
    }
}
/**
 * Компонент боковой панели aka холодильник.
 */
var Sidebar = /** @class */ (function (_super) {
    __extends(Sidebar, _super);
    function Sidebar() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.cn = bem_react_classname_1.createCn('sidebar');
        _this.state = {
            isMobile: false,
        };
        _this.handleMqMatchChange = function (isMatched) {
            _this.setState({ isMobile: isMatched });
        };
        _this.handleClose = function (event) {
            if (_this.props.onCloserClick) {
                if (_this.state.isMobile) {
                    document.body.scrollTop = savedScrollPosition;
                    document.documentElement.scrollTop = savedScrollPosition;
                }
                _this.props.onCloserClick(event);
            }
        };
        _this.handleKeyDown = function (event) {
            switch (event.which) {
                case keyboard_code_1.default.ESCAPE:
                    event.preventDefault();
                    _this.handleClose(event);
                    break;
            }
        };
        return _this;
    }
    Sidebar.prototype.componentDidMount = function () {
        this.styleBodyRightMargin();
        setBodyClass({ visible: this.props.visible, hasOverlay: this.props.hasOverlay });
        if (this.props.visible) {
            window.addEventListener('keydown', this.handleKeyDown);
        }
        window.addEventListener('scroll', handleBodyScroll);
    };
    Sidebar.prototype.componentDidUpdate = function () {
        this.styleBodyRightMargin();
        setBodyClass({ visible: this.props.visible, hasOverlay: this.props.hasOverlay });
        if (this.state.isMobile) {
            setCurrentPosition();
        }
        if (this.props.visible) {
            window.addEventListener('keydown', this.handleKeyDown);
        }
        else {
            window.removeEventListener('keydown', this.handleKeyDown);
        }
    };
    Sidebar.prototype.componentWillUnmount = function () {
        setBodyClass({ visible: false, hasOverlay: this.props.hasOverlay });
        if (this.state.isMobile) {
            setCurrentPosition();
        }
        window.removeEventListener('keydown', this.handleKeyDown);
        window.removeEventListener('scroll', handleBodyScroll);
    };
    Sidebar.prototype.render = function () {
        var _a = this.props, hasCloser = _a.hasCloser, children = _a.children, visible = _a.visible, headerContent = _a.headerContent, footerContent = _a.footerContent, hasOverlay = _a.hasOverlay, width = _a.width;
        var offset = visible ? scrollbar_width_1.default() : 0;
        var style = { width: this.state.isMobile ? '100%' : width + offset + "px" };
        var contentStyle = { marginRight: this.state.isMobile ? 0 : "-" + offset + "px" };
        return (react_1.default.createElement(popup_container_provider_1.default, { className: this.cn({ visible: visible }), style: style, "data-test-id": this.props['data-test-id'] },
            react_1.default.createElement("div", { role: "button", tabIndex: -1, className: this.cn('overlay', { visible: visible && hasOverlay }), onClick: this.handleClose }),
            react_1.default.createElement(mq_1.default, { query: "--small-only", onMatchChange: this.handleMqMatchChange }),
            react_1.default.createElement("div", { className: this.cn('inner'), id: this.props.id },
                react_1.default.createElement("header", { className: this.cn('header') },
                    hasCloser
                        && (react_1.default.createElement("div", { className: this.cn('closer') },
                            react_1.default.createElement(icon_button_1.default, { size: this.state.isMobile ? 'm' : 'l', onClick: this.handleClose },
                                react_1.default.createElement(icons_classic_1.CloseLIcon, { className: this.cn('icon') })))),
                    headerContent
                        ? this.renderHeaderContent()
                        : null),
                react_1.default.createElement("div", { style: contentStyle, className: this.cn('content') }, children),
                react_1.default.createElement("footer", { className: this.cn('footer') }, footerContent))));
    };
    Sidebar.prototype.renderHeaderContent = function () {
        return (react_1.default.createElement("div", { className: this.cn('header-content') }, this.props.headerContent));
    };
    Sidebar.prototype.styleBodyRightMargin = function () {
        var offset = this.props.visible ? scrollbar_width_1.default() : 0;
        document.body.style.marginRight = !this.state.isMobile && this.props.hasOverlay ? offset + "px" : '0';
    };
    Sidebar.defaultProps = {
        hasOverlay: true,
        hasCloser: true,
        width: SIDEBAR_WIDTH,
    };
    return Sidebar;
}(react_1.default.PureComponent));
exports.Sidebar = Sidebar;
exports.default = cn_1.withTheme(Sidebar);

//# sourceMappingURL=sidebar.js.map
