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 { getRandomID } from '../../lib/utils.js';
import { isKeyArrowVertical, isKeyEnter, isKeyEscape, isKeySpace, someKeys, } from '../../lib/events/keyboard/identifiers.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { ThemeFactory } from '../../lib/theming/ThemeFactory.js';
import { Popup, PopupIds } from '../Popup/index.js';
import { RenderLayer } from '../RenderLayer/index.js';
import { CommonWrapper } from '../CommonWrapper/index.js';
import { responsiveLayout } from '../../components/ResponsiveLayout/decorator.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { Menu } from '../Menu/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { isValidPositions } from './validatePositions.js';
import { getStyles } from './PopupMenu.styles.js';
import { PopupMenuDataTids } from './tids.js';
export * from './tids.js';
export var PopupMenuType = {
    Dropdown: 'dropdown',
    Tooltip: 'tooltip',
};
var Positions = [
    'top left',
    'top center',
    'top right',
    'right top',
    'right middle',
    'right bottom',
    'bottom left',
    'bottom center',
    'bottom right',
    'left top',
    'left middle',
    'left bottom',
];
var PopupMenu = /** @class */ (function (_super) {
    __extends(PopupMenu, _super);
    function PopupMenu() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.rootId = PopupIds.root + getRandomID();
        _this.getProps = createPropsGetter(PopupMenu_1.defaultProps);
        _this.state = {
            menuVisible: false,
            firstItemShouldBeSelected: false,
        };
        _this.captionWrapper = null;
        _this.savedFocusableElement = null;
        _this.menu = null;
        _this.open = function () { return _this.showMenu(); };
        _this.close = function () { return _this.hideMenu(); };
        _this.menuRef = function (element) {
            _this.menu = element;
        };
        _this.handleOpen = function () {
            if (_this.menu) {
                _this.menu.focus();
            }
        };
        _this.passPropsToCaption = function (caption) {
            var _a;
            if (typeof caption === 'string' || typeof caption === 'number') {
                return caption;
            }
            return React.cloneElement(caption, {
                id: _this.props.id,
                'aria-controls': (_a = _this.props.popupMenuId) !== null && _a !== void 0 ? _a : _this.rootId,
                'aria-expanded': _this.state.menuVisible ? 'true' : 'false',
                'aria-label': _this.props['aria-label'],
            });
        };
        _this.renderCaption = function () {
            if (typeof _this.props.caption === 'function') {
                var caption = _this.props.caption({
                    opened: _this.state.menuVisible,
                    openMenu: _this.showMenu,
                    closeMenu: _this.hideMenu,
                    toggleMenu: _this.toggleMenu,
                    corners: _this.props.corners,
                });
                return (React.createElement("span", { "data-tid": PopupMenuDataTids.caption, className: _this.styles.caption(), ref: function (element) {
                        _this.captionWrapper = element;
                    } }, _this.passPropsToCaption(caption)));
            }
            return (React.createElement("span", { "data-tid": PopupMenuDataTids.caption, onClick: _this.handleCaptionClick, onKeyDown: _this.handleCaptionKeyDown, ref: function (element) {
                    _this.captionWrapper = element;
                }, className: _this.styles.caption() }, _this.passPropsToCaption(_this.props.caption)));
        };
        _this.hideMenuWithoutFocusing = function () { return _this.hideMenu(); };
        _this.showMenu = function (firstItemShouldBeSelected) {
            _this.saveFocus();
            _this.setState({
                menuVisible: true,
                firstItemShouldBeSelected: firstItemShouldBeSelected,
            }, function () {
                _this.handleChangeMenuVisible(false);
            });
        };
        _this.hideMenu = function (restoreFocus) {
            _this.setState({
                menuVisible: false,
                firstItemShouldBeSelected: false,
            }, function () {
                _this.handleChangeMenuVisible(!!restoreFocus);
            });
        };
        _this.toggleMenu = function () {
            _this.state.menuVisible ? _this.hideMenu() : _this.showMenu();
        };
        _this.handleCaptionClick = function () {
            _this.toggleMenu();
        };
        _this.handleCaptionKeyDown = function (e) {
            if (someKeys(isKeyEnter, isKeySpace, isKeyArrowVertical)(e)) {
                e.preventDefault();
                _this.showMenu(true);
            }
        };
        _this.handleKeyDown = function (e) {
            if (isKeyEscape(e)) {
                var restoreFocus = true;
                _this.hideMenu(restoreFocus);
            }
        };
        _this.saveFocus = function () {
            if (_this.globalObject.document) {
                _this.savedFocusableElement = _this.globalObject.document.activeElement;
            }
        };
        _this.restoreFocus = function () {
            if (_this.savedFocusableElement) {
                _this.savedFocusableElement.focus();
                _this.savedFocusableElement = null;
            }
        };
        _this.handleChangeMenuVisible = function (focusShouldBeRestored) {
            if (focusShouldBeRestored) {
                _this.restoreFocus();
            }
            if (_this.state.menuVisible && _this.props.onOpen) {
                _this.props.onOpen();
            }
            if (!_this.state.menuVisible && _this.props.onClose) {
                _this.props.onClose();
            }
            if (typeof _this.props.onChangeMenuState === 'function') {
                _this.props.onChangeMenuState(_this.state.menuVisible, focusShouldBeRestored);
            }
        };
        _this.handleItemSelection = function (event) {
            if (event.isDefaultPrevented()) {
                return;
            }
            if (event.type === 'keydown') {
                event.preventDefault();
            }
            var restoreFocus = event.type === 'keydown';
            _this.hideMenu(restoreFocus);
        };
        return _this;
    }
    PopupMenu_1 = PopupMenu;
    PopupMenu.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            return (React.createElement(ThemeContext.Provider, { value: ThemeFactory.create({
                    menuOffsetY: theme.popupMenuMenuOffsetY,
                }, theme) }, _this.renderMain()));
        }));
    };
    PopupMenu.prototype.renderMain = function () {
        var _a;
        var _b = this.getProps(), popupHasPin = _b.popupHasPin, disableAnimations = _b.disableAnimations;
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
            React.createElement(RenderLayer, { onClickOutside: this.hideMenuWithoutFocusing, onFocusOutside: this.hideMenuWithoutFocusing, active: this.state.menuVisible },
                React.createElement("div", { "data-tid": PopupMenuDataTids.root, className: this.styles.container(), style: { width: this.props.width } },
                    this.renderCaption(),
                    this.captionWrapper && this.props.children && (React.createElement(Popup, { id: (_a = this.props.popupMenuId) !== null && _a !== void 0 ? _a : this.rootId, anchorElement: this.captionWrapper, opened: this.state.menuVisible, hasShadow: true, margin: this.props.popupMargin, hasPin: popupHasPin, pinOffset: this.props.popupPinOffset, positions: this.getPositions(), disableAnimations: disableAnimations, onOpen: this.handleOpen, mobileOnCloseRequest: this.hideMenu, width: this.isMobileLayout ? 'auto' : this.props.menuWidth || 'auto' },
                        React.createElement(Menu, { maxHeight: this.isMobileLayout ? 'none' : this.props.menuMaxHeight || 'none', onKeyDown: this.handleKeyDown, onItemClick: this.handleItemSelection, preventIconsOffset: this.props.preventIconsOffset, cyclicSelection: false, ref: this.menuRef, initialSelectedItemIndex: this.state.firstItemShouldBeSelected ? 0 : -1, header: this.props.header, footer: this.props.footer }, this.props.children)))))));
    };
    PopupMenu.prototype.getPositions = function () {
        var positions = this.getProps().positions;
        if (positions && isValidPositions(positions)) {
            return positions;
        }
        return Positions;
    };
    var PopupMenu_1;
    PopupMenu.__KONTUR_REACT_UI__ = 'PopupMenu';
    PopupMenu.displayName = 'PopupMenu';
    PopupMenu.defaultProps = {
        positions: Positions,
        type: PopupMenuType.Tooltip,
        popupHasPin: true,
        disableAnimations: false,
    };
    PopupMenu.Type = PopupMenuType;
    PopupMenu = PopupMenu_1 = __decorate([
        withRenderEnvironment,
        rootNode,
        responsiveLayout
    ], PopupMenu);
    return PopupMenu;
}(React.Component));
export { PopupMenu };
//# sourceMappingURL=PopupMenu.js.map