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 { isBrowser } from '../../lib/globalObject.js';
import { isKeyArrowDown, isKeyArrowUp, isKeyEnter } from '../../lib/events/keyboard/identifiers.js';
import { MenuSeparator } from '../../components/MenuSeparator/index.js';
import { ThemeFactory } from '../../lib/theming/ThemeFactory.js';
import { getDOMRect } from '../../lib/dom/getDOMRect.js';
import { responsiveLayout } from '../../components/ResponsiveLayout/decorator.js';
import { isNonNullable } from '../../lib/utils.js';
import { ScrollContainer } from '../../components/ScrollContainer/index.js';
import { MenuItemDataTids } from '../../components/MenuItem/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { getRootNode, rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { isInstanceOf } from '../../lib/isInstanceOf.js';
import { CommonWrapper } from '../CommonWrapper/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './Menu.styles.js';
import { MenuNavigation } from './MenuNavigation.js';
import { MenuContext } from './MenuContext.js';
export var MenuDataTids = {
    root: 'Menu__root',
};
var Menu = /** @class */ (function (_super) {
    __extends(Menu, _super);
    function Menu() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getProps = createPropsGetter(Menu_1.defaultProps);
        _this.state = {
            maxHeight: _this.getProps().maxHeight || 'none',
            scrollState: 'top',
            enableIconPadding: false,
        };
        _this.unmounted = false;
        _this.contentRef = React.createRef();
        _this.menuNavigation = new MenuNavigation(_this.contentRef, MenuItemDataTids.content);
        _this.focusOnRootElement = function () {
            var rootNode = getRootNode(_this);
            if (isInstanceOf(rootNode, _this.globalObject.HTMLElement)) {
                rootNode === null || rootNode === void 0 ? void 0 : rootNode.focus();
            }
        };
        _this.renderHeader = function () {
            var _a;
            return (React.createElement("div", { className: _this.cx((_a = {},
                    _a[_this.styles.wrapper()] = true,
                    _a[_this.styles.headerWrapper()] = true,
                    _a)), ref: function (el) {
                    _this.header = el;
                } },
                React.createElement("div", { className: _this.styles.contentWrapper() }, _this.props.header),
                React.createElement("div", { className: _this.styles.menuSeparatorWrapper(_this.theme) }, _this.state.scrollState !== 'top' && _this.renderMenuSeparatorWithNoMargin())));
        };
        _this.renderFooter = function () {
            var _a;
            return (React.createElement("div", { className: _this.cx((_a = {},
                    _a[_this.styles.wrapper()] = true,
                    _a[_this.styles.footerWrapper()] = true,
                    _a)), ref: function (el) {
                    _this.footer = el;
                } },
                React.createElement("div", { className: _this.styles.menuSeparatorWrapper(_this.theme) }, _this.state.scrollState !== 'bottom' && _this.renderMenuSeparatorWithNoMargin()),
                React.createElement("div", { className: _this.styles.contentWrapper() }, _this.props.footer)));
        };
        _this.renderMenuSeparatorWithNoMargin = function () {
            return (React.createElement(ThemeContext.Provider, { value: ThemeFactory.create({ menuSeparatorMarginY: '0' }, _this.theme) },
                React.createElement(MenuSeparator, null)));
        };
        _this.setInitialSelection = function () {
            for (var i = _this.getProps().initialSelectedItemIndex; i > -1; i--) {
                _this.down();
            }
        };
        _this.shouldRecalculateMaxHeight = function (prevProps) {
            var _a = _this.props, header = _a.header, footer = _a.footer, children = _a.children;
            var maxHeight = _this.getProps().maxHeight;
            var prevMaxHeight = prevProps.maxHeight;
            var prevHeader = prevProps.header;
            var prevFooter = prevProps.footer;
            var prevChildrenCount = React.Children.count(prevProps.children);
            return (maxHeight !== prevMaxHeight ||
                footer !== prevFooter ||
                header !== prevHeader ||
                React.Children.count(children) !== prevChildrenCount);
        };
        _this.calculateMaxHeight = function () {
            var _a, _b;
            var maxHeight = _this.getProps().maxHeight;
            var parsedMaxHeight = maxHeight;
            var rootNode = getRootNode(_this);
            if (typeof maxHeight === 'string' && isBrowser(_this.globalObject) && rootNode) {
                var rootElementMaxHeight = (_b = (_a = _this.globalObject).getComputedStyle) === null || _b === void 0 ? void 0 : _b.call(_a, rootNode).maxHeight;
                if (rootElementMaxHeight) {
                    parsedMaxHeight = parseFloat(rootElementMaxHeight);
                }
            }
            var calculatedMaxHeight = typeof parsedMaxHeight === 'number'
                ? parsedMaxHeight +
                    ((_this.header && getDOMRect(_this.header).height) || 0) +
                    ((_this.footer && getDOMRect(_this.footer).height) || 0)
                : maxHeight;
            _this.setState({
                maxHeight: calculatedMaxHeight || 'none',
            });
        };
        _this.refScrollContainer = function (scrollContainer) {
            _this.scrollContainer = scrollContainer;
        };
        _this.scrollToSelected = function () {
            var highlightedItem = _this.menuNavigation.highlightedItem;
            if (_this.scrollContainer && highlightedItem) {
                var rootNode_1 = getRootNode(highlightedItem);
                // TODO: Remove this check once IF-647 is resolved
                if (isInstanceOf(rootNode_1, _this.globalObject.HTMLElement)) {
                    _this.scrollContainer.scrollTo(rootNode_1);
                }
            }
        };
        _this.scrollToTop = function () {
            if (_this.scrollContainer) {
                _this.scrollContainer.scrollToTop();
            }
        };
        _this.scrollToBottom = function () {
            if (_this.scrollContainer) {
                _this.scrollContainer.scrollToBottom();
            }
        };
        _this.scroll = function (nextIndex) {
            var _a, _b, _c;
            switch (nextIndex) {
                case 0:
                    (_a = _this.scrollToTop) === null || _a === void 0 ? void 0 : _a.call(_this);
                    break;
                case _this.menuNavigation.items.length - 1:
                    (_b = _this.scrollToBottom) === null || _b === void 0 ? void 0 : _b.call(_this);
                    break;
                default:
                    (_c = _this.scrollToSelected) === null || _c === void 0 ? void 0 : _c.call(_this);
            }
        };
        _this.handleKeyDown = function (event) {
            if (typeof _this.props.onKeyDown === 'function') {
                _this.props.onKeyDown(event);
            }
            if (event.defaultPrevented) {
                return;
            }
            if (isKeyArrowUp(event)) {
                event.preventDefault();
                _this.up();
            }
            else if (isKeyArrowDown(event)) {
                event.preventDefault();
                _this.down();
            }
            else if (isKeyEnter(event)) {
                _this.menuNavigation.select(event);
            }
        };
        _this.getStyle = function (props) {
            if (props.align === 'right') {
                return {
                    maxWidth: props.width,
                    minWidth: props.width,
                    maxHeight: _this.state.maxHeight,
                };
            }
            return {
                width: props.width,
                maxHeight: _this.state.maxHeight,
            };
        };
        _this.handleScrollStateChange = function (scrollState) {
            if (_this.state.scrollState !== scrollState) {
                _this.setState({ scrollState: scrollState });
            }
        };
        _this.setEnableIconPadding = function (isIconPaddingEnabled) {
            !_this.getProps().preventIconsOffset && _this.setState({ enableIconPadding: isIconPaddingEnabled });
        };
        return _this;
    }
    Menu_1 = Menu;
    Menu.prototype.componentWillUnmount = function () {
        this.unmounted = true;
    };
    Menu.prototype.componentDidMount = function () {
        this.setInitialSelection();
        this.calculateMaxHeight();
        this.unmounted = false;
    };
    Menu.prototype.componentDidUpdate = function (prevProps) {
        if (this.shouldRecalculateMaxHeight(prevProps)) {
            this.calculateMaxHeight();
        }
        if (prevProps.maxHeight !== this.getProps().maxHeight) {
            this.setState({
                maxHeight: this.props.maxHeight || 'none',
            });
        }
    };
    Menu.prototype.focus = function () {
        this.focusOnRootElement();
    };
    Menu.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();
        }));
    };
    /**
     * @public
     */
    Menu.prototype.up = function () {
        this.move(-1);
    };
    /**
     * @public
     */
    Menu.prototype.down = function () {
        this.move(1);
    };
    /**
     * @public
     */
    Menu.prototype.enter = function (event) {
        var _a;
        (_a = this.menuNavigation.highlightedItem) === null || _a === void 0 ? void 0 : _a.navigate();
        return this.menuNavigation.select(event);
    };
    /**
     * @public
     */
    Menu.prototype.reset = function () {
        this.menuNavigation.reset();
    };
    /**
     * @public
     */
    Menu.prototype.hasHighlightedItem = function () {
        return !!this.menuNavigation.highlightedItem;
    };
    Menu.prototype.highlightItem = function (index) {
        this.menuNavigation.highlightByIndex(index);
    };
    Menu.prototype.renderMain = function () {
        var _a, _b;
        if (this.isEmpty()) {
            return null;
        }
        var _c = this.getProps(), hasMargin = _c.hasMargin, maxHeight = _c.maxHeight, preventWindowScroll = _c.preventWindowScroll;
        var offsetY = {
            top: "".concat(this.theme.scrollContainerScrollBarOffsetY),
            right: 0,
            bottom: "".concat(this.theme.scrollContainerScrollBarOffsetY),
        };
        var isMobile = this.isMobileLayout;
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
            React.createElement("div", { "data-tid": MenuDataTids.root, className: this.cx(getAlignRightClass(this.props, this.cx, this.styles), (_a = {},
                    _a[this.styles.root(this.theme)] = true,
                    _a[this.styles.hasMargin(this.theme)] = hasMargin,
                    _a[this.styles.mobileRoot(this.theme)] = isMobile,
                    _a[this.styles.shadow(this.theme)] = !isMobile,
                    _a)), style: this.getStyle(this.props), id: this.props.id, onKeyDown: this.handleKeyDown, tabIndex: 0 },
                this.props.header && this.renderHeader(),
                React.createElement(ScrollContainer, { ref: this.refScrollContainer, maxHeight: maxHeight, preventWindowScroll: preventWindowScroll, onScrollStateChangeY: this.handleScrollStateChange, disabled: this.props.disableScrollContainer, offsetY: offsetY },
                    React.createElement("div", { className: this.cx((_b = {},
                            _b[this.styles.scrollContainer(this.theme)] = true,
                            _b[this.styles.scrollContainerMobile(this.theme)] = isMobile,
                            _b)), ref: this.contentRef },
                        React.createElement(MenuContext.Provider, { value: {
                                navigation: this.menuNavigation,
                                onItemClick: this.props.onItemClick,
                                enableIconPadding: this.state.enableIconPadding,
                                setEnableIconPadding: this.setEnableIconPadding,
                            } }, this.props.children))),
                this.props.footer && this.renderFooter())));
    };
    Menu.prototype.move = function (step) {
        if (this.unmounted) {
            // NOTE workaround, because `ComboBox` call `process.nextTick` in reducer
            return;
        }
        var nextIndex = this.menuNavigation.move(step, this.getProps().cyclicSelection);
        this.scroll(nextIndex);
    };
    Menu.prototype.isEmpty = function () {
        var children = this.props.children;
        return !children || !childrenToArray(children).filter(isNonNullable).length;
    };
    var Menu_1;
    Menu.__KONTUR_REACT_UI__ = 'Menu';
    Menu.displayName = 'Menu';
    Menu.defaultProps = {
        align: 'left',
        width: 'auto',
        maxHeight: 300,
        hasMargin: true,
        preventWindowScroll: true,
        cyclicSelection: true,
        initialSelectedItemIndex: -1,
    };
    Menu = Menu_1 = __decorate([
        withRenderEnvironment,
        responsiveLayout,
        rootNode
    ], Menu);
    return Menu;
}(React.PureComponent));
export { Menu };
function childrenToArray(children) {
    var ret = [];
    // Use forEach instead of map to avoid cloning for key unifying.
    React.Children.forEach(children, function (child) {
        ret.push(child);
    });
    return ret;
}
var getAlignRightClass = function (props, cx, styles) {
    if (props.align === 'right') {
        return cx(styles.alignRight());
    }
    return null;
};
//# sourceMappingURL=Menu.js.map