"use strict";

Liferay.Loader.define("@frontend-taglib-clay$clayui/multi-select@3.58.0/lib/index", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/autocomplete', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/drop-down', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/label', '@frontend-taglib-clay$clayui/loading-indicator', '@frontend-taglib-clay$clayui/shared', 'frontend-taglib-clay$classnames', 'frontend-taglib-clay$fuzzy', 'frontend-js-react-web$react'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.itemLabelFilter = exports.default = void 0;

    var _autocomplete = _interopRequireDefault(require("@frontend-taglib-clay$clayui/autocomplete"));

    var _button = require("@frontend-taglib-clay$clayui/button");

    var _dropDown = _interopRequireDefault(require("@frontend-taglib-clay$clayui/drop-down"));

    var _form = require("@frontend-taglib-clay$clayui/form");

    var _label = _interopRequireDefault(require("@frontend-taglib-clay$clayui/label"));

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

    var _shared = require("@frontend-taglib-clay$clayui/shared");

    var _classnames = _interopRequireDefault(require("frontend-taglib-clay$classnames"));

    var _fuzzy = _interopRequireDefault(require("frontend-taglib-clay$fuzzy"));

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _excluded = ["clearAllTitle", "closeButtonAriaLabel", "defaultItems", "defaultValue", "disabled", "disabledClearAll", "inputName", "inputValue", "isLoading", "isValid", "items", "locator", "menuRenderer", "onBlur", "onClearAllButtonClick", "onChange", "onFocus", "onItemsChange", "onKeyDown", "onPaste", "value", "sourceItems", "spritemap"];

    function _getRequireWildcardCache(nodeInterop) {
      if (typeof WeakMap !== "function") return null;var cacheBabelInterop = new WeakMap();var cacheNodeInterop = new WeakMap();return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
      })(nodeInterop);
    }

    function _interopRequireWildcard(obj, nodeInterop) {
      if (!nodeInterop && obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache(nodeInterop);if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _extends() {
      _extends = Object.assign || function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }return target;
      };return _extends.apply(this, arguments);
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }

    function _iterableToArray(iter) {
      if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) return _arrayLikeToArray(arr);
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }

    function _unsupportedIterableToArray(o, minLen) {
      if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
    }

    function _arrayLikeToArray(arr, len) {
      if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {
        arr2[i] = arr[i];
      }return arr2;
    }

    function _iterableToArrayLimit(arr, i) {
      var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];if (_i == null) return;var _arr = [];var _n = true;var _d = false;var _s, _e;try {
        for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    function _objectWithoutProperties(source, excluded) {
      if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];
        }
      }return target;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];
      }return target;
    }

    var DELIMITER_KEYS = ['Enter', ','];

    var MultiSelectMenuRenderer = function MultiSelectMenuRenderer(_ref) {
      var locator = _ref.locator,
          _ref$onItemClick = _ref.onItemClick,
          onItemClick = _ref$onItemClick === void 0 ? function () {} : _ref$onItemClick,
          sourceItems = _ref.sourceItems,
          value = _ref.value;
      return (/*#__PURE__*/_react.default.createElement(_dropDown.default.ItemList, null, sourceItems.map(function (item) {
          return (/*#__PURE__*/_react.default.createElement(_autocomplete.default.Item, {
              key: item[locator.value],
              match: value,
              onClick: function onClick() {
                return onItemClick(item);
              },
              value: item[locator.label]
            })
          );
        }))
      );
    };

    var ClayMultiSelect = /*#__PURE__*/_react.default.forwardRef(function (_ref2, ref) {
      var _ref2$clearAllTitle = _ref2.clearAllTitle,
          clearAllTitle = _ref2$clearAllTitle === void 0 ? 'Clear All' : _ref2$clearAllTitle,
          _ref2$closeButtonAria = _ref2.closeButtonAriaLabel,
          closeButtonAriaLabel = _ref2$closeButtonAria === void 0 ? 'Remove {0}' : _ref2$closeButtonAria,
          _ref2$defaultItems = _ref2.defaultItems,
          defaultItems = _ref2$defaultItems === void 0 ? [] : _ref2$defaultItems,
          _ref2$defaultValue = _ref2.defaultValue,
          defaultValue = _ref2$defaultValue === void 0 ? '' : _ref2$defaultValue,
          disabled = _ref2.disabled,
          disabledClearAll = _ref2.disabledClearAll,
          inputName = _ref2.inputName,
          inputValue = _ref2.inputValue,
          _ref2$isLoading = _ref2.isLoading,
          isLoading = _ref2$isLoading === void 0 ? false : _ref2$isLoading,
          _ref2$isValid = _ref2.isValid,
          isValid = _ref2$isValid === void 0 ? true : _ref2$isValid,
          items = _ref2.items,
          _ref2$locator = _ref2.locator,
          locator = _ref2$locator === void 0 ? {
        label: 'label',
        value: 'value'
      } : _ref2$locator,
          _ref2$menuRenderer = _ref2.menuRenderer,
          MenuRenderer = _ref2$menuRenderer === void 0 ? MultiSelectMenuRenderer : _ref2$menuRenderer,
          _ref2$onBlur = _ref2.onBlur,
          _onBlur = _ref2$onBlur === void 0 ? _shared.noop : _ref2$onBlur,
          onClearAllButtonClick = _ref2.onClearAllButtonClick,
          onChange = _ref2.onChange,
          _ref2$onFocus = _ref2.onFocus,
          _onFocus = _ref2$onFocus === void 0 ? _shared.noop : _ref2$onFocus,
          onItemsChange = _ref2.onItemsChange,
          _ref2$onKeyDown = _ref2.onKeyDown,
          onKeyDown = _ref2$onKeyDown === void 0 ? _shared.noop : _ref2$onKeyDown,
          _ref2$onPaste = _ref2.onPaste,
          onPaste = _ref2$onPaste === void 0 ? _shared.noop : _ref2$onPaste,
          value = _ref2.value,
          _ref2$sourceItems = _ref2.sourceItems,
          sourceItems = _ref2$sourceItems === void 0 ? [] : _ref2$sourceItems,
          spritemap = _ref2.spritemap,
          otherProps = _objectWithoutProperties(_ref2, _excluded);

      var defaultRef = _react.default.useRef(null);

      var inputRef = _react.default.useRef(null);

      var lastItemRef = _react.default.useRef(null);

      var _React$useState = _react.default.useState(false),
          _React$useState2 = _slicedToArray(_React$useState, 2),
          active = _React$useState2[0],
          setActive = _React$useState2[1];

      var _React$useState3 = _react.default.useState(false),
          _React$useState4 = _slicedToArray(_React$useState3, 2),
          isFocused = _React$useState4[0],
          setIsFocused = _React$useState4[1];

      var _useInternalState = (0, _shared.useInternalState)({
        defaultName: 'defaultItems',
        defaultValue: defaultItems,
        handleName: 'onItemsChange',
        name: 'items',
        onChange: onItemsChange,
        value: items
      }),
          _useInternalState2 = _slicedToArray(_useInternalState, 2),
          internalItems = _useInternalState2[0],
          setItems = _useInternalState2[1];

      var _useInternalState3 = (0, _shared.useInternalState)({
        defaultName: 'defaultValue',
        defaultValue: defaultValue,
        handleName: 'onChange',
        name: 'value',
        onChange: onChange,
        value: value !== null && value !== void 0 ? value : inputValue
      }),
          _useInternalState4 = _slicedToArray(_useInternalState3, 2),
          internalValue = _useInternalState4[0],
          setValue = _useInternalState4[1];

      (0, _react.useEffect)(function () {
        if (isFocused) {
          setActive(!!internalValue && sourceItems.length !== 0);
        }
      }, [internalValue, isFocused, sourceItems]);

      var setNewValue = function setNewValue(newVal) {
        setItems([].concat(_toConsumableArray(internalItems), [newVal]));
        setValue('');
      };

      var getSourceItemByLabel = function getSourceItemByLabel(label) {
        return sourceItems.find(function (item) {
          return item[locator.label] === label;
        });
      };

      var getNewItem = function getNewItem(value) {
        var _ref3;

        return getSourceItemByLabel(value) || (_ref3 = {}, _defineProperty(_ref3, locator.label, value), _defineProperty(_ref3, locator.value, value), _ref3);
      };

      var containerRef = ref || defaultRef;
      return (/*#__PURE__*/_react.default.createElement(_shared.FocusScope, {
          arrowKeysUpDown: false
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('form-control form-control-tag-group input-group', {
            focus: isFocused && isValid
          }),
          ref: containerRef
        }, /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, null, internalItems.map(function (item, i) {
          var removeItem = function removeItem() {
            return setItems([].concat(_toConsumableArray(internalItems.slice(0, i)), _toConsumableArray(internalItems.slice(i + 1))));
          };

          return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
              key: i
            }, /*#__PURE__*/_react.default.createElement(_label.default, {
              closeButtonProps: {
                'aria-label': (0, _shared.sub)(closeButtonAriaLabel, [item[locator.label]]),
                disabled: disabled,
                onClick: function onClick() {
                  if (inputRef.current) {
                    inputRef.current.focus();
                  }

                  removeItem();
                },
                ref: function ref(_ref4) {
                  if (i === internalItems.length - 1) {
                    lastItemRef.current = _ref4;
                  }
                }
              },
              onKeyDown: function onKeyDown(_ref5) {
                var key = _ref5.key;

                if (key !== _shared.Keys.Backspace) {
                  return;
                }

                if (inputRef.current) {
                  inputRef.current.focus();
                }

                removeItem();
              },
              spritemap: spritemap
            }, item[locator.label]), inputName && /*#__PURE__*/_react.default.createElement("input", {
              name: inputName,
              type: "hidden",
              value: item[locator.value]
            }))
          );
        }), /*#__PURE__*/_react.default.createElement("input", _extends({}, otherProps, {
          className: "form-control-inset",
          disabled: disabled,
          onBlur: function onBlur(event) {
            _onBlur(event);

            setIsFocused(false);
          },
          onChange: function onChange(event) {
            return setValue(event.target.value.replace(',', ''));
          },
          onFocus: function onFocus(event) {
            _onFocus(event);

            setIsFocused(true);
          },
          onKeyDown: function handleKeyDown(event) {
            onKeyDown(event);
            var key = event.key;

            if (key === _shared.Keys.Backspace && !internalValue) {
              event.preventDefault();
            }

            if (internalValue.trim() && DELIMITER_KEYS.includes(key)) {
              event.preventDefault();
              setNewValue(getNewItem(internalValue));
            } else if (!internalValue && key === _shared.Keys.Backspace && inputRef.current && lastItemRef.current) {
              inputRef.current.blur();
              lastItemRef.current.focus();
            }
          },
          onPaste: function handlePaste(event) {
            onPaste(event);
            var pastedText = event.clipboardData.getData('Text');
            var pastedItems = pastedText.split(',').map(function (itemLabel) {
              return getNewItem(itemLabel.trim());
            }).filter(Boolean);

            if (pastedItems.length > 0) {
              event.preventDefault();
              setItems([].concat(_toConsumableArray(internalItems), _toConsumableArray(pastedItems)));
            }
          },
          ref: inputRef,
          type: "text",
          value: internalValue
        }))), isLoading && /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          shrink: true
        }, /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, {
          small: true
        })), !disabled && !disabledClearAll && (internalValue || internalItems.length > 0) && /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          shrink: true
        }, /*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
          borderless: true,
          className: "component-action",
          displayType: "secondary",
          onClick: function onClick() {
            if (onClearAllButtonClick) {
              onClearAllButtonClick();
            } else {
              setItems([]);
              setValue('');
            }

            if (inputRef.current) {
              inputRef.current.focus();
            }
          },
          outline: true,
          spritemap: spritemap,
          symbol: "times-circle",
          title: clearAllTitle
        })), sourceItems.length > 0 && /*#__PURE__*/_react.default.createElement(_autocomplete.default.DropDown, {
          active: active,
          alignElementRef: containerRef,
          onSetActive: setActive
        }, /*#__PURE__*/_react.default.createElement(MenuRenderer, {
          inputValue: internalValue,
          locator: locator,
          onItemClick: function onItemClick(item) {
            setNewValue(item);

            if (inputRef.current) {
              inputRef.current.focus();
            }
          },
          sourceItems: sourceItems,
          value: internalValue
        }))))
      );
    });

    ClayMultiSelect.displayName = 'ClayMultiSelect';
    /**
     * Utility used for filtering an array of items based off the locator which
     * is set to `label` by default.
     */

    var itemLabelFilter = function itemLabelFilter(items, value) {
      var locator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'label';
      return items.filter(function (item) {
        return _fuzzy.default.match(value, item[locator]);
      });
    };

    exports.itemLabelFilter = itemLabelFilter;
    var _default = ClayMultiSelect;
    exports.default = _default;
  }
});
//# sourceMappingURL=index.js.map