Liferay.Loader.define("sharing-web@2.0.45/manage_collaborators/js/ManageCollaborators.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/alert', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/layout', '@frontend-taglib-clay$clayui/loading-indicator', '@frontend-taglib-clay$clayui/sticker', 'frontend-js-react-web$classnames', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-metal-web$metal-dom', 'frontend-js-react-web$prop-types', '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 _alert = _interopRequireDefault(require("@frontend-taglib-clay$clayui/alert"));

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

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

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

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

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

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

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

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

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

    var _metalDom = _interopRequireDefault(require("frontend-js-metal-web$metal-dom"));

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

    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 _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 ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    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;
    }

    /**
     * Handles actions to delete or change permissions of the
     * collaborators for a file entry.
     */
    var ManageCollaborators = function ManageCollaborators(_ref) {
      var actionUrl = _ref.actionUrl,
          classNameId = _ref.classNameId,
          classPK = _ref.classPK,
          collaborators = _ref.collaborators,
          portletNamespace = _ref.portletNamespace;

      var _useState = (0, _react.useState)(collaborators),
          _useState2 = _slicedToArray(_useState, 2),
          currentCollaborators = _useState2[0],
          setCurrentCollaborators = _useState2[1];

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

      var _useState5 = (0, _react.useState)(false),
          _useState6 = _slicedToArray(_useState5, 2),
          expirationDateError = _useState6[0],
          setExpirationDateError = _useState6[1];

      var _useState7 = (0, _react.useState)(1234),
          _useState8 = _slicedToArray(_useState7, 2),
          expandedCollaboratorId = _useState8[0],
          setExpandedCollaboratorId = _useState8[1];

      var _useState9 = (0, _react.useState)(false),
          _useState10 = _slicedToArray(_useState9, 2),
          loadingResponse = _useState10[0],
          setLoadingResponse = _useState10[1];

      var _useState11 = (0, _react.useState)({}),
          _useState12 = _slicedToArray(_useState11, 2),
          sharingEntryIdsAndExpirationDate = _useState12[0],
          setSharingEntryIdsAndExpirationDate = _useState12[1];

      var _useState13 = (0, _react.useState)({}),
          _useState14 = _slicedToArray(_useState13, 2),
          sharingEntryIdsAndPermissions = _useState14[0],
          setSharingEntryIdsAndPermissions = _useState14[1];

      var _useState15 = (0, _react.useState)({}),
          _useState16 = _slicedToArray(_useState15, 2),
          sharingEntryIdsAndShareables = _useState16[0],
          setSharingEntryIdsAndShareables = _useState16[1];

      var _useState17 = (0, _react.useState)(),
          _useState18 = _slicedToArray(_useState17, 2),
          tomorrowDate = _useState18[0],
          setTomorrowDate = _useState18[1];

      var delay = (0, _frontendJsReactWeb.useTimeout)();

      var checkExpirationDate = function checkExpirationDate(expirationDate) {
        var date = new Date(expirationDate);
        return date >= new Date(tomorrowDate);
      };

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

      var objectToPairArray = function objectToPairArray(object) {
        var entries = Object.entries(object);
        var result = [];
        entries.forEach(function (_ref2) {
          var _ref3 = _slicedToArray(_ref2, 2),
              key = _ref3[0],
              value = _ref3[1];

          result.push("".concat(key, ",").concat(value));
        });
        return result;
      };

      var findExpirationDateError = function findExpirationDateError() {
        var collaborator = currentCollaborators.find(function (collaborator) {
          return collaborator.sharingEntryExpirationDateError === true;
        });
        setExpirationDateError(!!collaborator);
      };

      var getCollaborator = function getCollaborator(collaboratorId) {
        var collaboratorIdNumber = Number(collaboratorId);
        var collaborator = currentCollaborators.find(function (collaborator) {
          return collaborator.userId === collaboratorIdNumber;
        });
        return collaborator;
      };

      var getTooltipDate = function getTooltipDate(expirationDate) {
        return Liferay.Util.sub(Liferay.Language.get('until-x'), new Date(expirationDate).toLocaleDateString(Liferay.ThemeDisplay.getBCP47LanguageId()));
      };

      var handleCollaboratorClick = function handleCollaboratorClick(event) {
        var eventTarget = event.target;


        if ('select,option,button'.indexOf(eventTarget.nodeName.toLowerCase()) === -1) {
          var collaboratorContainer = _metalDom.default.closest(eventTarget, '.list-group-item');

          setExpandedCollaboratorId(Number(collaboratorContainer.dataset.collaboratorid));
        }
      };

      var handleDeleteCollaboratorButtonClick = function handleDeleteCollaboratorButtonClick(event) {
        var button = event.currentTarget;
        var collaboratorId = Number(button.dataset.collaboratorId);
        var sharingEntryId = button.dataset.sharingentryId;
        event.stopPropagation();
        setCurrentCollaborators(currentCollaborators.filter(function (collaborator) {
          return collaborator.userId != collaboratorId;
        }));
        deleteSharingEntryIds.push(sharingEntryId);
        setDeleteSharingEntryIds(deleteSharingEntryIds);
      };

      var setCollaborator = function setCollaborator(updatedCollaborator) {
        setCurrentCollaborators(currentCollaborators.map(function (collaborator) {
          if (collaborator.userId === updatedCollaborator.userId) {
            return _objectSpread(_objectSpread({}, collaborator), updatedCollaborator);
          }

          return collaborator;
        }));
      };

      var handleExpirationDateCheckboxChange = function handleExpirationDateCheckboxChange(event) {
        var checkbox = event.target;
        var collaboratorId = checkbox.dataset.collaboratorId;
        var enabled = checkbox.checked;
        var collaborator = getCollaborator(collaboratorId);
        collaborator.enabledExpirationDate = enabled;
        var sharingEntryExpirationDate = enabled ? tomorrowDate : '';

        if (!enabled) {
          collaborator.sharingEntryExpirationDateError = false;
          findExpirationDateError();
        }

        collaborator.sharingEntryExpirationDate = sharingEntryExpirationDate;
        collaborator.sharingEntryExpirationDateTooltip = getTooltipDate(sharingEntryExpirationDate);
        setCollaborator(collaborator);
        setSharingEntryIdsAndExpirationDate(_objectSpread(_objectSpread({}, sharingEntryIdsAndExpirationDate), {}, _defineProperty({}, collaborator.sharingEntryId, sharingEntryExpirationDate)));
      };

      var handleExpirationDateInputBlur = function handleExpirationDateInputBlur(event) {
        var input = event.target;
        var collaboratorId = input.dataset.collaboratorId;
        var sharingEntryExpirationDate = input.value;
        var sharingEntryId = input.dataset.sharingentryId;
        var collaborator = getCollaborator(collaboratorId);
        var dateError = !checkExpirationDate(sharingEntryExpirationDate);
        collaborator.sharingEntryExpirationDateError = dateError;

        if (!dateError) {
          collaborator.sharingEntryExpirationDate = sharingEntryExpirationDate;
          collaborator.sharingEntryExpirationDateTooltip = getTooltipDate(sharingEntryExpirationDate);
          setCollaborator(collaborator);
          setSharingEntryIdsAndExpirationDate(_objectSpread(_objectSpread({}, sharingEntryIdsAndExpirationDate), {}, _defineProperty({}, sharingEntryId, sharingEntryExpirationDate)));
        }

        delay(function () {
          return findExpirationDateError();
        }, 0);
      };

      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 handleShareableCheckboxChange = function handleShareableCheckboxChange(event) {
        var checkbox = event.target;
        var collaboratorId = checkbox.dataset.collaboratorId;
        var shareable = checkbox.checked;
        var sharingEntryId = checkbox.dataset.sharingentryId;
        var collaborator = getCollaborator(collaboratorId);
        collaborator.sharingEntryShareable = shareable;
        setCollaborator(collaborator);
        setSharingEntryIdsAndShareables(_objectSpread(_objectSpread({}, sharingEntryIdsAndShareables), {}, _defineProperty({}, sharingEntryId, shareable)));
      };

      (0, _react.useEffect)(function () {
        var tomorrow = new Date();
        tomorrow = tomorrow.setDate(tomorrow.getDate() + 1);
        setTomorrowDate(new Date(tomorrow).toISOString().split('T')[0]);
      }, []);

      var Collaborator = function Collaborator(_ref4) {
        var fullName = _ref4.fullName,
            portraitURL = _ref4.portraitURL,
            sharingEntryExpirationDate = _ref4.sharingEntryExpirationDate,
            sharingEntryExpirationDateError = _ref4.sharingEntryExpirationDateError,
            sharingEntryExpirationDateTooltip = _ref4.sharingEntryExpirationDateTooltip,
            sharingEntryId = _ref4.sharingEntryId,
            sharingEntryPermissionActionId = _ref4.sharingEntryPermissionActionId,
            sharingEntryPermissionDisplaySelectOptions = _ref4.sharingEntryPermissionDisplaySelectOptions,
            sharingEntryShareable = _ref4.sharingEntryShareable,
            userId = _ref4.userId;
        return (/*#__PURE__*/_react.default.createElement("li", {
            className: (0, _classnames.default)('list-group-item', 'list-group-item-action', 'list-group-item-flex', {
              active: userId === expandedCollaboratorId
            }),
            "data-collaboratorid": userId,
            id: "collaborator".concat(userId),
            onClick: handleCollaboratorClick,
            role: "button"
          }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, /*#__PURE__*/_react.default.createElement(_sticker.default, {
            className: !portraitURL && "user-icon-color-".concat(userId % 10),
            shape: "circle",
            size: "lg"
          }, portraitURL ? /*#__PURE__*/_react.default.createElement("img", {
            className: "sticker-img",
            src: portraitURL
          }) : /*#__PURE__*/_react.default.createElement(_icon.default, {
            symbol: "user"
          }))), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, {
            expand: true
          }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentRow, {
            verticalAlign: "center"
          }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, {
            expand: true
          }, /*#__PURE__*/_react.default.createElement("strong", null, /*#__PURE__*/_react.default.createElement("span", null, fullName))), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, sharingEntryExpirationDate ? /*#__PURE__*/_react.default.createElement(_icon.default, {
            "data-title": sharingEntryExpirationDateTooltip,
            symbol: "time"
          }) : /*#__PURE__*/_react.default.createElement("span", {
            className: "lexicon-icon"
          })), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, sharingEntryShareable ? /*#__PURE__*/_react.default.createElement(_icon.default, {
            "data-title": Liferay.Language.get('user-can-share'),
            symbol: "users"
          }) : /*#__PURE__*/_react.default.createElement("span", {
            className: "lexicon-icon"
          })), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, /*#__PURE__*/_react.default.createElement(_form.ClaySelectWithOption, {
            name: sharingEntryId,
            onChange: function onChange(event) {
              setSharingEntryIdsAndPermissions(_objectSpread(_objectSpread({}, sharingEntryIdsAndPermissions), {}, _defineProperty({}, event.target.name, event.target.value)));
            },
            options: sharingEntryPermissionDisplaySelectOptions,
            value: sharingEntryIdsAndPermissions[sharingEntryId] || sharingEntryPermissionActionId
          })), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, /*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
            borderless: true,
            "data-collaborator-id": userId,
            "data-sharingentry-id": sharingEntryId,
            disabled: loadingResponse,
            displayType: "secondary",
            onClick: handleDeleteCollaboratorButtonClick,
            symbol: "times-circle"
          }))), /*#__PURE__*/_react.default.createElement("div", {
            className: (0, _classnames.default)({
              hide: userId !== expandedCollaboratorId
            })
          }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentRow, {
            verticalAlign: "center"
          }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, /*#__PURE__*/_react.default.createElement("div", {
            className: "form-group"
          }, /*#__PURE__*/_react.default.createElement("div", {
            className: "custom-checkbox custom-control"
          }, /*#__PURE__*/_react.default.createElement(_form.ClayCheckbox, {
            checked: sharingEntryShareable,
            className: "custom-control-input",
            "data-collaborator-id": userId,
            "data-sharingentry-id": sharingEntryId,
            label: Liferay.Language.get('allow-the-item-to-be-shared-with-other-users'),
            onChange: handleShareableCheckboxChange
          }))))), /*#__PURE__*/_react.default.createElement(_layout.default.ContentRow, {
            verticalAlign: "center"
          }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, /*#__PURE__*/_react.default.createElement("div", {
            className: "form-group"
          }, /*#__PURE__*/_react.default.createElement("div", {
            className: "custom-checkbox custom-control"
          }, /*#__PURE__*/_react.default.createElement(_form.ClayCheckbox, {
            className: "custom-control-input",
            "data-collaborator-id": userId,
            defaultChecked: sharingEntryExpirationDate,
            label: Liferay.Language.get('set-expiration-date'),
            onChange: handleExpirationDateCheckboxChange
          })))), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, {
            className: (0, _classnames.default)('no-padding', {
              'has-error': sharingEntryExpirationDateError
            })
          }, /*#__PURE__*/_react.default.createElement(_form.ClayInput, {
            className: "form-control",
            "data-collaborator-id": userId,
            "data-sharingentry-id": sharingEntryId,
            defaultValue: sharingEntryExpirationDate,
            disabled: !sharingEntryExpirationDate,
            min: tomorrowDate,
            onBlur: handleExpirationDateInputBlur,
            type: "date"
          }))))))
        );
      };

      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "inline-scroller modal-body"
        }, currentCollaborators.length ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, expirationDateError && /*#__PURE__*/_react.default.createElement(_alert.default, {
          displayType: "danger",
          onClose: function onClose() {
            setExpirationDateError(false);
          },
          title: "".concat(Liferay.Language.get('error'), ":"),
          variant: "stripe"
        }, Liferay.Language.get('please-enter-an-expiration-date-that-comes-after-today')), /*#__PURE__*/_react.default.createElement("ul", {
          className: "list-group"
        }, currentCollaborators.map(function (collaborator) {
          return (/*#__PURE__*/_react.default.createElement(Collaborator, _extends({}, collaborator, {
              key: collaborator.userId
            }))
          );
        }))) : /*#__PURE__*/_react.default.createElement(_layout.default.ContentRow, {
          className: "empty-collaborators",
          verticalAlign: "center"
        }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, {
          expand: true
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "message-content"
        }, /*#__PURE__*/_react.default.createElement("h3", null, Liferay.Language.get('no-collaborators')), /*#__PURE__*/_react.default.createElement("p", null, Liferay.Language.get('to-add-collaborators-share-the-file-again')))))), /*#__PURE__*/_react.default.createElement("div", {
          className: "modal-footer"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "modal-item-last"
        }, /*#__PURE__*/_react.default.createElement(_button.default.Group, {
          spaced: true
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: loadingResponse,
          displayType: "secondary",
          onClick: closeDialog
        }, Liferay.Language.get('cancel')), /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: loadingResponse || expirationDateError,
          displayType: "primary",
          onClick: function handleSaveButtonClick() {
            if (findExpirationDateError()) {
              return;
            }

            setLoadingResponse(true);
            var data = Liferay.Util.ns(portletNamespace, {
              deleteSharingEntryIds: deleteSharingEntryIds,
              sharingEntryIdActionIdPairs: objectToPairArray(sharingEntryIdsAndPermissions),
              sharingEntryIdExpirationDatePairs: objectToPairArray(sharingEntryIdsAndExpirationDate),
              sharingEntryIdShareablePairs: objectToPairArray(sharingEntryIdsAndShareables)
            });
            (0, _frontendJsWeb.fetch)(actionUrl, {
              body: (0, _frontendJsWeb.objectToFormData)(data),
              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 (json) {
              parent.Liferay.fire('sharing:changed', {
                classNameId: classNameId,
                classPK: classPK
              });
              setLoadingResponse(false);
              showNotification(json.successMessage);
            }).catch(function (error) {
              showNotification(error.message, true);
              setLoadingResponse(false);
            });
          }
        }, loadingResponse && /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null), Liferay.Language.get('save'))))))
      );
    };

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