'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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_dom_1 = require("react-dom");
var Store_1 = require("../../data/Store");
var FormGroup_1 = require("./FormGroup");
var FormControl_1 = require("./FormControl");
var Checkbox_1 = require("./Checkbox");
var Filter_1 = require("../Filter");
var Icon_1 = require("../Icon");
var Tooltip_1 = require("../Tooltip");
var react_1 = __importDefault(require("react"));
var prop_types_1 = __importDefault(require("prop-types"));
var react_bootstrap_1 = require("react-bootstrap");
var lodash_1 = __importDefault(require("lodash"));
var classnames_1 = __importDefault(require("classnames"));
var utils_1 = require("../list/utils");
var utils_2 = require("../../../utils");
var FocusHelper_1 = require("../../utils/FocusHelper");
var constants_1 = require("../../../utils/constants");
var index_en_US_1 = __importDefault(require("../../../lang/common/index-en_US"));
var FC = FormControl_1.FormControl;
var doNothing = function () { };
// declare namespace MultiSelectModule {
//     class MultiSelectOption extends React.Component<any> {}
//     class MultiSelectMasterOption extends React.Component<any> {}
//     class MultiSelectOptionGroup extends React.Component<any> {}
//     class MultiSelectField extends React.Component<any> {}
// }
var MultiSelectField = /** @class */ (function (_super) {
    __extends(MultiSelectField, _super);
    function MultiSelectField() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MultiSelectField.prototype.renderInput = function () {
        var _a = this.getPropsFromContext(), children = _a.children, innerLabel = _a.innerLabel, props = __rest(_a, ["children", "innerLabel"]);
        var MultiSelectTS = MultiSelect;
        return (react_1.default.createElement(MultiSelectTS, __assign({}, props, { label: innerLabel, ref: "control", hasFormGroupContainer: true }), children));
    };
    MultiSelectField.propTypes = __assign({}, FormGroup_1.FormGroup.propTypes);
    MultiSelectField.defaultProps = __assign({}, FormGroup_1.FormGroup.defaultProps, { testAutomationId: 'multiSelect' });
    return MultiSelectField;
}(FormGroup_1.FormGroup));
var multiSelectInstanceCounter = 0;
var MultiSelectOption = /** @class */ (function (_super) {
    __extends(MultiSelectOption, _super);
    function MultiSelectOption(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.handleKeyDown = _this.handleKeyDown.bind(_this);
        return _this;
    }
    MultiSelectOption.compareOptionValue = function (source) {
        if (lodash_1.default.isObject(source)) {
            return lodash_1.default.matches(source);
        }
        return function (value) {
            return value === source;
        };
    };
    MultiSelectOption.prototype.getChildContext = function () {
        var _this = this;
        return {
            getOptionIdPrefix: function () { return _this.getId(); }
        };
    };
    MultiSelectOption.prototype.handleKeyDown = function (event) {
        switch (event.keyCode) {
            case 13: // enter
            case 32: // space
                this.refs.control.click();
                event.preventDefault();
                break;
            default:
                this.props.onKeyDown(event);
        }
    };
    MultiSelectOption.prototype.getId = function () {
        if (!lodash_1.default.isFunction(this.context.getOptionIdPrefix)) {
            return null;
        }
        return this.context.getOptionIdPrefix() + "_" + (this.props.groupMaster ? 'masterOption' : 'option') + "_" + this.props.ariaPosition;
    };
    MultiSelectOption.prototype.finalRender = function (props, content) {
        if (lodash_1.default.isFunction(this.props.tagRenderer)) {
            return this.props.tagRenderer(props, content);
        }
        return content;
    };
    MultiSelectOption.prototype.render = function () {
        var _this = this;
        var _a = this.props, hint = _a.hint, description = _a.description, secondLine = _a.secondLine, overlayProps = _a.overlayProps;
        var behaveAsFlat = this.context.multiSelect.behaveAsFlat;
        var values = this.context.multiSelect.values;
        var filterCallback = this.context.multiSelect.filterCallback;
        var isSelected = false;
        var isMaster = this.props.groupMaster;
        var isOptionDisabled = !!(isMaster &&
            this.context.multiSelect.isSingleSelectMode &&
            this.props.value === undefined) || this.props.disabled;
        var optionValues = [];
        var labelTitle = !description ? this.props.label : this.props.label + " - " + description;
        if (behaveAsFlat) {
            isSelected = values.some(MultiSelectOption.compareOptionValue(this.props.value));
        }
        else if (!isMaster) {
            optionValues = [this.props.value];
            var index = lodash_1.default.findIndex(values, MultiSelectOption.compareOptionValue(this.props.value));
            isSelected = index > -1;
            // Skip not matched options
            if (!filterCallback(this.props.label, this.props.value)) {
                return null;
            }
        }
        else {
            optionValues = this.context.multiSelectGroup.values;
            var selectedValuesCount_1 = 0;
            var groupFilteredLabels = this.context.multiSelectGroup.filteredLabels;
            optionValues.forEach(function (value) {
                var index = lodash_1.default.findIndex(values, MultiSelectOption.compareOptionValue(value));
                if (index > -1) {
                    selectedValuesCount_1++;
                }
            });
            if (selectedValuesCount_1 > 0) {
                isSelected = selectedValuesCount_1 === optionValues.length ? true : null;
            }
            // Skip not matched groups
            if (!filterCallback(this.props.label, this.props.value) &&
                !groupFilteredLabels.length) {
                return null;
            }
        }
        var highlightedLabelText = this.props.customLabel ||
            utils_1.highlight(this.context.multiSelect.filterRegExp, this.props.label);
        var icon = this.props.icon;
        var content;
        var label = (react_1.default.createElement("span", { className: "multi-select__item-text-container" },
            highlightedLabelText,
            description !== null ? (react_1.default.createElement("span", { className: "multi-select__item-hint select-description" },
                ' ',
                "- ",
                description)) : null));
        if (this.context.multiSelect.isSingleSelectMode) {
            isSelected =
                this.props.value !== undefined &&
                    MultiSelectOption.compareOptionValue(this.props.value)(values[0]);
            var onClick = function (event) {
                if (_this.props.value !== undefined) {
                    _this.context.multiSelect.setValues([_this.props.value]);
                }
                _this.context.multiSelect.close();
            };
            var labelProps = {
                className: classnames_1.default('option-label', this.props.labelClassName, {
                    'selected-option': isSelected
                }),
                ref: 'control'
            };
            if (!isOptionDisabled) {
                labelProps.onClick = onClick;
            }
            var secondLineElement = secondLine ? (react_1.default.createElement("div", { className: "second-line text-overflow", title: secondLine }, secondLine)) : null;
            content = (react_1.default.createElement("span", __assign({}, labelProps),
                isSelected ? (react_1.default.createElement(Icon_1.Icon, { "aria-hidden": "true", name: "checkbox-selected-readonly" })) : null,
                label,
                secondLineElement,
                react_1.default.createElement("div", { className: "icon-wrapper", "aria-hidden": "true" }, icon ? react_1.default.createElement(Icon_1.Icon, { name: icon }) : null)));
        }
        else {
            content = (react_1.default.createElement(Checkbox_1.Checkbox, { name: undefined, ref: "control", label: label, labelClassName: this.props.labelClassName, checked: isSelected, "aria-hidden": true, "aria-checked": isSelected === null ? 'mixed' : isSelected, disabled: isOptionDisabled, onChange: function () {
                    var isSelected = _this.refs.control.getValue();
                    var next = behaveAsFlat ? [_this.props.value] : optionValues;
                    var newValues = isSelected
                        ? values.concat(next)
                        : values.filter(function (source) {
                            var compare = MultiSelectOption.compareOptionValue(source);
                            return next.every(function (value) { return !compare(value); });
                        });
                    _this.context.multiSelect.setValues(newValues);
                } }));
        }
        var optionId = this.getId();
        var liProps = {
            id: optionId,
            'data-test-automation-id': this.props.testAutomationId || 'option' + this.context.multiSelect.uid(),
            className: classnames_1.default("multi-select-option multi-select-option-level-" + this.props.ariaLevel, this.props.className, {
                'master-option': isMaster,
                'option-disabled': isOptionDisabled
            }),
            role: 'treeitem',
            'aria-level': this.props.ariaLevel,
            'aria-setsize': this.props.ariaSetSize,
            'aria-posinset': this.props.ariaPosition
        };
        if (!isOptionDisabled) {
            liProps.tabIndex = '-1';
            liProps.onKeyDown = this.handleKeyDown;
            liProps.onSelect = this.props.onSelect;
            liProps['aria-selected'] = isSelected === true;
            liProps.onFocus = function () {
                if (lodash_1.default.isFunction(_this.context.setAriaActivedescendant)) {
                    _this.context.setAriaActivedescendant(optionId);
                }
            };
        }
        var finalContent = hint ? (react_1.default.createElement(react_bootstrap_1.OverlayTrigger, __assign({ overlay: react_1.default.createElement(Tooltip_1.Tooltip, null, hint) }, overlayProps), content)) : (this.finalRender(liProps, content));
        return (react_1.default.createElement("li", __assign({}, liProps, { title: labelTitle }), finalContent));
    };
    MultiSelectOption.contextTypes = {
        multiSelect: prop_types_1.default.object,
        multiSelectGroup: prop_types_1.default.object,
        getOptionIdPrefix: prop_types_1.default.func,
        setAriaActivedescendant: prop_types_1.default.func
    };
    MultiSelectOption.childContextTypes = {
        getOptionIdPrefix: prop_types_1.default.func
    };
    MultiSelectOption.propTypes = {
        className: prop_types_1.default.string,
        disabled: prop_types_1.default.bool,
        groupMaster: prop_types_1.default.bool,
        icon: prop_types_1.default.string,
        label: prop_types_1.default.string.isRequired,
        labelClassName: prop_types_1.default.string,
        onKeyDown: prop_types_1.default.func,
        onSelect: prop_types_1.default.func,
        testAutomationId: prop_types_1.default.string,
        value: prop_types_1.default.any.isRequired,
        ariaPosition: prop_types_1.default.number,
        ariaLevel: prop_types_1.default.number,
        ariaSetSize: prop_types_1.default.number,
        hint: prop_types_1.default.string,
        customLabel: prop_types_1.default.any,
        tagRenderer: prop_types_1.default.func,
        description: prop_types_1.default.string,
        secondLine: prop_types_1.default.string
    };
    MultiSelectOption.defaultProps = {
        className: null,
        disabled: false,
        groupMaster: false,
        icon: '',
        labelClassName: '',
        onKeyDown: doNothing,
        onSelect: doNothing,
        testAutomationId: null,
        ariaPosition: null,
        ariaLevel: null,
        ariaSetSize: null,
        hint: null,
        customLabel: null,
        tagRenderer: null,
        description: null,
        secondLine: null,
        overlayProps: {}
    };
    return MultiSelectOption;
}(react_1.default.Component));
var MultiSelectMasterOptionWrapper = /** @class */ (function (_super) {
    __extends(MultiSelectMasterOptionWrapper, _super);
    function MultiSelectMasterOptionWrapper() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.tagRenderer = function (props, content) {
            return react_1.default.createElement("div", { id: _this.props.groupLabelId }, content);
        };
        return _this;
    }
    MultiSelectMasterOptionWrapper.prototype.getTestAutomationId = function () {
        var testAutomationId = this.props.testAutomationId;
        var multiSelect = this.context.multiSelect;
        if (testAutomationId) {
            return testAutomationId;
        }
        return "optionMaster" + multiSelect.uid();
    };
    MultiSelectMasterOptionWrapper.prototype.render = function () {
        return (react_1.default.createElement(MultiSelectOption, __assign({}, this.props, { testAutomationId: this.getTestAutomationId(), tagRenderer: this.tagRenderer, groupMaster: true })));
    };
    MultiSelectMasterOptionWrapper.propTypes = __assign({}, MultiSelectOption.propTypes, { testAutomationId: prop_types_1.default.string, groupLabelId: prop_types_1.default.string.isRequired });
    MultiSelectMasterOptionWrapper.defaultProps = __assign({}, MultiSelectOption.defaultProps, { testAutomationId: null });
    MultiSelectMasterOptionWrapper.contextTypes = {
        multiSelect: prop_types_1.default.object
    };
    return MultiSelectMasterOptionWrapper;
}(react_1.default.Component));
var MultiSelectMasterOption = /** @class */ (function (_super) {
    __extends(MultiSelectMasterOption, _super);
    function MultiSelectMasterOption() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MultiSelectMasterOption.prototype.render = function () {
        return null;
    };
    MultiSelectMasterOption.propTypes = __assign({}, MultiSelectOption.propTypes);
    return MultiSelectMasterOption;
}(react_1.default.Component));
function getChildrenValues(children) {
    return lodash_1.default.flatten(react_1.default.Children.toArray(children)
        .filter(function (child) {
        return ((child.type === MultiSelectOption && !child.props.groupMaster) ||
            child.type === MultiSelectOptionGroup);
    })
        .map(function (child) {
        if (child.type === MultiSelectOption) {
            return child.props.value;
        }
        return getChildrenValues(child.props.children);
    }));
}
function hasValueChild(children) {
    var items = react_1.default.Children.toArray(children);
    var hasValue = items.some(function (o) { return o && o.props && o.props.value !== undefined; });
    if (hasValue) {
        return true;
    }
    for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
        var child = items_1[_i];
        if (child && child.props && child.props.children && hasValueChild(child.props.children)) {
            return true;
        }
    }
    return false;
}
function getChildrenLabels(children, filterCallback) {
    return lodash_1.default.flatten(react_1.default.Children.toArray(children)
        .filter(function (child) {
        if (child.type === MultiSelectOption || child.type === MultiSelectMasterOption) {
            if (filterCallback && !filterCallback(child.props.label, child.props.value)) {
                return false;
            }
            return true;
        }
        else if (child.type === MultiSelectOptionGroup) {
            return true;
        }
    })
        .map(function (child) {
        if (child.type === MultiSelectOption || child.type === MultiSelectMasterOption) {
            return child.props.label;
        }
        return getChildrenLabels(child.props.children, filterCallback);
    }));
}
function getGroupValueOptionSize(children) {
    if (!Array.isArray(children)) {
        children = react_1.default.Children.toArray(children);
    }
    return children.filter(function (o) { return !isMasterOption(o); }).length;
}
function isMasterOption(node) {
    return node && node.type === MultiSelectMasterOption;
}
var TreeItemAriaProps = ['aria-selected', 'aria-level', 'aria-setsize', 'aria-posinset', 'role'];
var MultiSelectOptionGroup = /** @class */ (function (_super) {
    __extends(MultiSelectOptionGroup, _super);
    function MultiSelectOptionGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getOptionId = function () {
            if (lodash_1.default.isFunction(_this.context.getOptionIdPrefix)) {
                return _this.context.getOptionIdPrefix() + "_" + _this.props.ariaPosition;
            }
            return null;
        };
        _this.getMasterOptionWrapperProps = function (props) {
            return lodash_1.default.omit(props, TreeItemAriaProps);
        };
        return _this;
    }
    MultiSelectOptionGroup.prototype.getChildContext = function () {
        return {
            multiSelectGroup: {
                values: getChildrenValues(this.props.children),
                filteredLabels: getChildrenLabels(this.props.children, this.context.multiSelect.filterCallback)
            },
            getOptionIdPrefix: this.getOptionId
        };
    };
    MultiSelectOptionGroup.prototype.getSiblingOptionSize = function (children) {
        return getGroupValueOptionSize(children);
    };
    MultiSelectOptionGroup.prototype.getGroupProps = function (props) {
        if (lodash_1.default.isEmpty(props)) {
            return null;
        }
        return lodash_1.default.pick(props, TreeItemAriaProps);
    };
    MultiSelectOptionGroup.prototype.render = function () {
        var _this = this;
        var children = react_1.default.Children.toArray(this.props.children);
        var ariaSetSize = this.getSiblingOptionSize(children);
        var hasMaster = false;
        var items = children.map(function (child, index) {
            var childProps = child.props || {};
            var isMasterNode = isMasterOption(child);
            if (isMasterNode) {
                hasMaster = true;
            }
            var ariaPosition = hasMaster ? index : index + 1;
            return react_1.default.cloneElement(child, {
                ariaPosition: isMasterNode ? _this.props.ariaPosition : ariaPosition,
                ariaLevel: _this.props.ariaLevel + (isMasterNode ? 0 : 1),
                ariaSetSize: isMasterNode ? _this.props.ariaSetSize : ariaSetSize,
                onKeyDown: _this.props.onKeyDown,
                onSelect: _this.props.onSelect
            }, childProps.children);
        });
        var masterItem = lodash_1.default.find(items, isMasterOption);
        var groupLabelId = this.getOptionId() + "_group_node";
        var masterOptionNode = masterItem ? (react_1.default.createElement(MultiSelectMasterOptionWrapper, __assign({ groupLabelId: groupLabelId }, this.getMasterOptionWrapperProps(masterItem.props)))) : null;
        var valueItems = items.filter(function (node) { return !isMasterOption(node); });
        var hasAvailableValue = hasValueChild(valueItems);
        var groupProps = __assign({ id: this.getOptionId(), 'data-test-automation-id': this.props.testAutomationId || 'groupOption' + this.context.multiSelect.uid(), role: 'treeitem', 'aria-expanded': true, 'aria-selected': false }, this.getGroupProps(masterItem && masterItem.props));
        groupProps.className = classnames_1.default(groupProps.className, {
            'multi-select-has-children': !lodash_1.default.isEmpty(valueItems)
        });
        var ariaProps = {};
        if (hasAvailableValue && masterItem) {
            ariaProps = { 'aria-labelledby': groupLabelId };
        }
        return (react_1.default.createElement("div", __assign({}, groupProps),
            masterOptionNode,
            react_1.default.createElement("ul", __assign({ className: classnames_1.default('multi-select-group', this.props.className), role: hasAvailableValue ? 'group' : '' }, ariaProps), valueItems)));
    };
    MultiSelectOptionGroup.contextTypes = {
        multiSelect: prop_types_1.default.object,
        multiSelectGroup: prop_types_1.default.object,
        getOptionIdPrefix: prop_types_1.default.func
    };
    MultiSelectOptionGroup.childContextTypes = {
        multiSelectGroup: prop_types_1.default.object,
        getOptionIdPrefix: prop_types_1.default.func
    };
    MultiSelectOptionGroup.propTypes = {
        children: prop_types_1.default.node,
        className: prop_types_1.default.string,
        onKeyDown: prop_types_1.default.func,
        onSelect: prop_types_1.default.func,
        testAutomationId: prop_types_1.default.string,
        ariaPosition: prop_types_1.default.number,
        ariaLevel: prop_types_1.default.number,
        ariaSetSize: prop_types_1.default.number
    };
    MultiSelectOptionGroup.defaultProps = {
        children: null,
        className: null,
        onKeyDown: doNothing,
        onSelect: doNothing,
        testAutomationId: null,
        ariaPosition: 1,
        ariaLevel: 1,
        ariaSetSize: 1
    };
    return MultiSelectOptionGroup;
}(react_1.default.Component));
var MultiSelectDefaultAutomationId = 'multiSelect';
var MultiSelect = /** @class */ (function (_super) {
    __extends(MultiSelect, _super);
    function MultiSelect(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.focusHelper = new FocusHelper_1.FocusHelper();
        _this.saveMultiSelectRef = function (ref) {
            _this.multiSelectEle = react_dom_1.findDOMNode(ref);
        };
        _this.focus = function () {
            _this.focusHelper.focus();
        };
        /** @param {Array<String>} selectedItemLabels */
        _this.getTitle = function (selectedItemLabels) {
            if (lodash_1.default.isEmpty(selectedItemLabels)) {
                return null;
            }
            var _a = _this.props, label = _a.label, selectedValuesPrefix = _a.selectedValuesPrefix;
            var valueStr = selectedItemLabels.join(', ');
            if (!_this.shouldApplyLabelPrefix()) {
                return valueStr;
            }
            return utils_2.translate(selectedValuesPrefix, {
                filterName: label,
                values: valueStr
            });
        };
        _this.getAriaLabel = function () {
            var _a = _this.props, label = _a.label, toggleAriaLabel = _a.toggleAriaLabel;
            if (!_this.shouldApplyLabelPrefix()) {
                return label;
            }
            return utils_2.translate(toggleAriaLabel, { filterName: label });
        };
        /** @param {Array<String>} selectedItems */
        _this.getDisplayLabel = function (selectedItems) {
            var _a = _this.props, label = _a.label, labelItemsLimit = _a.labelItemsLimit;
            if (lodash_1.default.isEmpty(selectedItems)) {
                return label;
            }
            var valueString = selectedItems.join(', ');
            if (selectedItems.length > labelItemsLimit) {
                valueString = selectedItems
                    .slice(0, labelItemsLimit)
                    .concat(['...'])
                    .join(', ');
            }
            return _this.shouldApplyLabelPrefix() ? label + ": " + valueString : valueString;
        };
        /** @returns {Array<String>}*/
        _this.getSelectedItemLabels = function () {
            var children = _this.props.children;
            var props = _this.getPropsFromContext();
            var values = toArray(props.value);
            return getChildrenLabels(children, function (label, value) {
                return lodash_1.default.findIndex(values, MultiSelectOption.compareOptionValue(value)) > -1;
            });
        };
        _this.onToggle = _this.onToggle.bind(_this);
        _this.onKeyDown = _this.onKeyDown.bind(_this);
        _this.showMore = _this.showMore.bind(_this);
        _this.filterByLimit = _this.filterByLimit.bind(_this);
        _this.filterByLabelAndLimit = _this.filterByLabelAndLimit.bind(_this);
        _this.listItemsFilteredByLimit = [];
        _this.listItemsFiltered = [];
        _this.state = {
            filterText: '',
            filterRegExp: null,
            filterCallback: _this.filterByLimit,
            isOpen: false,
            isMoreShowed: false,
            hasFilterFocus: false,
            ariaActivedescendant: null
        };
        _this.instanceId = ++multiSelectInstanceCounter;
        return _this;
    }
    MultiSelect.prototype.componentDidMount = function () {
        var _this = this;
        this.multiSelectEle.addEventListener('keydown', function (event) {
            if (_this.state.isOpen && event.key === constants_1.KeyNames.Escape) {
                event.stopPropagation();
            }
        });
    };
    MultiSelect.prototype.filterByLimit = function (label, value) {
        if (!(this.props.listItemsLimit > 0)) {
            return true;
        }
        if (this.state.isMoreShowed) {
            return true;
        }
        var validValue = typeof value !== 'undefined';
        // Calculate all visible options
        if (validValue && this.listItemsFiltered.indexOf(value) === -1) {
            this.listItemsFiltered.push(value);
        }
        if (this.listItemsFilteredByLimit.length < this.props.listItemsLimit) {
            if (validValue && this.listItemsFilteredByLimit.indexOf(value) === -1) {
                this.listItemsFilteredByLimit.push(value);
            }
            return true;
        }
        return this.listItemsFilteredByLimit.indexOf(value) !== -1;
    };
    MultiSelect.prototype.filterByLabelAndLimit = function (label, value) {
        var filterRegExp = this.state.filterRegExp;
        if (filterRegExp === null) {
            return this.filterByLimit(label, value);
        }
        filterRegExp.lastIndex = 0;
        return filterRegExp.test(label) && this.filterByLimit(label, value);
    };
    MultiSelect.prototype.outputConverter = function (e) {
        return e;
    };
    MultiSelect.prototype.getValue = function () {
        // FIXME [UIA-10000] Not implemented
        return null;
    };
    MultiSelect.prototype.getChildContext = function () {
        var _this = this;
        var props = this.getPropsFromContext();
        return {
            multiSelect: {
                uid: function () {
                    return ++_this.uid;
                },
                values: toArray(props.value),
                setValues: function (values) {
                    if (_this.props.isSingleSelect) {
                        values = values[0];
                    }
                    props.onChange(values);
                },
                filterCallback: this.state.filterCallback,
                filterRegExp: this.state.filterRegExp,
                isSingleSelectMode: this.props.isSingleSelect,
                behaveAsFlat: this.props.behaveAsFlat,
                close: function () {
                    _this.setState({ isOpen: false });
                }
            },
            level: 0,
            getOptionIdPrefix: function () { return "select_" + _this.instanceId; },
            setAriaActivedescendant: function (ariaActivedescendant) { return _this.setState({ ariaActivedescendant: ariaActivedescendant }); }
        };
    };
    MultiSelect.prototype.onToggle = function (isOpen) {
        this.uid = 0;
        if (!isOpen && this.state.hasFilterFocus) {
            isOpen = true;
        }
        this.setState({ isOpen: isOpen });
    };
    MultiSelect.prototype.onKeyDown = function (event) {
        switch (event.key) {
            case 'Escape':
            case 'Tab':
                this.setState({ isOpen: false });
                break;
        }
    };
    MultiSelect.prototype.setTextFilter = function (text) {
        var filterRegExp = Store_1.Store.searchStringToRegExp(text);
        this.listItemsFiltered = [];
        this.listItemsFilteredByLimit = [];
        this.setState({
            filterText: text,
            filterRegExp: filterRegExp,
            filterCallback: this.filterByLabelAndLimit,
            isMoreShowed: false
        });
    };
    MultiSelect.prototype.showMore = function (event) {
        event.preventDefault();
        this.setState({
            isMoreShowed: true
        });
    };
    MultiSelect.prototype.renderShowMore = function () {
        if (this.state.isMoreShowed) {
            return null;
        }
        var count = this.listItemsFiltered.length - this.listItemsFilteredByLimit.length;
        if (count <= 0) {
            return null;
        }
        return (react_1.default.createElement("li", { role: "menuitem" },
            react_1.default.createElement("a", { className: "show-more", onClick: this.showMore }, utils_2.translate(this.props.showMoreCountTextTemplate, { count: count }))));
    };
    MultiSelect.prototype.getAriaDescribedbyProp = function () {
        var describedby = this.props["aria-describedby"];
        return describedby ? { 'aria-describedby': describedby } : {};
    };
    MultiSelect.prototype.shouldApplyLabelPrefix = function () {
        var _a = this.props, isSingleSelect = _a.isSingleSelect, applyLabelPrefixForSingleMode = _a.applyLabelPrefixForSingleMode, applyLabelPrefixForMultiMode = _a.applyLabelPrefixForMultiMode;
        return isSingleSelect ? applyLabelPrefixForSingleMode : applyLabelPrefixForMultiMode;
    };
    MultiSelect.prototype.render = function () {
        var _this = this;
        this.uid = 0;
        var _a = this.props, id = _a.id, isFilterable = _a.isFilterable, searchText = _a.searchText, noResultsText = _a.noResultsText, label = _a.label, value = _a.value, children = _a.children, labelItemsLimit = _a.labelItemsLimit, testAutomationId = _a.testAutomationId, className = _a.className, block = _a.block, stretch = _a.stretch, listHeader = _a.listHeader, listItemsLimit = _a.listItemsLimit, showMoreCountTextTemplate = _a.showMoreCountTextTemplate, onChange = _a.onChange, ariaLabelledById = _a.ariaLabelledById, toggleAriaLabel = _a.toggleAriaLabel, stretchDropdownMenu = _a.stretchDropdownMenu, otherProps = __rest(_a, ["id", "isFilterable", "searchText", "noResultsText", "label", "value", "children", "labelItemsLimit", "testAutomationId", "className", "block", "stretch", "listHeader", "listItemsLimit", "showMoreCountTextTemplate", "onChange", "ariaLabelledById", "toggleAriaLabel", "stretchDropdownMenu"]);
        var filter = null;
        var isNoResults = false;
        var hasChildren = children && (!(children instanceof Array) || children.length);
        if (isFilterable && hasChildren) {
            filter = (react_1.default.createElement(Filter_1.Filter, { value: this.state.filterText, testAutomationId: "filter", className: "multi-select-filter", ref: "filter", placeholder: searchText, tabIndex: -1, onFocus: function (event) {
                    if (!_this.state.hasFilterFocus) {
                        _this.refs.filter.focus();
                        _this.setState({ hasFilterFocus: true });
                    }
                }, onBlur: function (event) { return _this.setState({ hasFilterFocus: false }); }, onKeyDown: function (event) {
                    if (['ArrowUp', 'ArrowDown', 'Escape', 'Tab'].indexOf(event.key) === -1) {
                        event.stopPropagation();
                    }
                }, onChange: function (filterText) { return _this.setTextFilter(filterText); } }));
            isNoResults = getChildrenLabels(children, this.state.filterCallback).length === 0;
        }
        var header = null;
        if (listHeader && filter) {
            header = (react_1.default.createElement("li", { className: "multi-select-list-header", role: "none" },
                listHeader,
                filter));
        }
        else if (listHeader) {
            header = (react_1.default.createElement("li", { className: "multi-select-list-header", role: "none" }, listHeader));
        }
        else if (filter) {
            header = (react_1.default.createElement("li", { className: "multi-select-list-header", role: "none" }, filter));
        }
        var selectedItemLabels = this.getSelectedItemLabels();
        var title = this.getTitle(selectedItemLabels);
        var displayLabel = this.getDisplayLabel(selectedItemLabels);
        id =
            id ||
                (testAutomationId !== MultiSelectDefaultAutomationId
                    ? testAutomationId
                    : Date.now());
        var dropdownMenuClassName = stretchDropdownMenu ? 'stretch' : null;
        return (react_1.default.createElement(react_bootstrap_1.Dropdown, __assign({ id: id, onToggle: this.onToggle, onKeyDown: this.onKeyDown, open: this.state.isOpen, ref: this.saveMultiSelectRef, "data-test-automation-id": this.props.hasFormGroupContainer ? undefined : testAutomationId, className: classnames_1.default('multi-select', className, {
                'btn-block': stretch || block,
                stretch: stretch
            }) }, this.getSafeProps(otherProps)),
            react_1.default.createElement(react_bootstrap_1.Dropdown.Toggle, __assign({ ref: this.focusHelper.setEl, "data-test-automation-id": "toggle", "aria-labelledby": ariaLabelledById, noCaret: true, disabled: this.props.disabled, "aria-label": this.getAriaLabel() }, this.getAriaDescribedbyProp(), { title: title, className: classnames_1.default({ 'btn-block': stretch || block }) }),
                react_1.default.createElement("span", { className: "icon-wrapper", "aria-hidden": "true" },
                    react_1.default.createElement(Icon_1.Icon, { name: "chevron-down-small" })),
                react_1.default.createElement("div", { className: "label-wrapper" },
                    react_1.default.createElement("div", { className: "label-wrapper-inner" },
                        react_1.default.createElement("div", { className: "label-text-overflow" }, displayLabel)))),
            react_1.default.createElement(react_bootstrap_1.Dropdown.Menu, { className: dropdownMenuClassName, "data-test-automation-id": "list" },
                header,
                !hasChildren || isNoResults ? (react_1.default.createElement("li", { className: "no-results", "data-test-automation-id": "noResult", role: "none" }, noResultsText)) : (react_1.default.createElement("li", { className: "multi-select-list-content", role: "menuitem" },
                    react_1.default.createElement("ul", { role: "tree", "aria-multiselectable": !this.props.isSingleSelect, "aria-activedescendant": this.state.ariaActivedescendant }, appendAriaPropsForMultiSelectChildren(children)))),
                hasChildren && !isNoResults ? this.renderShowMore() : null)));
    };
    MultiSelect.propTypes = __assign({}, FormControl_1.FormControl.propTypes, { id: prop_types_1.default.oneOfType([prop_types_1.default.string, prop_types_1.default.number]), isFilterable: prop_types_1.default.bool, searchText: prop_types_1.default.string, noResultsText: prop_types_1.default.string, label: prop_types_1.default.string, value: prop_types_1.default.any, testAutomationId: prop_types_1.default.string, className: prop_types_1.default.string, block: prop_types_1.default.bool, stretch: prop_types_1.default.bool, listHeader: prop_types_1.default.any, listItemsLimit: prop_types_1.default.number, labelItemsLimit: prop_types_1.default.number, onChange: prop_types_1.default.func, isSingleSelect: prop_types_1.default.bool, showMoreCountTextTemplate: prop_types_1.default.string, toggleAriaLabel: prop_types_1.default.string, selectedValuesPrefix: prop_types_1.default.string, applyLabelPrefixForSingleMode: prop_types_1.default.bool, applyLabelPrefixForMultiMode: prop_types_1.default.bool, ariaLabelledById: prop_types_1.default.string, stretchDropdownMenu: prop_types_1.default.bool, behaveAsFlat: prop_types_1.default.bool });
    MultiSelect.childContextTypes = {
        multiSelect: prop_types_1.default.object,
        level: prop_types_1.default.number,
        getOptionIdPrefix: prop_types_1.default.func,
        setAriaActivedescendant: prop_types_1.default.func
    };
    MultiSelect.Option = MultiSelectOption;
    MultiSelect.MasterOption = MultiSelectMasterOption;
    MultiSelect.Group = MultiSelectOptionGroup;
    MultiSelect.MultiSelectField = MultiSelectField;
    // extends defaultProps from superclass
    MultiSelect.defaultProps = __assign({}, FC.defaultProps, { isFilterable: false, labelItemsLimit: 3, testAutomationId: MultiSelectDefaultAutomationId, get searchText() {
            return index_en_US_1.default.SEARCH;
        },
        get noResultsText() {
            return index_en_US_1.default.NO_RESULTS;
        }, disabled: false, isSingleSelect: false, get showMoreCountTextTemplate() {
            return index_en_US_1.default.SHOW_MORE_COUNT;
        },
        /** example string format: "{filterName} filter" */
        get toggleAriaLabel() {
            return index_en_US_1.default.MULTI_SELECT_ARIA_LABEL;
        },
        /**  example string format: "selected {filterName}: {values}" */
        get selectedValuesPrefix() {
            return index_en_US_1.default.MULTI_SELECT_SELECTED_TITLE_LABEL;
        }, applyLabelPrefixForSingleMode: false, applyLabelPrefixForMultiMode: true, stretchDropdownMenu: false, behaveAsFlat: false });
    return MultiSelect;
}(FormControl_1.FormControl));
exports.MultiSelect = MultiSelect;
function appendAriaPropsForMultiSelectChildren(children) {
    var arr = lodash_1.default.flatten(toArray(children));
    return lodash_1.default.map(arr, function (child, index) {
        if (lodash_1.default.isEmpty(child)) {
            return child;
        }
        var childProps = child.props || {};
        return react_1.default.cloneElement(child, {
            ariaPosition: index + 1,
            ariaLevel: 1,
            ariaSetSize: arr.length
        }, childProps.children);
    });
}
function toArray(value) {
    return lodash_1.default.isArray(value) ? value : [value];
}
//# sourceMappingURL=MultiSelect.js.map