"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __assign = (this && this.__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;
};
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;
};
var React = require("react");
var Utilities_1 = require("../../Utilities");
var FocusZone_1 = require("../../FocusZone");
var ContextualMenu_1 = require("../../ContextualMenu");
var DirectionalHint_1 = require("../../common/DirectionalHint");
var Icon_1 = require("../../Icon");
var CommandBar_scss_1 = require("./CommandBar.scss");
var OVERFLOW_KEY = 'overflow';
var OVERFLOW_WIDTH = 41.5;
var CommandBar = (function (_super) {
    __extends(CommandBar, _super);
    function CommandBar(props) {
        var _this = _super.call(this, props) || this;
        _this.state = _this._getStateFromProps(props);
        _this._id = Utilities_1.getId('CommandBar');
        _this._events = new Utilities_1.EventGroup(_this);
        return _this;
    }
    CommandBar.prototype.componentDidMount = function () {
        this._updateItemMeasurements();
        this._updateRenderedItems();
        this._events.on(window, 'resize', this._updateRenderedItems);
    };
    CommandBar.prototype.componentWillUnmount = function () {
        this._events.dispose();
    };
    CommandBar.prototype.componentWillReceiveProps = function (nextProps) {
        this.setState(this._getStateFromProps(nextProps));
        this._commandItemWidths = null;
    };
    CommandBar.prototype.componentDidUpdate = function (prevProps, prevStates) {
        if (!this._commandItemWidths) {
            this._updateItemMeasurements();
            this._updateRenderedItems();
        }
    };
    CommandBar.prototype.render = function () {
        var _this = this;
        var _a = this.props, isSearchBoxVisible = _a.isSearchBoxVisible, searchPlaceholderText = _a.searchPlaceholderText, className = _a.className;
        var _b = this.state, renderedItems = _b.renderedItems, contextualMenuProps = _b.contextualMenuProps, expandedMenuItemKey = _b.expandedMenuItemKey, expandedMenuId = _b.expandedMenuId, renderedOverflowItems = _b.renderedOverflowItems, contextualMenuTarget = _b.contextualMenuTarget, renderedFarItems = _b.renderedFarItems;
        var searchBox;
        if (isSearchBoxVisible) {
            searchBox = (React.createElement("div", { className: Utilities_1.css('ms-CommandBarSearch', CommandBar_scss_1.default.search), ref: 'searchSurface' },
                React.createElement("input", { className: Utilities_1.css('ms-CommandBarSearch-input', CommandBar_scss_1.default.searchInput), type: 'text', placeholder: searchPlaceholderText }),
                React.createElement("div", { className: Utilities_1.css('ms-CommandBarSearch-iconWrapper ms-CommandBarSearch-iconSearchWrapper', CommandBar_scss_1.default.searchIconWrapper, CommandBar_scss_1.default.searchIconSearchWrapper) },
                    React.createElement("i", { className: Utilities_1.css('ms-Icon ms-Icon--Search') })),
                React.createElement("div", { className: Utilities_1.css('ms-CommandBarSearch-iconWrapper ms-CommandBarSearch-iconClearWrapper ms-font-s', CommandBar_scss_1.default.searchIconWrapper, CommandBar_scss_1.default.searchIconClearWrapper) },
                    React.createElement("i", { className: Utilities_1.css('ms-Icon ms-Icon--Cancel') }))));
        }
        return (React.createElement("div", { className: Utilities_1.css('ms-CommandBar', CommandBar_scss_1.default.root, className), ref: 'commandBarRegion' },
            searchBox,
            React.createElement(FocusZone_1.FocusZone, { ref: 'focusZone', direction: FocusZone_1.FocusZoneDirection.horizontal, role: 'menubar' },
                React.createElement("div", { className: Utilities_1.css('ms-CommandBar-primaryCommands', CommandBar_scss_1.default.primaryCommands), ref: 'commandSurface' }, renderedItems.map(function (item, index) { return (_this._renderItemInCommandBar(item, index, expandedMenuItemKey)); }).concat((renderedOverflowItems && renderedOverflowItems.length) ? [
                    React.createElement("div", { className: Utilities_1.css('ms-CommandBarItem', CommandBar_scss_1.default.item), key: OVERFLOW_KEY, ref: OVERFLOW_KEY },
                        React.createElement("button", { type: 'button', id: this._id + OVERFLOW_KEY, className: Utilities_1.css('ms-CommandBarItem-link', CommandBar_scss_1.default.itemLink, (_c = {},
                                _c['is-expanded ' + CommandBar_scss_1.default.itemLinkIsExpanded] = (expandedMenuItemKey === OVERFLOW_KEY),
                                _c)), onClick: this._onOverflowClick, role: 'menuitem', "aria-label": this.props.elipisisAriaLabel || '', "aria-haspopup": true, "data-automation-id": 'commandBarOverflow' },
                            React.createElement("i", { className: Utilities_1.css('ms-CommandBarItem-overflow ms-Icon ms-Icon--More', CommandBar_scss_1.default.itemOverflow) })))
                ] : [])),
                React.createElement("div", { className: Utilities_1.css('ms-CommandBar-sideCommands', CommandBar_scss_1.default.sideCommands), ref: 'farCommandSurface' }, renderedFarItems.map(function (item, index) { return (_this._renderItemInCommandBar(item, index, expandedMenuItemKey, true)); }))),
            (contextualMenuProps) ?
                (React.createElement(ContextualMenu_1.ContextualMenu, __assign({ className: Utilities_1.css('ms-CommandBar-menuHost'), isBeakVisible: true, directionalHint: DirectionalHint_1.DirectionalHint.bottomAutoEdge }, contextualMenuProps, { targetElement: contextualMenuTarget, labelElementId: expandedMenuId, onDismiss: this._onContextMenuDismiss }))) : (null)));
        var _c;
    };
    CommandBar.prototype.focus = function () {
        this.refs.focusZone.focus();
    };
    CommandBar.prototype._renderItemInCommandBar = function (item, index, expandedMenuItemKey, isFarItem) {
        var _this = this;
        var itemKey = item.key || String(index);
        var className = Utilities_1.css(item.onClick ? ('ms-CommandBarItem-link ' + CommandBar_scss_1.default.itemLink) : ('ms-CommandBarItem-text ' + CommandBar_scss_1.default.itemText), !item.name && ('ms-CommandBarItem--noName ' + CommandBar_scss_1.default.itemLinkIsNoName), (expandedMenuItemKey === item.key) && ('is-expanded ' + CommandBar_scss_1.default.itemLinkIsExpanded));
        var hasIcon = !!item.icon || !!item.iconProps;
        return React.createElement("div", { className: Utilities_1.css('ms-CommandBarItem', CommandBar_scss_1.default.item, item.className), key: itemKey, ref: itemKey }, (function () {
            if (item.onClick || ContextualMenu_1.hasSubmenuItems(item)) {
                return React.createElement("button", __assign({}, Utilities_1.getNativeProps(item, Utilities_1.buttonProperties), { id: _this._id + item.key, className: className, onClick: function (ev) { return _this._onItemClick(ev, item); }, "data-command-key": index, "aria-haspopup": ContextualMenu_1.hasSubmenuItems(item), role: 'menuitem', "aria-label": item.ariaLabel || item.name, "aria-disabled": item.disabled }),
                    (hasIcon) ? _this._renderIcon(item) : (null),
                    (!!item.name) && (React.createElement("span", { className: Utilities_1.css('ms-CommandBarItem-commandText', CommandBar_scss_1.default.itemCommandText) }, item.name)),
                    ContextualMenu_1.hasSubmenuItems(item) ? (React.createElement("i", { className: Utilities_1.css('ms-CommandBarItem-chevronDown ms-Icon ms-Icon--ChevronDown', CommandBar_scss_1.default.itemChevronDown) })) : (null));
            }
            else {
                return React.createElement("div", __assign({}, Utilities_1.getNativeProps(item, Utilities_1.divProperties), { id: _this._id + item.key, className: className, "data-command-key": index, "aria-haspopup": ContextualMenu_1.hasSubmenuItems(item) }),
                    (hasIcon) ? _this._renderIcon(item) : (null),
                    React.createElement("span", { className: Utilities_1.css('ms-CommandBarItem-commandText ms-font-m ms-font-weight-regular', CommandBar_scss_1.default.itemCommandText), "aria-hidden": 'true', role: 'presentation' }, item.name));
            }
        })());
    };
    CommandBar.prototype._renderIcon = function (item) {
        // Only present to allow continued use of item.icon which is deprecated.
        var iconProps = item.iconProps ? item.iconProps : {
            iconName: item.icon
        };
        // Use the default icon color for the known icon names
        var iconColorClassName = iconProps.iconName === 'None' ? '' : ('ms-CommandBarItem-iconColor ' + CommandBar_scss_1.default.itemIconColor);
        var iconClassName = Utilities_1.css('ms-CommandBarItem-icon', CommandBar_scss_1.default.itemIcon, iconColorClassName, iconProps.className);
        return React.createElement(Icon_1.Icon, __assign({}, iconProps, { className: iconClassName }));
    };
    CommandBar.prototype._updateItemMeasurements = function () {
        // the generated width for overflow is 35 in chrome, 38 in IE, but the actual value is 41.5
        if (this.refs[OVERFLOW_KEY] || (this.props.overflowItems && this.props.overflowItems.length)) {
            this._overflowWidth = OVERFLOW_WIDTH;
        }
        else {
            this._overflowWidth = 0;
        }
        if (!this._commandItemWidths) {
            this._commandItemWidths = {};
        }
        for (var i = 0; i < this.props.items.length; i++) {
            var item = this.props.items[i];
            if (!this._commandItemWidths[item.key]) {
                var el = this.refs[item.key];
                if (el) {
                    this._commandItemWidths[item.key] = el.getBoundingClientRect().width;
                }
            }
        }
    };
    CommandBar.prototype._updateRenderedItems = function () {
        var _a = this.props, items = _a.items, overflowItems = _a.overflowItems;
        var commandSurface = this.refs.commandSurface;
        var farCommandSurface = this.refs.farCommandSurface;
        var commandBarRegion = this.refs.commandBarRegion;
        var searchSurface = this.refs.searchSurface;
        var renderedItems = [].concat(items);
        var renderedOverflowItems = overflowItems;
        var consumedWidth = 0;
        var isOverflowVisible = overflowItems && overflowItems.length;
        var style = window.getComputedStyle(commandSurface);
        var availableWidth = commandBarRegion.clientWidth - parseInt(style.marginLeft, 10) - parseInt(style.marginRight, 10);
        if (searchSurface) {
            availableWidth -= searchSurface.getBoundingClientRect().width;
        }
        if (farCommandSurface) {
            availableWidth -= farCommandSurface.getBoundingClientRect().width;
        }
        if (isOverflowVisible) {
            availableWidth -= this._overflowWidth;
        }
        for (var i = 0; i < renderedItems.length; i++) {
            var item = renderedItems[i];
            var itemWidth = this._commandItemWidths[item.key];
            if ((consumedWidth + itemWidth) >= availableWidth) {
                if (i > 0 && !isOverflowVisible && (availableWidth - consumedWidth) < OVERFLOW_WIDTH) {
                    i--;
                }
                renderedOverflowItems = renderedItems.splice(i).concat(overflowItems);
                break;
            }
            else {
                consumedWidth += itemWidth;
            }
        }
        var renderedContextualMenuProps = this._getContextualMenuPropsAfterUpdate(renderedItems.concat(this.state.renderedFarItems), renderedOverflowItems);
        this.setState({
            renderedItems: renderedItems,
            renderedOverflowItems: renderedOverflowItems,
            expandedMenuItemKey: renderedContextualMenuProps ? this.state.expandedMenuItemKey : null,
            contextualMenuProps: renderedContextualMenuProps,
            contextualMenuTarget: renderedContextualMenuProps ? this.state.contextualMenuTarget : null
        });
    };
    CommandBar.prototype._onItemClick = function (ev, item) {
        if (item.key === this.state.expandedMenuItemKey || !ContextualMenu_1.hasSubmenuItems(item)) {
            this._onContextMenuDismiss();
        }
        else {
            this.setState({
                expandedMenuId: ev.currentTarget.id,
                expandedMenuItemKey: item.key,
                contextualMenuProps: this._getContextualMenuPropsFromItem(item),
                contextualMenuTarget: ev.currentTarget
            });
        }
        if (item.onClick) {
            item.onClick(ev, item);
        }
    };
    CommandBar.prototype._onOverflowClick = function (ev) {
        if (this.state.expandedMenuItemKey === OVERFLOW_KEY) {
            this._onContextMenuDismiss();
        }
        else {
            this.setState({
                expandedMenuId: ev.currentTarget.id,
                expandedMenuItemKey: OVERFLOW_KEY,
                contextualMenuProps: { items: this.state.renderedOverflowItems },
                contextualMenuTarget: ev.currentTarget
            });
        }
    };
    CommandBar.prototype._onContextMenuDismiss = function (ev) {
        if (!ev || !ev.relatedTarget || !this.refs.commandSurface.contains(ev.relatedTarget)) {
            var contextualMenuProps = this.state.contextualMenuProps;
            if (contextualMenuProps && contextualMenuProps.onDismiss) {
                this.state.contextualMenuProps.onDismiss(ev);
            }
            this.setState({
                expandedMenuItemKey: null,
                contextualMenuProps: null,
                contextualMenuTarget: null
            });
        }
        else {
            ev.stopPropagation();
            ev.preventDefault();
        }
    };
    CommandBar.prototype._getStateFromProps = function (nextProps) {
        return {
            renderedItems: nextProps.items || [],
            renderedOverflowItems: null,
            contextualMenuProps: this._getContextualMenuPropsAfterUpdate(nextProps.items.concat(nextProps.farItems), nextProps.overflowItems),
            renderedFarItems: nextProps.farItems || null
        };
    };
    CommandBar.prototype._getContextualMenuPropsAfterUpdate = function (renderedItems, overflowItems) {
        var _this = this;
        if (this.state && this.state.expandedMenuItemKey) {
            if (this.state.expandedMenuItemKey === OVERFLOW_KEY) {
                // Keep the overflow menu open
                return { items: overflowItems };
            }
            else {
                // Find the currently open key in the new props
                var matchingItem = renderedItems.filter(function (item) { return item.key === _this.state.expandedMenuItemKey; });
                if (matchingItem.length === 1) {
                    return this._getContextualMenuPropsFromItem(matchingItem[0]);
                }
            }
        }
        return null;
    };
    CommandBar.prototype._getContextualMenuPropsFromItem = function (item) {
        return item.subMenuProps || (item.items && { items: item.items });
    };
    return CommandBar;
}(React.Component));
CommandBar.defaultProps = {
    items: [],
    overflowItems: [],
    farItems: []
};
__decorate([
    Utilities_1.autobind
], CommandBar.prototype, "_onOverflowClick", null);
__decorate([
    Utilities_1.autobind
], CommandBar.prototype, "_onContextMenuDismiss", null);
exports.CommandBar = CommandBar;

//# sourceMappingURL=CommandBar.js.map
