Liferay.Loader.define("sharing-web@2.0.45/sharing/js/Sharing.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/data-provider', '@frontend-taglib-clay$clayui/drop-down', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/modal', '@frontend-taglib-clay$clayui/multi-select', '@frontend-taglib-clay$clayui/sticker', 'frontend-js-web', '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.default = void 0;

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

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

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

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

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

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

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

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

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

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

    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 _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 _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 filterDuplicateItems(items) {
      return items.filter(function (item, index) {
        return items.findIndex(function (newItem) {
          return newItem.value.toLowerCase() === item.value.toLowerCase();
        }) === index;
      });
    }

    var SharingAutocomplete = function SharingAutocomplete(_ref) {
      var _ref$onItemClick = _ref.onItemClick,
          onItemClick = _ref$onItemClick === void 0 ? function () {} : _ref$onItemClick,
          sourceItems = _ref.sourceItems;
      return (/*#__PURE__*/_react.default.createElement(_dropDown.default.ItemList, null, sourceItems.map(function (item) {
          return (/*#__PURE__*/_react.default.createElement(_dropDown.default.Item, {
              key: item.id,
              onClick: function onClick() {
                return onItemClick(item);
              }
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "autofit-row autofit-row-center"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "autofit-col mr-3"
            }, /*#__PURE__*/_react.default.createElement(_sticker.default, {
              className: "sticker-user-icon ".concat(item.portraitURL ? '' : item.userId % 10),
              size: "lg"
            }, item.portraitURL ? /*#__PURE__*/_react.default.createElement("div", {
              className: "sticker-overlay"
            }, /*#__PURE__*/_react.default.createElement("img", {
              className: "sticker-img",
              src: item.portraitURL
            })) : /*#__PURE__*/_react.default.createElement(_icon.default, {
              symbol: "user"
            }))), /*#__PURE__*/_react.default.createElement("div", {
              className: "autofit-col"
            }, /*#__PURE__*/_react.default.createElement("strong", null, item.fullName), /*#__PURE__*/_react.default.createElement("span", null, item.emailAddress))))
          );
        }))
      );
    };

    var Sharing = function Sharing(_ref2) {
      var autocompleteUserURL = _ref2.autocompleteUserURL,
          classNameId = _ref2.classNameId,
          classPK = _ref2.classPK,
          portletNamespace = _ref2.portletNamespace,
          shareActionURL = _ref2.shareActionURL,
          sharingEntryPermissionDisplayActionId = _ref2.sharingEntryPermissionDisplayActionId,
          sharingEntryPermissionDisplays = _ref2.sharingEntryPermissionDisplays,
          sharingVerifyEmailAddressURL = _ref2.sharingVerifyEmailAddressURL;

      var _useState = (0, _react.useState)([]),
          _useState2 = _slicedToArray(_useState, 2),
          emailAddressErrorMessages = _useState2[0],
          setEmailAddressErrorMessages = _useState2[1];

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

      var _useState5 = (0, _react.useState)(''),
          _useState6 = _slicedToArray(_useState5, 2),
          multiSelectValue = _useState6[0],
          setMultiSelectValue = _useState6[1];

      var _useState7 = (0, _react.useState)(true),
          _useState8 = _slicedToArray(_useState7, 2),
          allowSharingChecked = _useState8[0],
          setAllowSharingChecked = _useState8[1];

      var _useState9 = (0, _react.useState)('VIEW'),
          _useState10 = _slicedToArray(_useState9, 2),
          sharingPermission = _useState10[0],
          setSharingPermission = _useState10[1];

      var emailValidationInProgress = (0, _react.useRef)(false);

      var closeDialog = function closeDialog() {
        Liferay.Util.getOpener().Liferay.fire('closeModal', {
          id: 'sharingDialog'
        });
      };

      var showNotification = function showNotification(message, error) {
        var parentOpenToast = Liferay.Util.getOpener().Liferay.Util.openToast;
        var openToastParams = {
          message: message
        };

        if (error) {
          openToastParams.title = Liferay.Language.get('error');
          openToastParams.type = 'danger';
        }

        closeDialog();
        parentOpenToast(openToastParams);
      };

      var isEmailAddressValid = function isEmailAddressValid(email) {
        var emailRegex = /.+@.+\..+/i;
        return emailRegex.test(email);
      };

      var handleItemsChange = (0, _react.useCallback)(function (items) {
        emailValidationInProgress.current = true;
        Promise.all(items.map(function (item) {
          if (item.id || selectedItems.some(function (_ref4) {
            var value = _ref4.value;
            return item.value === value;
          })) {
            return Promise.resolve({
              item: item
            });
          }

          if (!isEmailAddressValid(item.value)) {
            return Promise.resolve({
              error: Liferay.Util.sub(Liferay.Language.get('x-is-not-a-valid-email-address'), item.value),
              item: item
            });
          }

          return (0, _frontendJsWeb.fetch)(sharingVerifyEmailAddressURL, {
            body: (0, _frontendJsWeb.objectToFormData)(_defineProperty({}, "".concat(portletNamespace, "emailAddress"), item.value)),
            method: 'POST'
          }).then(function (response) {
            return response.json();
          }).then(function (_ref5) {
            var userExists = _ref5.userExists;
            return {
              error: !userExists ? Liferay.Util.sub(Liferay.Language.get('user-x-does-not-exist'), item.value) : undefined,
              item: item
            };
          });
        })).then(function (results) {
          emailValidationInProgress.current = false;
          var erroredResults = results.filter(function (_ref6) {
            var error = _ref6.error;
            return !!error;
          });
          setEmailAddressErrorMessages(erroredResults.map(function (_ref7) {
            var error = _ref7.error;
            return error;
          }));

          if (erroredResults.length === 0) {
            setMultiSelectValue('');
          }

          if (erroredResults.length === 1) {
            setMultiSelectValue(erroredResults[0].item.value);
          }

          setSelectedItems(filterDuplicateItems(results.filter(function (_ref8) {
            var error = _ref8.error;
            return !error;
          }).map(function (_ref9) {
            var item = _ref9.item;
            return item;
          })));
        });
      }, [portletNamespace, selectedItems, sharingVerifyEmailAddressURL]);
      var handleChange = (0, _react.useCallback)(function (value) {
        if (!emailValidationInProgress.current) {
          setMultiSelectValue(value);
        }
      }, []);
      var multiSelectFilter = (0, _react.useCallback)(function () {
        return true;
      }, []);

      var _useResource = (0, _dataProvider.useResource)({
        fetchOptions: {
          credentials: 'include',
          headers: new Headers({
            'x-csrf-token': Liferay.authToken
          }),
          method: 'GET'
        },
        fetchRetry: {
          attempts: 0
        },
        link: autocompleteUserURL,
        variables: _defineProperty({}, "".concat(portletNamespace, "query"), multiSelectValue)
      }),
          resource = _useResource.resource;

      var users = resource;
      return (/*#__PURE__*/_react.default.createElement(_form.default, {
          className: "sharing-modal-content",
          onSubmit: function handleSubmit(event) {
            var _data;

            event.preventDefault();
            var data = (_data = {}, _defineProperty(_data, "".concat(portletNamespace, "classNameId"), classNameId), _defineProperty(_data, "".concat(portletNamespace, "classPK"), classPK), _defineProperty(_data, "".concat(portletNamespace, "shareable"), allowSharingChecked), _defineProperty(_data, "".concat(portletNamespace, "sharingEntryPermissionDisplayActionId"), sharingPermission), _defineProperty(_data, "".concat(portletNamespace, "userEmailAddress"), selectedItems.map(function (_ref3) {
              var value = _ref3.value;
              return value;
            }).join(',')), _data);
            var formData = (0, _frontendJsWeb.objectToFormData)(data);
            (0, _frontendJsWeb.fetch)(shareActionURL, {
              body: formData,
              method: 'POST'
            }).then(function (response) {
              var jsonResponse = response.json();
              return response.ok ? jsonResponse : jsonResponse.then(function (json) {
                var error = new Error(json.errorMessage || response.statusText);
                throw Object.assign(error, {
                  response: response
                });
              });
            }).then(function (response) {
              parent.Liferay.fire('sharing:changed', {
                classNameId: classNameId,
                classPK: classPK
              });
              showNotification(response.successMessage);
            }).catch(function (error) {
              showNotification(error.message, true);
            });
          }
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "inline-scroller modal-body"
        }, /*#__PURE__*/_react.default.createElement(_form.default.Group, {
          className: emailAddressErrorMessages.length ? 'has-error' : ''
        }, /*#__PURE__*/_react.default.createElement(_form.ClayInput.Group, null, /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, null, /*#__PURE__*/_react.default.createElement("label", {
          htmlFor: "userEmailAddress"
        }, Liferay.Language.get('invite-to-collaborate')), /*#__PURE__*/_react.default.createElement(_multiSelect.default, {
          filter: multiSelectFilter,
          inputName: "".concat(portletNamespace, "userEmailAddress"),
          inputValue: multiSelectValue,
          items: selectedItems,
          menuRenderer: SharingAutocomplete,
          onChange: handleChange,
          onItemsChange: handleItemsChange,
          placeholder: Liferay.Language.get('enter-name-or-email-address'),
          sourceItems: multiSelectValue && users ? users.map(function (user) {
            return {
              emailAddress: user.emailAddress,
              fullName: user.fullName,
              id: user.userId,
              label: user.fullName,
              portraitURL: user.portraitURL,
              value: user.emailAddress
            };
          }) : []
        }), /*#__PURE__*/_react.default.createElement(_form.default.FeedbackGroup, null, /*#__PURE__*/_react.default.createElement(_form.default.Text, null, Liferay.Language.get('you-can-use-a-comma-to-enter-multiple-collaborators'))), emailAddressErrorMessages.length > 0 && /*#__PURE__*/_react.default.createElement(_form.default.FeedbackGroup, null, emailAddressErrorMessages.map(function (emailAddressErrorMessage) {
          return (/*#__PURE__*/_react.default.createElement(_form.default.FeedbackItem, {
              key: emailAddressErrorMessage
            }, emailAddressErrorMessage)
          );
        }))))), /*#__PURE__*/_react.default.createElement(_form.default.Group, null, /*#__PURE__*/_react.default.createElement(_form.ClayCheckbox, {
          checked: allowSharingChecked,
          label: Liferay.Language.get('allow-the-item-to-be-shared-with-other-users'),
          name: "".concat(portletNamespace, "shareable"),
          onChange: function onChange() {
            return setAllowSharingChecked(function (allow) {
              return !allow;
            });
          }
        })), /*#__PURE__*/_react.default.createElement("h4", {
          className: "sheet-tertiary-title"
        }, Liferay.Language.get('sharing-permissions')), /*#__PURE__*/_react.default.createElement(_form.default.Group, null, /*#__PURE__*/_react.default.createElement(_form.ClayRadioGroup, {
          name: "".concat(portletNamespace, "sharingEntryPermissionDisplayActionId"),
          onSelectedValueChange: function onSelectedValueChange(permission) {
            return setSharingPermission(permission);
          },
          selectedValue: sharingPermission
        }, sharingEntryPermissionDisplays.map(function (display) {
          return (/*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
              checked: sharingEntryPermissionDisplayActionId === display.sharingEntryPermissionDisplayActionId,
              disabled: !display.enabled,
              key: display.sharingEntryPermissionDisplayActionId,
              label: display.title,
              value: display.sharingEntryPermissionDisplayActionId
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "form-text"
            }, display.description))
          );
        })))), /*#__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: closeDialog
          }, Liferay.Language.get('cancel')), /*#__PURE__*/_react.default.createElement(_button.default, {
            displayType: "primary",
            type: "submit"
          }, Liferay.Language.get('share')))
        }))
      );
    };

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