'use strict';
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 __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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
import React, { cloneElement } from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Modal } from 'react-bootstrap';
import { getScrollbarWidth, closePopup, restorePopupVisibility, popupContainerId } from '../utils';
import { KeyCodes } from '../../../utils/constants';
import tabbable from 'tabbable';
import lang from '../../../lang/common/index-en_US';
var Popup = /** @class */ (function (_super) {
    __extends(Popup, _super);
    function Popup(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.handleHeaderRef = function (ref) {
            if (!ref) {
                return;
            }
            var $modalHeader = findDOMNode(ref);
            if (!$modalHeader) {
                return;
            }
            var $closeButton = $modalHeader.querySelector("button[class = 'close']");
            if ($closeButton) {
                $closeButton.setAttribute('data-test-automation-id', 'closeButton');
            }
        };
        _this.trapFocus = function (event) {
            if (event.keyCode === KeyCodes.TAB) {
                var activeElement = document.activeElement;
                var modalContentNode = _this.modalContentRef.current;
                var tabbableNodes = tabbable(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();
                    }
                }
            }
        };
        _this.hideModal = function () {
            if (_this.props.onClose) {
                _this.props.onClose();
            }
            else {
                Popup.close();
            }
        };
        if (!Popup.styleSheet) {
            Popup.addStyleSheet();
        }
        Popup.stack.push(_this);
        Popup.updateBodyClass();
        _this.modalContentRef = React.createRef();
        _this.hideModal = _this.hideModal.bind(_this);
        return _this;
    }
    Popup.close = function () {
        if (Popup.stack.length) {
            var popup = Popup.stack[Popup.stack.length - 1];
            if (popup.props.onHide) {
                popup.props.onHide();
                return;
            }
        }
        closePopup();
    };
    Popup.addStyleSheet = function () {
        var width = 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 () {
        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, '');
        }
    };
    Popup.prototype.componentWillUnmount = function () {
        var index = Popup.stack.indexOf(this);
        if (index !== -1) {
            Popup.stack.splice(index, 1);
            Popup.updateBodyClass();
            setImmediate(restorePopupVisibility);
        }
    };
    Popup.prototype.render = function () {
        // Extract own props to make it safe to pass Modal props down
        var _a = this.props, testAutomationId = _a.testAutomationId, stackable = _a.stackable, noPadding = _a.noPadding, noBottomPadding = _a.noBottomPadding, noHeaderPadding = _a.noHeaderPadding, borderedTitle = _a.borderedTitle, closeButton = _a.closeButton, keyboard = _a.keyboard, closeLabel = _a.closeLabel, className = _a.className, header = _a.header, footer = _a.footer, title = _a.title, onClose = _a.onClose, children = _a.children, ariaLabelledBy = _a["aria-labelledby"], ariaDescribedBy = _a["aria-describedby"], shouldDeriveDescFromBody = _a.shouldDeriveDescFromBody, props = __rest(_a, ["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.createElement(Modal.Footer, { "data-test-automation-id": "popupFooter" }, footer);
        }
        if (title) {
            title = (React.createElement(Modal.Title, { role: "presentation", "data-test-automation-id": "title", className: classnames({ 'bordered-modal-title': borderedTitle }) },
                React.createElement("span", { id: titleId }, title)));
        }
        if (!title && header) {
            header = cloneElement(header, { id: titleId });
        }
        var supportEscClose = keyboard || closeButton;
        return (React.createElement(Modal, __assign({ keyboard: supportEscClose, onKeyDown: this.trapFocus, show: true, "data-test-automation-id": testAutomationId, container: document.getElementById(popupContainerId) }, props, { "aria-labelledby": ariaLabelledBy, "aria-describedby": ariaDescribedBy, role: "document", enforceFocus: false, onHide: this.hideModal, className: classnames('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.createElement("div", { ref: this.modalContentRef },
                React.createElement(Modal.Header, { ref: this.handleHeaderRef, "data-test-automation-id": "popupHeader", closeButton: true, closeLabel: closeLabel },
                    title,
                    header),
                React.createElement(Modal.Body, { id: contentId, "data-test-automation-id": "popupContent" }, children),
                footer)));
    };
    Popup.stack = [];
    Popup.propTypes = {
        children: PropTypes.node,
        className: PropTypes.string,
        stackable: PropTypes.bool,
        borderedTitle: PropTypes.bool,
        noPadding: PropTypes.bool,
        noBottomPadding: PropTypes.bool,
        noHeaderPadding: PropTypes.bool,
        closeButton: PropTypes.bool,
        closeLabel: PropTypes.string,
        title: PropTypes.string,
        testAutomationId: PropTypes.string,
        header: PropTypes.node,
        footer: PropTypes.node,
        onClose: PropTypes.func,
        'aria-labelledby': PropTypes.string,
        'aria-describedby': PropTypes.string,
        shouldDeriveDescFromBody: PropTypes.bool,
        keyboard: PropTypes.bool
    };
    Popup.defaultProps = {
        children: null,
        className: null,
        testAutomationId: 'popup',
        borderedTitle: false,
        noPadding: false,
        noBottomPadding: false,
        noHeaderPadding: false,
        title: '',
        closeButton: true,
        get closeLabel() {
            return lang.CLOSE;
        },
        header: null,
        footer: null,
        stackable: false,
        backdrop: 'static',
        onClose: null,
        'aria-labelledby': null,
        'aria-describedby': null,
        shouldDeriveDescFromBody: false,
        keyboard: false
    };
    return Popup;
}(React.Component));
export { Popup };
//# sourceMappingURL=Popup.js.map