Liferay.Loader.define("document-library-web@5.0.84/document_library/js/categorization/tags/EditTagsModal.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/alert', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/loading-indicator', '@frontend-taglib-clay$clayui/modal', 'asset-taglib', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', './EditTagsContext.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 _alert = _interopRequireDefault(require("@frontend-taglib-clay$clayui/alert"));

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

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

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

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

    var _assetTaglib = require("asset-taglib");

    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 _EditTagsContext = _interopRequireDefault(require("./EditTagsContext.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 _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;
    }

    var URL_SELECTION = '/bulk/v1.0/bulk-selection',
        URL_TAGS = '/bulk/v1.0/keywords/common',
        URL_UPDATE_TAGS = '/bulk/v1.0/keywords/batch';

    var noop = function noop() {};

    var EditTagsModal = function EditTagsModal(_ref) {
      var fileEntries = _ref.fileEntries,
          folderId = _ref.folderId,
          groupIds = _ref.groupIds,
          pathModule = _ref.pathModule,
          repositoryId = _ref.repositoryId,
          _ref$selectAll = _ref.selectAll,
          selectAll = _ref$selectAll === void 0 ? false : _ref$selectAll,
          observer = _ref.observer,
          _ref$onModalClose = _ref.onModalClose,
          onModalClose = _ref$onModalClose === void 0 ? noop : _ref$onModalClose;

      var _useContext = (0, _react.useContext)(_EditTagsContext.default),
          namespace = _useContext.namespace;

      var isMounted = (0, _frontendJsReactWeb.useIsMounted)(); // Flag that indicates whether new selected items must be added to old ones
      // or replace them.

      var _useState = (0, _react.useState)(true),
          _useState2 = _slicedToArray(_useState, 2),
          append = _useState2[0],
          setAppend = _useState2[1];

      var _useState3 = (0, _react.useState)(''),
          _useState4 = _slicedToArray(_useState3, 2),
          description = _useState4[0],
          setDescription = _useState4[1];

      var _useState5 = (0, _react.useState)(true),
          _useState6 = _slicedToArray(_useState5, 2),
          loading = _useState6[0],
          setLoading = _useState6[1];

      var _useState7 = (0, _react.useState)(false),
          _useState8 = _slicedToArray(_useState7, 2),
          multiple = _useState8[0],
          setMultiple = _useState8[1]; // Selected items received from the server and saved to compare with new
      // ones.


      var _useState9 = (0, _react.useState)([]),
          _useState10 = _slicedToArray(_useState9, 2),
          initialSelectedItems = _useState10[0],
          setInitialSelectedItems = _useState10[1];

      var _useState11 = (0, _react.useState)(),
          _useState12 = _slicedToArray(_useState11, 2),
          inputValue = _useState12[0],
          setInputValue = _useState12[1]; // Current selected items.


      var _useState13 = (0, _react.useState)([]),
          _useState14 = _slicedToArray(_useState13, 2),
          selectedItems = _useState14[0],
          setSelectedItems = _useState14[1];

      var _useState15 = (0, _react.useState)('add'),
          _useState16 = _slicedToArray(_useState15, 2),
          selectedRadioGroupValue = _useState16[0],
          setSelectedRadioGroupValue = _useState16[1];

      var fileEntriesLength = fileEntries && fileEntries.length;
      var fetchTags = (0, _react.useCallback)(function (url, method, bodyData) {
        var init = {
          body: JSON.stringify(bodyData),
          headers: {
            'Content-Type': 'application/json'
          },
          method: method
        };
        return (0, _frontendJsWeb.fetch)("".concat(pathModule).concat(url), init).then(function (response) {
          return response.json();
        }).catch(function () {
          onModalClose();
        });
      }, [onModalClose, pathModule]);

      var getDescription = function getDescription(size) {
        if (size === 1) {
          return Liferay.Language.get('you-are-editing-the-tags-for-the-selected-item');
        }

        return Liferay.Util.sub(Liferay.Language.get('you-are-editing-the-common-tags-for-x-items.-select-edit-or-replace-current-tags'), size);
      }; // This makes the component fetch selected items only after mounting it
      // (a.k.a. first render).


      (0, _react.useEffect)(function () {
        var selection = {
          documentIds: fileEntries,
          selectionScope: {
            folderId: folderId,
            repositoryId: repositoryId,
            selectAll: selectAll
          }
        };
        Promise.all([fetchTags(URL_TAGS, 'POST', selection), fetchTags(URL_SELECTION, 'POST', selection)]).then(function (_ref2) {
          var _ref3 = _slicedToArray(_ref2, 2),
              responseTags = _ref3[0],
              responseSelection = _ref3[1];

          if (responseTags && responseSelection) {
            var _selectedItems = (responseTags.items || []).map(function (_ref4) {
              var name = _ref4.name;
              return {
                label: name,
                value: name
              };
            });

            if (isMounted()) {
              setLoading(false);
              setInitialSelectedItems(_selectedItems);
              setSelectedItems(_selectedItems);
              setDescription(getDescription(responseSelection.size));
              setMultiple(fileEntries.length > 1 || selectAll);
            }
          }
        });
      }, [fetchTags, fileEntries, fileEntriesLength, folderId, isMounted, repositoryId, selectAll]);

      return (/*#__PURE__*/_react.default.createElement(_modal.default, {
          observer: observer,
          size: "md"
        }, /*#__PURE__*/_react.default.createElement(_modal.default.Header, null, Liferay.Language.get('edit-tags')), /*#__PURE__*/_react.default.createElement("form", {
          onSubmit: function handleSubmit(event) {
            event.preventDefault();
            var addedLabels = !append ? selectedItems : selectedItems.filter(function (selectedItem) {
              return !initialSelectedItems.find(function (initialSelectedItem) {
                return initialSelectedItem.value === selectedItem.value;
              });
            });
            var removedLabels = initialSelectedItems.filter(function (initialSelectedItem) {
              return !selectedItems.find(function (selectedItem) {
                return selectedItem.value === initialSelectedItem.value;
              });
            });
            fetchTags(URL_UPDATE_TAGS, append ? 'PATCH' : 'PUT', {
              documentBulkSelection: {
                documentIds: fileEntries,
                selectionScope: {
                  folderId: folderId,
                  repositoryId: repositoryId,
                  selectAll: selectAll
                }
              },
              keywordsToAdd: addedLabels.map(function (addedLabel) {
                return addedLabel.value;
              }),
              keywordsToRemove: removedLabels.map(function (removedLabel) {
                return removedLabel.value;
              })
            }).then(function () {
              var bulkStatusComponent = Liferay.component("".concat(namespace, "BulkStatus"));

              if (bulkStatusComponent) {
                bulkStatusComponent.startWatch();
              }

              onModalClose();
            });
          }
        }, /*#__PURE__*/_react.default.createElement(_modal.default.Body, null, loading && /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null), selectAll && /*#__PURE__*/_react.default.createElement(_alert.default, {
          title: ""
        }, Liferay.Language.get('this-operation-will-not-be-applied-to-any-of-the-selected-folders')), /*#__PURE__*/_react.default.createElement("p", null, description), multiple && /*#__PURE__*/_react.default.createElement(_form.ClayRadioGroup, {
          name: "add-replace",
          onSelectedValueChange: function handleMultipleSelectedOptionChange(value) {
            setAppend(value === 'add');
            setSelectedRadioGroupValue(value);
          },
          selectedValue: selectedRadioGroupValue
        }, /*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
          label: Liferay.Language.get('edit'),
          value: "add"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "form-text"
        }, Liferay.Language.get('add-new-tags-or-remove-common-tags'))), /*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
          label: Liferay.Language.get('replace'),
          value: "replace"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "form-text"
        }, Liferay.Language.get('these-tags-replace-all-existing-tags')))), /*#__PURE__*/_react.default.createElement(_assetTaglib.AssetTagsSelector, {
          groupIds: groupIds,
          inputName: "".concat(namespace, "_hiddenInput"),
          inputValue: inputValue,
          onInputValueChange: setInputValue,
          onSelectedItemsChange: setSelectedItems,
          selectedItems: selectedItems
        })), /*#__PURE__*/_react.default.createElement(_modal.default.Footer, {
          last: /*#__PURE__*/_react.default.createElement(_button.default.Group, {
            spaced: true
          }, /*#__PURE__*/_react.default.createElement(_button.default, {
            displayType: "secondary",
            onClick: onModalClose
          }, Liferay.Language.get('cancel')), /*#__PURE__*/_react.default.createElement(_button.default, {
            displayType: "primary",
            type: "submit"
          }, Liferay.Language.get('save')))
        })))
      );
    };

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