"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _readOnlyError2 = _interopRequireDefault(require("@babel/runtime/helpers/readOnlyError"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _react = _interopRequireDefault(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _InputWithOptions2 = _interopRequireDefault(require("../InputWithOptions"));
var _InputWithTags = _interopRequireDefault(require("./InputWithTags"));
var _last = _interopRequireDefault(require("lodash/last"));
var _difference = _interopRequireDefault(require("difference"));
var _MultiSelectSt = require("./MultiSelect.st.css.js");
var _excluded = ["className", "data-ref"],
  _excluded2 = ["className", "ref"];
var _jsxFileName = "/home/builduser/work/57e038ea7326c1ec/packages/wix-design-system/dist/cjs/MultiSelect/MultiSelect.jsx",
  _MultiSelect;
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _superPropGet(t, o, e, r) { var p = (0, _get2["default"])((0, _getPrototypeOf2["default"])(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
var MultiSelect = /*#__PURE__*/function (_InputWithOptions) {
  function MultiSelect(props) {
    var _this;
    (0, _classCallCheck2["default"])(this, MultiSelect);
    _this = _callSuper(this, MultiSelect, [props]);
    _this.onKeyDown = _this.onKeyDown.bind(_this);
    _this.onPaste = _this.onPaste.bind(_this);
    _this._onBlur = _this._onBlur.bind(_this);
    _this.state = _objectSpread(_objectSpread({}, _this.state), {}, {
      pasteDetected: false
    });
    return _this;
  }
  (0, _inherits2["default"])(MultiSelect, _InputWithOptions);
  return (0, _createClass2["default"])(MultiSelect, [{
    key: "hideOptions",
    value: function hideOptions() {
      _superPropGet(MultiSelect, "hideOptions", this, 3)([]);
      if (this.props.clearOnBlur) {
        this.clearInput();
      }
    }
  }, {
    key: "rootAdditionalProps",
    value: function rootAdditionalProps() {
      var className = this.props.className;
      return {
        className: (0, _MultiSelectSt.st)(_MultiSelectSt.classes.root, className)
      };
    }
  }, {
    key: "onClickOutside",
    value: function onClickOutside() {
      if (this.state.showOptions) {
        this.hideOptions();
      }
    }
  }, {
    key: "_onBlur",
    value: function _onBlur(event) {
      _superPropGet(MultiSelect, "_onBlur", this, 3)([event]);
      this.props.acceptOnBlur && this.submitValue(this.state.inputValue);
    }
  }, {
    key: "getUnselectedOptions",
    value: function getUnselectedOptions() {
      var optionIds = this.props.options.map(function (option) {
        return option.id;
      });
      var tagIds = this.props.tags.map(function (tag) {
        return tag.id;
      });
      var unselectedOptionsIds = (0, _difference["default"])(optionIds, tagIds);
      return this.props.options.filter(function (option) {
        return unselectedOptionsIds.includes(option.id);
      });
    }
  }, {
    key: "dropdownAdditionalProps",
    value: function dropdownAdditionalProps() {
      var _this$props = this.props,
        predicate = _this$props.predicate,
        emptyStateMessage = _this$props.emptyStateMessage,
        fixedFooter = _this$props.fixedFooter;
      var filterFunc = this.state.isEditing ? predicate : function () {
        return true;
      };
      var filtered = this.getUnselectedOptions().filter(filterFunc);
      var options = filtered;
      if (emptyStateMessage && filtered.length === 0) {
        options = [{
          id: 'empty-state-message',
          value: emptyStateMessage,
          disabled: true
        }];
      }
      return {
        options: options,
        closeOnSelect: false,
        selectedHighlight: false,
        selectedId: -1,
        fixedFooter: fixedFooter
      };
    }
  }, {
    key: "closeOnSelect",
    value: function closeOnSelect() {
      return false;
    }
  }, {
    key: "isDropdownLayoutVisible",
    value: function isDropdownLayoutVisible() {
      // Don't show dropdown if there are no options available
      var options = this.props.options || [];
      var isWithOtherItems = !!this.props.fixedFooter || !!this.props.emptyStateMessage || !!this.props.customDropdownContent;
      return _superPropGet(MultiSelect, "isDropdownLayoutVisible", this, 3)([]) && (options.length > 0 || isWithOtherItems);
    }
  }, {
    key: "inputAdditionalProps",
    value: function inputAdditionalProps() {
      return {
        readOnly: this.props.readOnly,
        disableEditing: true,
        inputElement: /*#__PURE__*/_react["default"].createElement(_InputWithTags["default"], {
          className: _MultiSelectSt.classes.inputWithTags,
          onReorder: this.props.onReorder,
          maxNumRows: this.props.maxNumRows,
          mode: this.props.mode,
          hideCustomSuffix: this.isDropdownLayoutVisible(),
          customSuffix: this.props.customSuffix,
          customPrefix: this.props.customPrefix,
          border: this.props.border,
          __self: this,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 102,
            columnNumber: 9
          }
        }),
        onKeyDown: this.onKeyDown,
        delimiters: this.props.delimiters,
        onPaste: this.onPaste
      };
    }
  }, {
    key: "onPaste",
    value: function onPaste() {
      this.setState({
        pasteDetected: true
      });
    }
  }, {
    key: "_splitByDelimitersAndTrim",
    value: function _splitByDelimitersAndTrim(value) {
      var delimitersRegexp = new RegExp(this.props.delimiters.join('|'), 'g');
      return value.split(delimitersRegexp).map(function (str) {
        return str.trim();
      }).filter(function (str) {
        return str;
      });
    }
  }, {
    key: "_onChange",
    value: function _onChange(event) {
      var _this2 = this;
      if (this.state.pasteDetected) {
        var value = event.target.value;
        this.setState({
          pasteDetected: false
        }, function () {
          _this2.submitValue(value);
        });
      } else {
        this.setState({
          inputValue: event.target.value
        });
        this.props.onChange && this.props.onChange(event);
      }
      // If the input value is not empty, should show the options
      if (event.target.value.trim()) {
        this.showOptions();
      }
    }
  }, {
    key: "_onSelect",
    value: function _onSelect(option) {
      this.onSelect(option);
    }
  }, {
    key: "_onManuallyInput",
    value: function _onManuallyInput(inputValue, event) {
      var value = this.props.value;

      // FIXME: InputWithOptions is not updating it's inputValue state when the `value` prop changes.
      // So using `value` here, covers for that bug. (This is tested)
      // BTW: Previously, `value` was used to trigger onSelect, and `inputValue` was used to trigger onManuallyInput. Which is crazy.
      // So now both of them trigger a submit (onManuallyInput).
      var _value = value && value.trim() || inputValue && inputValue.trim();
      this.submitValue(_value);
      _value && event.preventDefault();
      if (this.closeOnSelect()) {
        this.hideOptions();
      }
    }
  }, {
    key: "getManualSubmitKeys",
    value: function getManualSubmitKeys() {
      return ['Enter', 'Tab'].concat(this.props.delimiters);
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(event) {
      var _this$props2 = this.props,
        tags = _this$props2.tags,
        value = _this$props2.value,
        onRemoveTag = _this$props2.onRemoveTag;
      if (tags.length > 0 && (event.key === 'Delete' || event.key === 'Backspace') && value && value.length === 0) {
        onRemoveTag((0, _last["default"])(tags).id);
      }
      if (event.key === 'Escape') {
        this.clearInput();
        _superPropGet(MultiSelect, "hideOptions", this, 3)([]);
        event.stopPropagation();
      }
      if (this.props.onKeyDown) {
        this.props.onKeyDown(event);
      }
    }
  }, {
    key: "optionToTag",
    value: function optionToTag(_ref) {
      var id = _ref.id,
        value = _ref.value,
        tag = _ref.tag,
        theme = _ref.theme;
      return tag ? _objectSpread({
        id: id
      }, tag) : {
        id: id,
        label: value,
        theme: theme
      };
    }
  }, {
    key: "onSelect",
    value: function onSelect(option) {
      this.clearInput();
      var onSelect = this.props.onSelect;
      if (onSelect) {
        onSelect(this.props.options.find(function (o) {
          return o.id === option.id;
        }));
      }
    }
  }, {
    key: "submitValue",
    value: function submitValue(inputValue) {
      if (!inputValue) {
        return;
      }
      var onManuallyInput = this.props.onManuallyInput;
      var values = this._splitByDelimitersAndTrim(inputValue);
      onManuallyInput && values.length && onManuallyInput(values);
      this.clearInput();
    }
  }, {
    key: "clearInput",
    value: function clearInput() {
      this.input.current && this.input.current.clear();
      if (this.props.onChange) {
        this.props.onChange({
          target: {
            value: ''
          }
        });
      }
    }
  }]);
}(_InputWithOptions2["default"]);
_MultiSelect = MultiSelect;
MultiSelect.autoSizeInput = function (_ref2) {
  var className = _ref2.className,
    dataRef = _ref2['data-ref'],
    rest = (0, _objectWithoutProperties2["default"])(_ref2, _excluded);
  var inputClassName = (0, _classnames["default"])(className, _MultiSelectSt.classes.autoSizeInput);
  return /*#__PURE__*/_react["default"].createElement("input", (0, _extends2["default"])({}, rest, {
    ref: dataRef,
    className: inputClassName,
    __self: _MultiSelect,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 230,
      columnNumber: 12
    }
  }));
};
MultiSelect.autoSizeInputWithRef = function () {
  return /*#__PURE__*/_react["default"].forwardRef(function (props, ref) {
    return function (_ref3) {
      var className = _ref3.className,
        ref = _ref3.ref,
        rest = (0, _objectWithoutProperties2["default"])(_ref3, _excluded2);
      var inputClassName = (0, _classnames["default"])(className, _MultiSelectSt.classes.autoSizeInput);
      return /*#__PURE__*/_react["default"].createElement("input", (0, _extends2["default"])({}, rest, {
        ref: ref,
        className: inputClassName,
        __self: _MultiSelect,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 237,
          columnNumber: 16
        }
      }));
    }(_objectSpread(_objectSpread({}, props), {}, {
      ref: ref
    }));
  });
};
MultiSelect.displayName = 'MultiSelect';
MultiSelect.defaultProps = _objectSpread(_objectSpread({}, _InputWithOptions2["default"].defaultProps), {}, {
  predicate: function predicate() {
    return true;
  },
  tags: [],
  delimiters: [','],
  clearOnBlur: true,
  customInput: MultiSelect.autoSizeInputWithRef()
});
var _default = exports["default"] = MultiSelect;