Liferay.Loader.define("asset-taglib@5.4.12/asset_categories_selector/AssetVocabularyCategoriesSelector.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/data-provider', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/multi-select', 'frontend-js-react-web$classnames', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../utils/lang.es'], 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.default = void 0;

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

    var _dataProvider = require("@frontend-taglib-clay$clayui/data-provider");

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

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

    var _multiSelect = _interopRequireDefault(require("@frontend-taglib-clay$clayui/multi-select"));

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

    var _frontendJsReactWeb = require("frontend-js-react-web");

    var _frontendJsWeb = require("frontend-js-web");

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

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

    var _lang = _interopRequireDefault(require("../utils/lang.es"));

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (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 _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

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

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_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 AssetVocabulariesCategoriesSelector(_ref) {
      var eventName = _ref.eventName,
          id = _ref.id,
          _ref$isValid = _ref.isValid,
          isValid = _ref$isValid === void 0 ? true : _ref$isValid,
          _ref$groupIds = _ref.groupIds,
          groupIds = _ref$groupIds === void 0 ? [] : _ref$groupIds,
          inputName = _ref.inputName,
          label = _ref.label,
          _ref$onSelectedItemsC = _ref.onSelectedItemsChange,
          onSelectedItemsChange = _ref$onSelectedItemsC === void 0 ? function () {} : _ref$onSelectedItemsC,
          portletURL = _ref.portletURL,
          required = _ref.required,
          _ref$selectedItems = _ref.selectedItems,
          selectedItems = _ref$selectedItems === void 0 ? [] : _ref$selectedItems,
          singleSelect = _ref.singleSelect,
          _ref$sourceItemsVocab = _ref.sourceItemsVocabularyIds,
          sourceItemsVocabularyIds = _ref$sourceItemsVocab === void 0 ? [] : _ref$sourceItemsVocab,
          useFallbackInput = _ref.useFallbackInput;

      var _useState = (0, _react.useState)(''),
          _useState2 = _slicedToArray(_useState, 2),
          inputValue = _useState2[0],
          setInputValue = _useState2[1];

      var _useState3 = (0, _react.useState)([]),
          _useState4 = _slicedToArray(_useState3, 2),
          invalidItems = _useState4[0],
          setInvalidItems = _useState4[1];

      var _useResource = (0, _dataProvider.useResource)({
        fetchOptions: {
          body: new URLSearchParams({
            cmd: JSON.stringify({
              '/assetcategory/search': {
                '-obc': null,
                end: 20,
                groupIds: groupIds,
                name: "%".concat(inputValue.toLowerCase(), "%"),
                start: 0,
                vocabularyIds: sourceItemsVocabularyIds
              }
            }),
            p_auth: Liferay.authToken
          }),
          credentials: 'include',
          method: 'POST',
          'x-csrf-token': Liferay.authToken
        },
        link: "".concat(window.location.origin).concat(themeDisplay.getPathContext(), "\n\t\t\t\t/api/jsonws/invoke")
      }),
          refetch = _useResource.refetch,
          resource = _useResource.resource;

      var previousInputValue = (0, _frontendJsReactWeb.usePrevious)(inputValue);
      (0, _react.useEffect)(function () {
        if (inputValue && inputValue !== previousInputValue) {
          refetch();
        }
      }, [inputValue, previousInputValue, refetch]);

      var getUnique = function getUnique(arr, property) {
        return arr.map(function (element) {
          return element[property];
        }).map(function (element, index, array) {
          return array.indexOf(element) === index && index;
        }).filter(function (element) {
          return arr[element];
        }).map(function (element) {
          return arr[element];
        });
      };

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "field-content vocabulary-validation"
        }, /*#__PURE__*/_react.default.createElement(_form.default.Group, {
          className: (0, _classnames.default)({
            'has-error': invalidItems && invalidItems.length > 0 || !isValid
          }),
          id: id
        }, useFallbackInput && /*#__PURE__*/_react.default.createElement("input", {
          name: inputName,
          type: "hidden",
          value: selectedItems.map(function (item) {
            return item.value;
          }).join()
        }), label && /*#__PURE__*/_react.default.createElement("label", {
          htmlFor: inputName + '_MultiSelect'
        }, label, required && /*#__PURE__*/_react.default.createElement("span", {
          className: "inline-item inline-item-after reference-mark vocabulary-required"
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: 'asterisk'
        }), /*#__PURE__*/_react.default.createElement("span", {
          className: "hide-accessible"
        }, Liferay.Language.get('required')))), /*#__PURE__*/_react.default.createElement(_form.ClayInput.Group, null, /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, null, /*#__PURE__*/_react.default.createElement(_multiSelect.default, {
          id: inputName + '_MultiSelect',
          inputName: inputName,
          items: selectedItems,
          onChange: setInputValue,
          onItemsChange: function handleItemsChange(items) {
            var addedItems = getUnique(items.filter(function (item) {
              return !selectedItems.find(function (selectedItem) {
                return selectedItem.value === item.value;
              });
            }), 'label');
            var invalidAddedItems = [];
            var validAddedItems = [];
            addedItems.map(function (item) {
              if (resource.find(function (sourceItem) {
                return sourceItem.titleCurrentValue === item.label;
              })) {
                validAddedItems.push(item);
              } else {
                invalidAddedItems.push(item);
              }
            });
            var removedItems = selectedItems.filter(function (selectedItem) {
              return !items.find(function (item) {
                return item.value === selectedItem.value;
              });
            });
            var current = [].concat(_toConsumableArray(selectedItems), validAddedItems).filter(function (item) {
              return !removedItems.find(function (removedItem) {
                return removedItem.value === item.value;
              });
            });
            setInvalidItems(invalidAddedItems);
            onSelectedItemsChange(current);
          },
          sourceItems: resource ? resource.map(function (category) {
            return {
              label: category.titleCurrentValue,
              value: category.categoryId
            };
          }) : [],
          value: inputValue
        }), invalidItems && invalidItems.length > 0 && /*#__PURE__*/_react.default.createElement(_form.default.FeedbackGroup, null, /*#__PURE__*/_react.default.createElement(_form.default.FeedbackItem, {
          "aria-live": "polite"
        }, /*#__PURE__*/_react.default.createElement(_form.default.FeedbackIndicator, {
          symbol: "info-circle"
        }), _lang.default.sub(Liferay.Language.get("category-x-does-not-exist"), [invalidItems.map(function (item) {
          return item.label;
        }).join(',')]))), !isValid && /*#__PURE__*/_react.default.createElement(_form.default.FeedbackGroup, null, /*#__PURE__*/_react.default.createElement(_form.default.FeedbackItem, null, /*#__PURE__*/_react.default.createElement(_form.default.FeedbackIndicator, {
          symbol: "info-circle"
        }), /*#__PURE__*/_react.default.createElement("span", {
          className: "ml-2"
        }, Liferay.Language.get('this-field-is-required'))))), /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          shrink: true
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          displayType: "secondary",
          onClick: function handleSelectButtonClick() {

            var url = function sub(str, obj) {
              return str.replace(/\{([^}]+)\}/g, function (_, m) {
                return obj[m];
              });
            }(decodeURIComponent(portletURL), {
              selectedCategories: selectedItems.map(function (item) {
                return item.value;
              }).join(),
              singleSelect: singleSelect,
              vocabularyIds: sourceItemsVocabularyIds.concat()
            });
            var itemSelectorDialog = new _frontendJsWeb.ItemSelectorDialog({
              buttonAddLabel: Liferay.Language.get('done'),
              dialogClasses: 'modal-lg',
              eventName: eventName,
              title: label ? Liferay.Util.sub(Liferay.Language.get('select-x'), label) : Liferay.Language.get('select-categories'),
              url: url
            });
            itemSelectorDialog.open();
            itemSelectorDialog.on('selectedItemChange', function (event) {
              var dialogSelectedItems = event.selectedItem;

              if (dialogSelectedItems) {
                var newValues = Object.keys(dialogSelectedItems).reduce(function (acc, itemKey) {
                  var item = dialogSelectedItems[itemKey];

                  if (!item.unchecked) {
                    acc.push({
                      label: item.value,
                      value: item.categoryId
                    });
                  }

                  return acc;
                }, []);
                onSelectedItemsChange(newValues);
              }
            });
          }
        }, Liferay.Language.get('select'))))))
      );
    }

    var _default = AssetVocabulariesCategoriesSelector;
    exports.default = _default;
    //# sourceMappingURL=AssetVocabularyCategoriesSelector.es.js.map
  }
});
//# sourceMappingURL=AssetVocabularyCategoriesSelector.es.js.map