'use strict';

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.MultiSelect = void 0;

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _reactDom = require("react-dom");

var _Store = _interopRequireDefault(require("../../data/Store"));

var _FormGroup2 = require("./FormGroup");

var _FormControl2 = require("./FormControl");

var _Checkbox = require("./Checkbox");

var _Filter = require("../Filter");

var _Icon = require("../Icon");

var _Tooltip = require("../Tooltip");

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _Dropdown = _interopRequireDefault(require("react-bootstrap/lib/Dropdown"));

var _OverlayTrigger = _interopRequireDefault(require("react-bootstrap/lib/OverlayTrigger"));

var _lodash = _interopRequireDefault(require("lodash"));

var _classnames = _interopRequireDefault(require("classnames"));

var _utils = require("../list/utils");

var _utils2 = require("../../../utils");

var _FocusHelper = require("../../utils/FocusHelper");

var _constants = require("../../../utils/constants");

var FC = _FormControl2.FormControl;

var doNothing = function doNothing() {};

var MultiSelectField =
/*#__PURE__*/
function (_FormGroup) {
  (0, _inheritsLoose2.default)(MultiSelectField, _FormGroup);

  function MultiSelectField() {
    return _FormGroup.apply(this, arguments) || this;
  }

  var _proto = MultiSelectField.prototype;

  _proto.renderInput = function renderInput() {
    var _this$getPropsFromCon = this.getPropsFromContext(),
        children = _this$getPropsFromCon.children,
        innerLabel = _this$getPropsFromCon.innerLabel,
        props = (0, _objectWithoutPropertiesLoose2.default)(_this$getPropsFromCon, ["children", "innerLabel"]);

    return _react.default.createElement(MultiSelect, (0, _extends2.default)({}, props, {
      label: innerLabel,
      ref: "control",
      hasFormGroupContainer: true
    }), children);
  };

  return MultiSelectField;
}(_FormGroup2.FormGroup);

(0, _defineProperty2.default)(MultiSelectField, "propTypes", Object.assign({}, _FormGroup2.FormGroup.propTypes));
(0, _defineProperty2.default)(MultiSelectField, "defaultProps", Object.assign({}, _FormGroup2.FormGroup.defaultProps, {
  testAutomationId: 'multiSelect'
}));
var multiSelectInstanceCounter = 0;

var MultiSelectOption =
/*#__PURE__*/
function (_React$Component) {
  (0, _inheritsLoose2.default)(MultiSelectOption, _React$Component);

  MultiSelectOption.compareOptionValue = function compareOptionValue(source) {
    if (_lodash.default.isObject(source)) {
      return _lodash.default.matches(source);
    }

    return function (value) {
      return value === source;
    };
  };

  function MultiSelectOption(props, context) {
    var _this;

    _this = _React$Component.call(this, props, context) || this;
    _this.handleKeyDown = _this.handleKeyDown.bind((0, _assertThisInitialized2.default)(_this));
    return _this;
  }

  var _proto2 = MultiSelectOption.prototype;

  _proto2.getChildContext = function getChildContext() {
    var _this2 = this;

    return {
      getOptionIdPrefix: function getOptionIdPrefix() {
        return _this2.getId();
      }
    };
  };

  _proto2.handleKeyDown = function handleKeyDown(event) {
    switch (event.keyCode) {
      case 13: // enter

      case 32:
        // space
        this.refs.control.click();
        event.preventDefault();
        break;

      default:
        this.props.onKeyDown(event);
    }
  };

  _proto2.getId = function getId() {
    if (!_lodash.default.isFunction(this.context.getOptionIdPrefix)) {
      return null;
    }

    return this.context.getOptionIdPrefix() + "_" + (this.props.groupMaster ? 'masterOption' : 'option') + "_" + this.props.ariaPosition;
  };

  _proto2.finalRender = function finalRender(props, content) {
    if (_lodash.default.isFunction(this.props.tagRenderer)) {
      return this.props.tagRenderer(props, content);
    }

    return content;
  };

  _proto2.render = function render() {
    var _this3 = this;

    var _this$props = this.props,
        hint = _this$props.hint,
        description = _this$props.description;
    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 = [];

    if (!isMaster) {
      optionValues = [this.props.value];

      var index = _lodash.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 = 0;
      var groupFilteredLabels = this.context.multiSelectGroup.filteredLabels;
      optionValues.forEach(function (value) {
        var index = _lodash.default.findIndex(values, MultiSelectOption.compareOptionValue(value));

        if (index > -1) {
          selectedValuesCount++;
        }
      });

      if (selectedValuesCount > 0) {
        isSelected = selectedValuesCount === 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 || (0, _utils.highlight)(this.context.multiSelect.filterRegExp, this.props.label);
    var icon = this.props.icon;
    var content;
    var labelTitle = !description ? this.props.label : this.props.label + " - " + description;

    var label = _react.default.createElement("span", {
      title: hint ? null : labelTitle
    }, highlightedLabelText, description ? _react.default.createElement("span", {
      className: "select-description"
    }, " - ", description) : null);

    if (this.context.multiSelect.isSingleSelectMode) {
      isSelected = this.props.value !== undefined && MultiSelectOption.compareOptionValue(this.props.value)(values[0]);

      var onClick = function onClick(event) {
        if (_this3.props.value !== undefined) {
          _this3.context.multiSelect.setValues([_this3.props.value]);
        }

        _this3.context.multiSelect.close();
      };

      var labelProps = {
        className: (0, _classnames.default)('option-label', this.props.labelClassName, {
          'selected-option': isSelected
        }),
        ref: 'control'
      };

      if (!isOptionDisabled) {
        labelProps.onClick = onClick;
      }

      content = _react.default.createElement("span", labelProps, isSelected ? _react.default.createElement(_Icon.Icon, {
        "aria-hidden": "true",
        name: "checkbox-selected-readonly"
      }) : null, label, _react.default.createElement("div", {
        className: "icon-wrapper",
        "aria-hidden": "true"
      }, icon ? _react.default.createElement(_Icon.Icon, {
        name: icon
      }) : null));
    } else {
      content = _react.default.createElement(_Checkbox.Checkbox, {
        ref: "control",
        label: label,
        labelClassName: this.props.labelClassName,
        checked: isSelected,
        "aria-hidden": true,
        "aria-checked": isSelected === null ? 'mixed' : isSelected,
        disabled: isOptionDisabled,
        onChange: function onChange(value) {
          var isSelected = _this3.refs.control.getValue();

          var newValues = values.filter(function (value) {
            return _lodash.default.findIndex(optionValues, MultiSelectOption.compareOptionValue(value)) === -1;
          });

          if (isSelected) {
            newValues = values.concat(optionValues);
          }

          _this3.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: (0, _classnames.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.default.isFunction(_this3.context.setAriaActivedescendant)) {
          _this3.context.setAriaActivedescendant(optionId);
        }
      };
    }

    var finalContent = hint ? _react.default.createElement(_OverlayTrigger.default, {
      overlay: _react.default.createElement(_Tooltip.Tooltip, null, hint)
    }, content) : this.finalRender(liProps, content);
    return _react.default.createElement("li", liProps, finalContent);
  };

  return MultiSelectOption;
}(_react.default.Component);

(0, _defineProperty2.default)(MultiSelectOption, "contextTypes", {
  multiSelect: _propTypes.default.object,
  multiSelectGroup: _propTypes.default.object,
  getOptionIdPrefix: _propTypes.default.func,
  setAriaActivedescendant: _propTypes.default.func
});
(0, _defineProperty2.default)(MultiSelectOption, "childContextTypes", {
  getOptionIdPrefix: _propTypes.default.func
});
(0, _defineProperty2.default)(MultiSelectOption, "propTypes", {
  className: _propTypes.default.string,
  disabled: _propTypes.default.bool,
  groupMaster: _propTypes.default.bool,
  icon: _propTypes.default.string,
  label: _propTypes.default.string.isRequired,
  labelClassName: _propTypes.default.string,
  onKeyDown: _propTypes.default.func,
  onSelect: _propTypes.default.func,
  testAutomationId: _propTypes.default.string,
  value: _propTypes.default.any.isRequired,
  ariaPosition: _propTypes.default.number,
  ariaLevel: _propTypes.default.number,
  ariaSetSize: _propTypes.default.number,
  hint: _propTypes.default.string,
  customLabel: _propTypes.default.any,
  tagRenderer: _propTypes.default.func,
  description: _propTypes.default.string
});
(0, _defineProperty2.default)(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
});

var MultiSelectMasterOptionWrapper =
/*#__PURE__*/
function (_React$Component2) {
  (0, _inheritsLoose2.default)(MultiSelectMasterOptionWrapper, _React$Component2);

  function MultiSelectMasterOptionWrapper() {
    var _this4;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this4 = _React$Component2.call.apply(_React$Component2, [this].concat(args)) || this;
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this4), "tagRenderer", function (props, content) {
      return _react.default.createElement("div", {
        id: _this4.props.groupLabelId
      }, content);
    });
    return _this4;
  }

  var _proto3 = MultiSelectMasterOptionWrapper.prototype;

  _proto3.getTestAutomationId = function getTestAutomationId() {
    var testAutomationId = this.props.testAutomationId;
    var multiSelect = this.context.multiSelect;

    if (testAutomationId) {
      return testAutomationId;
    }

    return "optionMaster" + multiSelect.uid();
  };

  _proto3.render = function render() {
    return _react.default.createElement(MultiSelectOption, (0, _extends2.default)({}, this.props, {
      testAutomationId: this.getTestAutomationId(),
      tagRenderer: this.tagRenderer,
      groupMaster: true
    }));
  };

  return MultiSelectMasterOptionWrapper;
}(_react.default.Component);

(0, _defineProperty2.default)(MultiSelectMasterOptionWrapper, "propTypes", Object.assign({}, MultiSelectOption.propTypes, {
  testAutomationId: _propTypes.default.string,
  groupLabelId: _propTypes.default.string.isRequired
}));
(0, _defineProperty2.default)(MultiSelectMasterOptionWrapper, "defaultProps", Object.assign({}, MultiSelectOption.defaultProps, {
  testAutomationId: null
}));
(0, _defineProperty2.default)(MultiSelectMasterOptionWrapper, "contextTypes", {
  multiSelect: _propTypes.default.object
});

var MultiSelectMasterOption =
/*#__PURE__*/
function (_React$Component3) {
  (0, _inheritsLoose2.default)(MultiSelectMasterOption, _React$Component3);

  function MultiSelectMasterOption() {
    return _React$Component3.apply(this, arguments) || this;
  }

  var _proto4 = MultiSelectMasterOption.prototype;

  _proto4.render = function render() {
    return null;
  };

  return MultiSelectMasterOption;
}(_react.default.Component);

(0, _defineProperty2.default)(MultiSelectMasterOption, "propTypes", Object.assign({}, MultiSelectOption.propTypes));

function getChildrenValues(children) {
  return _lodash.default.flatten(_react.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;
    } else {
      return getChildrenValues(child.props.children);
    }
  }));
}

function hasValueChild(children) {
  var items = _react.default.Children.toArray(children);

  var hasValue = items.some(function (o) {
    return o && o.props && o.props.value !== undefined;
  });

  if (hasValue) {
    return true;
  }

  for (var _iterator = items, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
    var _ref;

    if (_isArray) {
      if (_i >= _iterator.length) break;
      _ref = _iterator[_i++];
    } else {
      _i = _iterator.next();
      if (_i.done) break;
      _ref = _i.value;
    }

    var child = _ref;

    if (child && child.props && child.props.children && hasValueChild(child.props.children)) {
      return true;
    }
  }

  return false;
}

function getChildrenLabels(children, filterCallback) {
  return _lodash.default.flatten(_react.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;
    } else {
      return getChildrenLabels(child.props.children, filterCallback);
    }
  }));
}

function getGroupValueOptionSize(children) {
  return _lodash.default.filter(_react.default.Children.toArray(children), function (o) {
    return !isMasterOption(o);
  }).map(function (o) {
    return o.key;
  }).length;
}

function isMasterOption(node) {
  return node && node.type === MultiSelectMasterOption;
}

var TreeItemAriaProps = ['aria-selected', 'aria-level', 'aria-setsize', 'aria-posinset', 'role'];

var MultiSelectOptionGroup =
/*#__PURE__*/
function (_React$Component4) {
  (0, _inheritsLoose2.default)(MultiSelectOptionGroup, _React$Component4);

  function MultiSelectOptionGroup() {
    var _this5;

    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }

    _this5 = _React$Component4.call.apply(_React$Component4, [this].concat(args)) || this;
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this5), "getOptionId", function () {
      if (_lodash.default.isFunction(_this5.context.getOptionIdPrefix)) {
        return _this5.context.getOptionIdPrefix() + "_" + _this5.props.ariaPosition;
      }

      return null;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this5), "getMasterOptionWrapperProps", function (props) {
      return _lodash.default.omit(props, TreeItemAriaProps);
    });
    return _this5;
  }

  var _proto5 = MultiSelectOptionGroup.prototype;

  _proto5.getChildContext = function getChildContext() {
    return {
      multiSelectGroup: {
        values: getChildrenValues(this.props.children),
        filteredLabels: getChildrenLabels(this.props.children, this.context.multiSelect.filterCallback)
      },
      getOptionIdPrefix: this.getOptionId
    };
  };

  _proto5.getSiblingOptionSize = function getSiblingOptionSize() {
    return getGroupValueOptionSize(this.props.children);
  };

  _proto5.getGroupProps = function getGroupProps(props) {
    if (_lodash.default.isEmpty(props)) {
      return null;
    }

    return _lodash.default.pick(props, TreeItemAriaProps);
  };

  _proto5.render = function render() {
    var _this6 = this;

    var children = _react.default.Children.toArray(this.props.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.default.cloneElement(child, {
        ariaPosition: isMasterNode ? _this6.props.ariaPosition : ariaPosition,
        ariaLevel: _this6.props.ariaLevel + (isMasterNode ? 0 : 1),
        ariaSetSize: isMasterNode ? _this6.props.ariaSetSize : _this6.getSiblingOptionSize(),
        onKeyDown: _this6.props.onKeyDown,
        onSelect: _this6.props.onSelect
      }, childProps.children);
    });

    var masterItem = _lodash.default.find(items, isMasterOption);

    var groupLabelId = this.getOptionId() + "_group_node";
    var masterOptionNode = masterItem ? _react.default.createElement(MultiSelectMasterOptionWrapper, (0, _extends2.default)({
      groupLabelId: groupLabelId
    }, this.getMasterOptionWrapperProps(masterItem.props))) : null;
    var valueItems = items.filter(function (node) {
      return !isMasterOption(node);
    });
    var hasAvailableValue = hasValueChild(valueItems);
    var groupProps = Object.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 = (0, _classnames.default)(groupProps.className, {
      'multi-select-has-children': !_lodash.default.isEmpty(valueItems)
    });
    return _react.default.createElement("div", groupProps, masterOptionNode, _react.default.createElement("ul", {
      className: (0, _classnames.default)('multi-select-group', this.props.className),
      role: hasAvailableValue ? 'group' : null,
      "aria-labelledby": hasAvailableValue && masterItem ? groupLabelId : null
    }, valueItems));
  };

  return MultiSelectOptionGroup;
}(_react.default.Component);

(0, _defineProperty2.default)(MultiSelectOptionGroup, "contextTypes", {
  multiSelect: _propTypes.default.object,
  multiSelectGroup: _propTypes.default.object,
  getOptionIdPrefix: _propTypes.default.func
});
(0, _defineProperty2.default)(MultiSelectOptionGroup, "childContextTypes", {
  multiSelectGroup: _propTypes.default.object,
  getOptionIdPrefix: _propTypes.default.func
});
(0, _defineProperty2.default)(MultiSelectOptionGroup, "propTypes", {
  children: _propTypes.default.node,
  className: _propTypes.default.string,
  onKeyDown: _propTypes.default.func,
  onSelect: _propTypes.default.func,
  testAutomationId: _propTypes.default.string,
  ariaPosition: _propTypes.default.number,
  ariaLevel: _propTypes.default.number,
  ariaSetSize: _propTypes.default.number
});
(0, _defineProperty2.default)(MultiSelectOptionGroup, "defaultProps", {
  children: null,
  className: null,
  onKeyDown: doNothing,
  onSelect: doNothing,
  testAutomationId: null,
  ariaPosition: 1,
  ariaLevel: 1,
  ariaSetSize: 1
});
var MultiSelectDefaultAutomationId = 'multiSelect';

var MultiSelect =
/*#__PURE__*/
function (_FormControl) {
  (0, _inheritsLoose2.default)(MultiSelect, _FormControl);

  // extends defaultProps from superclass
  function MultiSelect(_props, context) {
    var _this7;

    _this7 = _FormControl.call(this, _props, context) || this;
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "focusHelper", new _FocusHelper.FocusHelper());
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "saveMultiSelectRef", function (ref) {
      _this7.multiSelectEle = (0, _reactDom.findDOMNode)(ref);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "focus", function () {
      _this7.focusHelper.focus();
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "getTitle", function (selectedItemLabels) {
      if (_lodash.default.isEmpty(selectedItemLabels)) {
        return null;
      }

      var _this7$props = _this7.props,
          label = _this7$props.label,
          selectedValuesPrefix = _this7$props.selectedValuesPrefix;
      var valueStr = selectedItemLabels.join(', ');

      if (!_this7.shouldApplyLabelPrefix()) {
        return valueStr;
      }

      return (0, _utils2.translate)(selectedValuesPrefix, {
        filterName: label,
        values: valueStr
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "getAriaLabel", function () {
      var _this7$props2 = _this7.props,
          label = _this7$props2.label,
          toggleAriaLabel = _this7$props2.toggleAriaLabel;

      if (!_this7.shouldApplyLabelPrefix()) {
        return label;
      }

      return (0, _utils2.translate)(toggleAriaLabel, {
        filterName: label
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "getDisplayLabel", function (selectedItems) {
      var _this7$props3 = _this7.props,
          label = _this7$props3.label,
          labelItemsLimit = _this7$props3.labelItemsLimit;

      if (_lodash.default.isEmpty(selectedItems)) {
        return label;
      }

      var valueString = selectedItems.join(', ');

      if (selectedItems.length > labelItemsLimit) {
        valueString = selectedItems.slice(0, labelItemsLimit).concat(['...']).join(', ');
      }

      return _this7.shouldApplyLabelPrefix() ? label + ": " + valueString : valueString;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this7), "getSelectedItemLabels", function () {
      var children = _this7.props.children;

      var props = _this7.getPropsFromContext();

      var values = toArray(props.value);
      return getChildrenLabels(children, function (label, value) {
        return _lodash.default.findIndex(values, MultiSelectOption.compareOptionValue(value)) > -1;
      });
    });
    _this7.onToggle = _this7.onToggle.bind((0, _assertThisInitialized2.default)(_this7));
    _this7.onKeyDown = _this7.onKeyDown.bind((0, _assertThisInitialized2.default)(_this7));
    _this7.showMore = _this7.showMore.bind((0, _assertThisInitialized2.default)(_this7));
    _this7.filterByLimit = _this7.filterByLimit.bind((0, _assertThisInitialized2.default)(_this7));
    _this7.filterByLabelAndLimit = _this7.filterByLabelAndLimit.bind((0, _assertThisInitialized2.default)(_this7));
    _this7.listItemsFilteredByLimit = [];
    _this7.listItemsFiltered = [];
    _this7.state = {
      filterText: '',
      filterRegExp: null,
      filterCallback: _this7.filterByLimit,
      isOpen: false,
      isMoreShowed: false,
      hasFilterFocus: false,
      ariaActivedescendant: null
    };
    _this7.instanceId = ++multiSelectInstanceCounter;
    return _this7;
  }

  var _proto6 = MultiSelect.prototype;

  _proto6.componentDidMount = function componentDidMount() {
    var _this8 = this;

    this.multiSelectEle.addEventListener('keydown', function (event) {
      if (_this8.state.isOpen && event.key === _constants.KeyNames.Escape) {
        event.stopPropagation();
      }
    });
  };

  _proto6.filterByLimit = function filterByLimit(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;
  };

  _proto6.filterByLabelAndLimit = function filterByLabelAndLimit(label, value) {
    var filterRegExp = this.state.filterRegExp;

    if (filterRegExp === null) {
      return this.filterByLimit(label, value);
    } else {
      filterRegExp.lastIndex = 0;
      return filterRegExp.test(label) && this.filterByLimit(label, value);
    }
  };

  _proto6.outputConverter = function outputConverter(e) {
    return e;
  };

  _proto6.getValue = function getValue() {
    //FIXME Not implemented
    return null;
  };

  _proto6.getChildContext = function getChildContext() {
    var _this9 = this;

    var props = this.getPropsFromContext();
    return {
      multiSelect: {
        uid: function uid() {
          return ++_this9.uid;
        },
        values: toArray(props.value),
        setValues: function setValues(values) {
          if (_this9.props.isSingleSelect) {
            values = values[0];
          }

          props.onChange(values);
        },
        filterCallback: this.state.filterCallback,
        filterRegExp: this.state.filterRegExp,
        isSingleSelectMode: this.props.isSingleSelect,
        close: function close() {
          _this9.setState({
            isOpen: false
          });
        }
      },
      level: 0,
      getOptionIdPrefix: function getOptionIdPrefix() {
        return "select_" + _this9.instanceId;
      },
      setAriaActivedescendant: function setAriaActivedescendant(ariaActivedescendant) {
        return _this9.setState({
          ariaActivedescendant: ariaActivedescendant
        });
      }
    };
  };

  _proto6.onToggle = function onToggle(isOpen) {
    this.uid = 0;

    if (!isOpen && this.state.hasFilterFocus) {
      isOpen = true;
    }

    this.setState({
      isOpen: isOpen
    });
  };

  _proto6.onKeyDown = function onKeyDown(event) {
    switch (event.key) {
      case 'Escape':
      case 'Tab':
        this.setState({
          isOpen: false
        });
        break;
    }
  };

  _proto6.setTextFilter = function setTextFilter(text) {
    var filterRegExp = _Store.default.searchStringToRegExp(text);

    this.listItemsFiltered = [];
    this.listItemsFilteredByLimit = [];
    this.setState({
      filterText: text,
      filterRegExp: filterRegExp,
      filterCallback: this.filterByLabelAndLimit,
      isMoreShowed: false
    });
  };

  _proto6.showMore = function showMore(event) {
    event.preventDefault();
    this.setState({
      isMoreShowed: true
    });
  };

  _proto6.renderShowMore = function renderShowMore() {
    if (this.state.isMoreShowed) {
      return null;
    }

    var count = this.listItemsFiltered.length - this.listItemsFilteredByLimit.length;

    if (count <= 0) {
      return null;
    }

    return _react.default.createElement("li", {
      role: "menuitem"
    }, _react.default.createElement("a", {
      className: "show-more",
      onClick: this.showMore
    }, (0, _utils2.translate)(this.props.showMoreCountTextTemplate, {
      count: count
    })));
  }
  /** @param {Array<String>} selectedItemLabels */
  ;

  _proto6.shouldApplyLabelPrefix = function shouldApplyLabelPrefix() {
    var _this$props2 = this.props,
        isSingleSelect = _this$props2.isSingleSelect,
        applyLabelPrefixForSingleMode = _this$props2.applyLabelPrefixForSingleMode,
        applyLabelPrefixForMultiMode = _this$props2.applyLabelPrefixForMultiMode;
    return isSingleSelect ? applyLabelPrefixForSingleMode : applyLabelPrefixForMultiMode;
  }
  /** @returns {Array<String>}*/
  ;

  _proto6.render = function render() {
    var _this10 = this;

    this.uid = 0;
    var _this$props3 = this.props,
        id = _this$props3.id,
        isFilterable = _this$props3.isFilterable,
        searchText = _this$props3.searchText,
        noResultsText = _this$props3.noResultsText,
        label = _this$props3.label,
        value = _this$props3.value,
        children = _this$props3.children,
        labelItemsLimit = _this$props3.labelItemsLimit,
        testAutomationId = _this$props3.testAutomationId,
        className = _this$props3.className,
        block = _this$props3.block,
        stretch = _this$props3.stretch,
        listHeader = _this$props3.listHeader,
        listItemsLimit = _this$props3.listItemsLimit,
        showMoreCountTextTemplate = _this$props3.showMoreCountTextTemplate,
        onChange = _this$props3.onChange,
        ariaLabelledById = _this$props3.ariaLabelledById,
        toggleAriaLabel = _this$props3.toggleAriaLabel,
        stretchDropdownMenu = _this$props3.stretchDropdownMenu,
        otherProps = (0, _objectWithoutPropertiesLoose2.default)(_this$props3, ["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.default.createElement(_Filter.Filter, {
        value: this.state.filterText,
        testAutomationId: "filter",
        className: "multi-select-filter",
        ref: "filter",
        placeholder: searchText,
        tabIndex: "-1",
        noOffset: true,
        onFocus: function onFocus(event) {
          if (!_this10.state.hasFilterFocus) {
            _this10.refs.filter.focus();

            _this10.setState({
              hasFilterFocus: true
            });
          }
        },
        onBlur: function onBlur(event) {
          return _this10.setState({
            hasFilterFocus: false
          });
        },
        onKeyDown: function onKeyDown(event) {
          if (['ArrowUp', 'ArrowDown', 'Escape', 'Tab'].indexOf(event.key) === -1) {
            event.stopPropagation();
          }
        },
        onChange: function onChange(filterText) {
          return _this10.setTextFilter(filterText);
        }
      });
      isNoResults = getChildrenLabels(children, this.state.filterCallback).length === 0;
    }

    var header = null;

    if (listHeader && filter) {
      header = _react.default.createElement("li", {
        className: "multi-select-list-header",
        role: "none"
      }, listHeader, filter);
    } else if (listHeader) {
      header = _react.default.createElement("li", {
        className: "multi-select-list-header",
        role: "none"
      }, listHeader);
    } else if (filter) {
      header = _react.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.default.createElement(_Dropdown.default, (0, _extends2.default)({
      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: (0, _classnames.default)('multi-select', className, {
        'btn-block': stretch || block,
        stretch: stretch
      })
    }, this.getSafeProps(otherProps)), _react.default.createElement(_Dropdown.default.Toggle, {
      ref: this.focusHelper.setEl,
      "data-test-automation-id": "toggle",
      "aria-labelledby": ariaLabelledById,
      noCaret: true,
      block: true,
      disabled: this.props.disabled,
      "aria-label": this.getAriaLabel(),
      "aria-describedby": otherProps['aria-describedby'] || null,
      title: title
    }, _react.default.createElement("span", {
      className: "icon-wrapper",
      "aria-hidden": "true"
    }, _react.default.createElement(_Icon.Icon, {
      name: "chevron-down-small"
    })), _react.default.createElement("div", {
      className: "label-wrapper"
    }, _react.default.createElement("div", {
      className: "label-wrapper-inner"
    }, _react.default.createElement("div", {
      className: "label-text-overflow"
    }, displayLabel)))), _react.default.createElement(_Dropdown.default.Menu, {
      className: dropdownMenuClassName,
      "data-test-automation-id": "list"
    }, header, !hasChildren || isNoResults ? _react.default.createElement("li", {
      className: "no-results",
      "data-test-automation-id": "noResult",
      role: "none"
    }, noResultsText) : _react.default.createElement("li", {
      className: "multi-select-list-content",
      role: "menuitem"
    }, _react.default.createElement("ul", {
      role: "tree",
      "aria-multiselectable": !this.props.isSingleSelect,
      "aria-activedescendant": this.state.ariaActivedescendant
    }, appendAriaPropsForMultiSelectChildren(children))), hasChildren && !isNoResults ? this.renderShowMore() : null));
  };

  return MultiSelect;
}(_FormControl2.FormControl);

exports.MultiSelect = MultiSelect;
(0, _defineProperty2.default)(MultiSelect, "propTypes", Object.assign({}, _FormControl2.FormControl.propTypes, {
  id: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number]),
  isFilterable: _propTypes.default.bool,
  searchText: _propTypes.default.string,
  noResultsText: _propTypes.default.string,
  label: _propTypes.default.string,
  value: _propTypes.default.any,
  testAutomationId: _propTypes.default.string,
  className: _propTypes.default.string,
  block: _propTypes.default.bool,
  stretch: _propTypes.default.bool,
  listHeader: _propTypes.default.any,
  listItemsLimit: _propTypes.default.number,
  labelItemsLimit: _propTypes.default.number,
  onChange: _propTypes.default.func,
  isSingleSelect: _propTypes.default.bool,
  showMoreCountTextTemplate: _propTypes.default.string,
  toggleAriaLabel: _propTypes.default.string,
  selectedValuesPrefix: _propTypes.default.string,
  applyLabelPrefixForSingleMode: _propTypes.default.bool,
  applyLabelPrefixForMultiMode: _propTypes.default.bool,
  ariaLabelledById: _propTypes.default.string,
  stretchDropdownMenu: _propTypes.default.bool
}));
(0, _defineProperty2.default)(MultiSelect, "childContextTypes", {
  multiSelect: _propTypes.default.object,
  level: _propTypes.default.number,
  getOptionIdPrefix: _propTypes.default.func,
  setAriaActivedescendant: _propTypes.default.func
});
(0, _defineProperty2.default)(MultiSelect, "Option", MultiSelectOption);
(0, _defineProperty2.default)(MultiSelect, "MasterOption", MultiSelectMasterOption);
(0, _defineProperty2.default)(MultiSelect, "Group", MultiSelectOptionGroup);
(0, _defineProperty2.default)(MultiSelect, "MultiSelectField", MultiSelectField);
(0, _defineProperty2.default)(MultiSelect, "defaultProps", Object.assign({}, FC.defaultProps, {
  isFilterable: false,
  labelItemsLimit: 3,
  testAutomationId: MultiSelectDefaultAutomationId,
  searchText: 'TRANSLATE:SEARCH',
  noResultsText: 'TRANSLATE:NO_RESULTS',
  disabled: false,
  isSingleSelect: false,
  showMoreCountTextTemplate: 'TRANSLATE:SHOW_MORE_COUNT',

  /** example string format: "{filterName} filter" */
  toggleAriaLabel: 'TRANSLATE:MULTI_SELECT_ARIA_LABEL',

  /**  example string format: "selected {filterName}: {values}" */
  selectedValuesPrefix: 'TRANSLATE:MULTI_SELECT_SELECTED_TITLE_LABEL',
  applyLabelPrefixForSingleMode: false,
  applyLabelPrefixForMultiMode: true,
  stretchDropdownMenu: false
}));

function appendAriaPropsForMultiSelectChildren(children) {
  var arr = _lodash.default.flatten(toArray(children));

  return _lodash.default.map(arr, function (child, index) {
    if (_lodash.default.isEmpty(child)) {
      return child;
    }

    var childProps = child.props || {};
    return _react.default.cloneElement(child, {
      ariaPosition: index + 1,
      ariaLevel: 1,
      ariaSetSize: arr.length
    }, childProps.children);
  });
}

function toArray(value) {
  return _lodash.default.isArray(value) ? value : [value];
}