'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;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importStar(require("react"));
var react_dom_1 = __importDefault(require("react-dom"));
var prop_types_1 = __importDefault(require("prop-types"));
var classnames_1 = __importDefault(require("classnames"));
var lodash_1 = require("lodash");
var react_bootstrap_1 = require("react-bootstrap");
var constants_1 = require("../../utils/constants");
var __1 = require("..");
var functions_1 = require("../utils/functions");
// export const tabPanelStyle: TabPanelStyle;
exports.TAB_PANEL_STYLES = {
    TABS: 'tabs',
    PILLS: 'pills',
    MENU: 'menu'
};
exports.TAB_PANEL_ITEM_ROLES = {
    menuitem: 'menuitem',
    tab: 'tab'
};
var TabPanel = /** @class */ (function (_super) {
    __extends(TabPanel, _super);
    function TabPanel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            focusedItemIndex: 0,
            isAnyDropdownOpen: false,
            isDropdownOpen: false,
            dropdownOpenStatuses: {},
            panelTabIndex: 0 // init with 0 to be able to get focus from another elements
        };
        _this.isStyledAsTab = function () {
            var _a = _this.props, bsStyle = _a.bsStyle, activeKey = _a.activeKey;
            return bsStyle === exports.TAB_PANEL_STYLES.TABS || (activeKey || activeKey === 0);
        };
        _this.setFocusedItemByIndex = function (index) {
            var rawChildren = _this.props.children;
            var children = functions_1.cleanEmptyChildren(rawChildren);
            if (index !== -1 && !children[index].props.disabled) {
                _this.setState({
                    focusedItemIndex: index
                });
            }
        };
        _this.handleClick = function (event) {
            var tabPanelNode = react_dom_1.default.findDOMNode(_this);
            var childNode = event.target.parentNode;
            var index = TabPanel.getChildIndex(tabPanelNode, childNode);
            _this.setFocusedItemByIndex(index);
        };
        _this.handleKeyDown = function (event) {
            var rawChildren = _this.props.children;
            var children = functions_1.cleanEmptyChildren(rawChildren);
            var _a = _this.state, focusedItemIndex = _a.focusedItemIndex, isAnyDropdownOpen = _a.isAnyDropdownOpen;
            var focusedTab = children[focusedItemIndex];
            switch (event.keyCode) {
                case constants_1.KeyCodes.ARROW_LEFT:
                case constants_1.KeyCodes.ARROW_UP:
                    if (!isAnyDropdownOpen) {
                        var previousTab = _this.getPreviousTab();
                        _this.setFocusedItemByIndex(previousTab);
                    }
                    break;
                case constants_1.KeyCodes.ARROW_RIGHT:
                    if (!isAnyDropdownOpen) {
                        var nextTab = _this.getNextTab();
                        _this.setFocusedItemByIndex(nextTab);
                    }
                    break;
                case constants_1.KeyCodes.ARROW_DOWN:
                    if (!isAnyDropdownOpen && !TabPanel.isItemOfDropdownType(focusedTab)) {
                        var nextTab = _this.getNextTab();
                        _this.setFocusedItemByIndex(nextTab);
                    }
                    break;
                case constants_1.KeyCodes.TAB:
                    var activeItemIndex = _this.getActiveItemIndex();
                    if (activeItemIndex >= 0 &&
                        ((activeItemIndex < focusedItemIndex && event.shiftKey) ||
                            (activeItemIndex > focusedItemIndex && !event.shiftKey))) {
                        _this.setFocusedItemByIndex(activeItemIndex);
                        event.preventDefault();
                    }
                    break;
                case constants_1.KeyCodes.ENTER:
                case constants_1.KeyCodes.SPACE:
                    if (!isAnyDropdownOpen && TabPanel.isItemCanBeFocusedWithKeyboard(focusedTab)) {
                        _this.setActiveItem(focusedTab, event);
                        event.preventDefault();
                    }
                    break;
            }
        };
        _this.setActiveItem = function (focusedTab, event) {
            var focusedItem;
            var target = event.target;
            if (TabPanel.isItemOfTabItemType(focusedTab)) {
                focusedItem = focusedTab;
            }
            else {
                var navDropdownNode = target.parentNode.parentNode;
                var index = TabPanel.getChildIndex(navDropdownNode, target);
                var children = functions_1.cleanEmptyChildren(focusedTab.props.children);
                focusedItem = children[index];
            }
            if (lodash_1.isEmpty(focusedItem)) {
                return;
            }
            var activeTabPath = TabPanel.getItemPath(focusedItem);
            _this.activatePath(activeTabPath);
            var _a = focusedItem.props, eventKey = _a.eventKey, onClick = _a.onClick, onSelect = _a.onSelect;
            if (onSelect) {
                onSelect(eventKey, event);
            }
            if (onClick) {
                onClick();
            }
        };
        _this.activatePath = function (activeTabPath) {
            if (activeTabPath) {
                _this.context.router.push(activeTabPath);
            }
        };
        _this.handleFocus = function (event) {
            var focusedItemIndex = _this.state.focusedItemIndex;
            var tabPanelNode = react_dom_1.default.findDOMNode(_this);
            if (tabPanelNode === event.target) {
                _this.focusToItemNodeByIndex(focusedItemIndex);
            }
        };
        _this.handleFocusOut = function (event) {
            // this allows to get a focus to the panel from another elements after it looses a focus
            _this.setState({
                panelTabIndex: 0
            });
        };
        _this.handleDropdownToggle = function (dropdownId, isOpen) {
            _this.setState(function (state) {
                var isAnyDropdownOpen;
                var dropdownOpenStatuses = state.dropdownOpenStatuses;
                dropdownOpenStatuses[dropdownId] = isOpen;
                isAnyDropdownOpen = lodash_1.includes(dropdownOpenStatuses, true);
                return {
                    dropdownOpenStatuses: dropdownOpenStatuses,
                    isAnyDropdownOpen: isAnyDropdownOpen
                };
            });
        };
        return _this;
    }
    TabPanel.getChildIndex = function (containerNode, childNode) {
        var index = -1;
        var childrenArray = Array.from(containerNode.children);
        while (index === -1 && childNode !== null) {
            index = childrenArray.indexOf(childNode);
            childNode = childNode.parentNode;
        }
        return index;
    };
    TabPanel.getItemPath = function (item) {
        if (lodash_1.isEmpty(item) || lodash_1.isEmpty(item.props)) {
            return '';
        }
        var to = item.props.to;
        return (to && (to.pathname || to)) || '';
    };
    TabPanel.isItemCanBeFocusedWithKeyboard = function (item) {
        var isAllowedByDefault = TabPanel.isItemOfDropdownType(item) || TabPanel.isItemOfTabItemType(item);
        return isAllowedByDefault || item.props.role in exports.TAB_PANEL_ITEM_ROLES;
    };
    TabPanel.isItemOfDropdownType = function (item) {
        return item && functions_1.isElementHasType(item, __1.NavDropdown);
    };
    TabPanel.isItemOfTabItemType = function (item) {
        return item && functions_1.isElementHasType(item, __1.TabItem);
    };
    TabPanel.prototype.getChildContext = function () {
        return {
            isStyledAsTab: this.isStyledAsTab
        };
    };
    TabPanel.prototype.componentDidMount = function () {
        this.focusActiveItem();
        // we need to handle focusout instead of onblur, see more here: https://github.com/facebook/react/issues/6410
        var tabPanel = react_dom_1.default.findDOMNode(this);
        tabPanel.addEventListener('focusout', this.handleFocusOut);
    };
    TabPanel.prototype.componentDidUpdate = function (previousProps, previousState) {
        if (this.isStyledAsTab()) {
            var previousChildren = previousProps.children;
            var previousFocusedItemIndex = previousState.focusedItemIndex;
            var children = this.props.children;
            var _a = this.state, focusedItemIndex = _a.focusedItemIndex, isDropdownOpen = _a.isDropdownOpen;
            // calling focusToItemNodeByIndex when children count updates due to TabPanelOverflowContainer lifecycle flow
            var currentChildren = functions_1.cleanEmptyChildren(children);
            previousChildren = functions_1.cleanEmptyChildren(previousChildren);
            if ((previousFocusedItemIndex !== focusedItemIndex && !isDropdownOpen) ||
                previousChildren.length !== currentChildren.length) {
                this.focusToItemNodeByIndex(focusedItemIndex);
            }
        }
    };
    TabPanel.prototype.focusToItemNodeByIndex = function (focusedItemIndex) {
        var childNodes = react_dom_1.default.findDOMNode(this).children;
        var activeNode = childNodes[focusedItemIndex];
        if (this.state.isAnyDropdownOpen) {
            return;
        }
        if (activeNode) {
            this.setFocusTo(activeNode.firstChild);
        }
        else {
            if (childNodes.length > 0) {
                this.setFocusTo(childNodes[childNodes.length - 1].firstChild);
            }
        }
    };
    TabPanel.prototype.setFocusTo = function (node) {
        node.focus();
        // we need this to have an ability to move out a focus from the panel with 'Shift+Tab' press
        this.setState({
            panelTabIndex: -1
        });
    };
    TabPanel.prototype.focusActiveItem = function () {
        var activeItemIndex = this.getActiveItemIndex();
        this.setFocusedItemByIndex(activeItemIndex);
        this.focusToItemNodeByIndex(activeItemIndex);
    };
    TabPanel.prototype.getActiveItemIndex = function () {
        var _this = this;
        var _a = this.props, activeKey = _a.activeKey, rawChildren = _a.children;
        var children = functions_1.cleanEmptyChildren(rawChildren);
        var activeItemIndex;
        if (activeKey === null) {
            activeItemIndex = children.findIndex(function (child) {
                return child &&
                    (child.props.active ||
                        (_this.context.router &&
                            _this.context.router.isActive(TabPanel.getItemPath(child), false)));
            });
        }
        else {
            activeItemIndex = children.findIndex(function (child) { return child && child.props.eventKey === activeKey; });
        }
        return activeItemIndex;
    };
    TabPanel.prototype.getPreviousTab = function () {
        var rawChildren = this.props.children;
        var children = functions_1.cleanEmptyChildren(rawChildren);
        var focusedItemIndex = this.state.focusedItemIndex;
        var previousItemIndex = focusedItemIndex - 1;
        var isPreviousChildPresent = previousItemIndex >= 0;
        var lastChildIndex = children.length - 1;
        if (isPreviousChildPresent &&
            TabPanel.isItemCanBeFocusedWithKeyboard(children[previousItemIndex])) {
            return previousItemIndex;
        }
        return TabPanel.isItemCanBeFocusedWithKeyboard(children[lastChildIndex])
            ? lastChildIndex
            : lastChildIndex - 1;
    };
    TabPanel.prototype.getNextTab = function () {
        var rawChildren = this.props.children;
        var children = functions_1.cleanEmptyChildren(rawChildren);
        var focusedItemIndex = this.state.focusedItemIndex;
        var nextItemIndex = focusedItemIndex + 1;
        var isNextChildPresent = nextItemIndex < children.length;
        if (isNextChildPresent &&
            TabPanel.isItemCanBeFocusedWithKeyboard(children[nextItemIndex])) {
            return nextItemIndex;
        }
        return 0;
    };
    TabPanel.prototype.getChildren = function () {
        var _this = this;
        var rawChildren = this.props.children;
        var children = functions_1.cleanEmptyChildren(rawChildren);
        return react_1.Children.map(children, function (child, index) {
            if (TabPanel.isItemOfDropdownType(child)) {
                var childProps = {
                    onToggle: function (isOpen) { return _this.handleDropdownToggle(index, isOpen); }
                };
                return react_1.cloneElement(child, childProps);
            }
            return child;
        });
    };
    TabPanel.prototype.render = function () {
        var _a = this.props, testAutomationId = _a.testAutomationId, centered = _a.centered, noBorder = _a.noBorder, topMenu = _a.topMenu, clearRightPadding = _a.clearRightPadding, clearLeftPadding = _a.clearLeftPadding, clearLeftWrapperPadding = _a.clearLeftWrapperPadding, clearRightWrapperPadding = _a.clearRightWrapperPadding, fullWidthBorder = _a.fullWidthBorder, noPadding = _a.noPadding, className = _a.className, preserveBottomBorder = _a.preserveBottomBorder, props = __rest(_a, ["testAutomationId", "centered", "noBorder", "topMenu", "clearRightPadding", "clearLeftPadding", "clearLeftWrapperPadding", "clearRightWrapperPadding", "fullWidthBorder", "noPadding", "className", "preserveBottomBorder"]);
        var panelTabIndex = this.state.panelTabIndex;
        className = classnames_1.default({
            'rc-nav-centered': centered,
            'rc-nav-noHorizontalPadding': noPadding,
            'rc-nav-noBorder': noBorder,
            'rc-nav-fullWidthBorder': !noBorder && fullWidthBorder,
            'rc-nav-topMenu': topMenu,
            'rc-nav-clearRightPadding': clearRightPadding,
            'rc-nav-clearLeftPadding': clearLeftPadding,
            'rc-nav-clearLeftWrapperPadding': clearLeftWrapperPadding,
            'rc-nav-clearRightWrapperPadding': clearRightWrapperPadding,
            'rc-nav-preserveBottomBorder': preserveBottomBorder
        }, className);
        return (react_1.default.createElement(react_bootstrap_1.Nav, __assign({ bsStyle: "tabs", className: className, "data-test-automation-id": testAutomationId, role: "tablist", tabIndex: panelTabIndex, onFocus: this.handleFocus, onClick: this.handleClick, onKeyDown: this.handleKeyDown }, props), this.getChildren()));
    };
    TabPanel.propTypes = {
        testAutomationId: prop_types_1.default.string,
        children: prop_types_1.default.node.isRequired,
        centered: prop_types_1.default.bool,
        noBorder: prop_types_1.default.bool,
        topMenu: prop_types_1.default.bool,
        clearRightPadding: prop_types_1.default.bool,
        clearLeftPadding: prop_types_1.default.bool,
        clearLeftWrapperPadding: prop_types_1.default.bool,
        clearRightWrapperPadding: prop_types_1.default.bool,
        fullWidthBorder: prop_types_1.default.bool,
        noPadding: prop_types_1.default.bool,
        preserveBottomBorder: prop_types_1.default.bool,
        className: prop_types_1.default.string,
        activeKey: prop_types_1.default.oneOfType([prop_types_1.default.string, prop_types_1.default.number]),
        bsStyle: prop_types_1.default.oneOf([
            exports.TAB_PANEL_STYLES.TABS,
            exports.TAB_PANEL_STYLES.MENU,
            exports.TAB_PANEL_STYLES.PILLS
        ])
    };
    TabPanel.defaultProps = {
        testAutomationId: 'tabs',
        centered: false,
        noBorder: false,
        topMenu: false,
        clearRightPadding: false,
        clearLeftPadding: false,
        clearLeftWrapperPadding: false,
        clearRightWrapperPadding: false,
        fullWidthBorder: false,
        preserveBottomBorder: false,
        noPadding: false,
        className: null,
        activeKey: null,
        bsStyle: exports.TAB_PANEL_STYLES.TABS
    };
    TabPanel.contextTypes = {
        router: prop_types_1.default.object
    };
    TabPanel.childContextTypes = {
        isStyledAsTab: prop_types_1.default.func
    };
    return TabPanel;
}(react_1.default.Component));
exports.TabPanel = TabPanel;
//# sourceMappingURL=TabPanel.js.map