Liferay.Loader.define("dynamic-data-mapping-form-field-type@5.0.83/DocumentLibrary/DocumentLibrary.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/card', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/progress-bar', 'dynamic-data-mapping-form-field-type$axios', 'dynamic-data-mapping-form-renderer', 'dynamic-data-mapping-form-renderer/js/util/fetch.es', 'frontend-js-web', 'frontend-js-react-web$react', '../FieldBase/ReactFieldBase.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 = _interopRequireWildcard(require("@frontend-taglib-clay$clayui/button"));

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

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

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

    var _progressBar = _interopRequireDefault(require("@frontend-taglib-clay$clayui/progress-bar"));

    var _axios = _interopRequireDefault(require("dynamic-data-mapping-form-field-type$axios"));

    var _dynamicDataMappingFormRenderer = require("dynamic-data-mapping-form-renderer");

    var _fetch = require("dynamic-data-mapping-form-renderer/js/util/fetch.es");

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

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

    var _ReactFieldBase = require("../FieldBase/ReactFieldBase.es");

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

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

    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 CardItem = function CardItem(_ref) {
      var fileEntryTitle = _ref.fileEntryTitle,
          fileEntryURL = _ref.fileEntryURL;
      return (/*#__PURE__*/_react.default.createElement(_card.default, {
          horizontal: true
        }, /*#__PURE__*/_react.default.createElement(_card.default.Body, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "card-col-content card-col-gutters"
        }, /*#__PURE__*/_react.default.createElement("h4", {
          className: "text-truncate",
          title: fileEntryTitle
        }, fileEntryTitle)), /*#__PURE__*/_react.default.createElement("div", {
          className: "card-col-field"
        }, /*#__PURE__*/_react.default.createElement("a", {
          download: fileEntryTitle,
          href: fileEntryURL
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: "download"
        })))))
      );
    };

    function transformFileEntryProperties(_ref2) {
      var fileEntryTitle = _ref2.fileEntryTitle,
          fileEntryURL = _ref2.fileEntryURL,
          value = _ref2.value;

      if (value && typeof value === 'string') {
        try {
          var fileEntry = JSON.parse(value);
          fileEntryTitle = fileEntry.title;

          if (fileEntry.url) {
            fileEntryURL = fileEntry.url;
          }
        } catch (e) {
          console.warn('Unable to parse JSON', value);
        }
      }

      return value ? [fileEntryTitle, fileEntryURL] : [];
    }

    var DocumentLibrary = function DocumentLibrary(_ref3) {
      var _ref3$fileEntryTitle = _ref3.fileEntryTitle,
          fileEntryTitle = _ref3$fileEntryTitle === void 0 ? '' : _ref3$fileEntryTitle,
          _ref3$fileEntryURL = _ref3.fileEntryURL,
          fileEntryURL = _ref3$fileEntryURL === void 0 ? '' : _ref3$fileEntryURL,
          id = _ref3.id,
          name = _ref3.name,
          onBlur = _ref3.onBlur,
          onClearButtonClicked = _ref3.onClearButtonClicked,
          onFocus = _ref3.onFocus,
          onSelectButtonClicked = _ref3.onSelectButtonClicked,
          placeholder = _ref3.placeholder,
          readOnly = _ref3.readOnly,
          value = _ref3.value;

      var _useMemo = (0, _react.useMemo)(function () {
        return transformFileEntryProperties({
          fileEntryTitle: fileEntryTitle,
          fileEntryURL: fileEntryURL,
          value: value
        });
      }, [fileEntryTitle, fileEntryURL, value]),
          _useMemo2 = _slicedToArray(_useMemo, 2),
          transformedFileEntryTitle = _useMemo2[0],
          transformedFileEntryURL = _useMemo2[1];

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "liferay-ddm-form-field-document-library"
        }, transformedFileEntryURL && readOnly ? /*#__PURE__*/_react.default.createElement(CardItem, {
          fileEntryTitle: transformedFileEntryTitle,
          fileEntryURL: transformedFileEntryURL
        }) : /*#__PURE__*/_react.default.createElement(_form.ClayInput.Group, null, /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          prepend: true
        }, /*#__PURE__*/_react.default.createElement(_form.ClayInput, {
          "aria-label": Liferay.Language.get('file'),
          className: "field",
          disabled: true,
          id: "".concat(name, "inputFile"),
          value: transformedFileEntryTitle || ''
        })), /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          append: true,
          shrink: true
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          className: "select-button",
          disabled: readOnly,
          displayType: "secondary",
          onBlur: onBlur,
          onClick: onSelectButtonClicked,
          onFocus: onFocus
        }, /*#__PURE__*/_react.default.createElement("span", {
          className: "lfr-btn-label"
        }, Liferay.Language.get('select')))), transformedFileEntryTitle && /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          append: true,
          shrink: true
        }, /*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
          "aria-label": Liferay.Language.get('unselect-file'),
          className: "clear-button",
          displayType: "secondary",
          onClick: onClearButtonClicked,
          symbol: "times"
        }))), /*#__PURE__*/_react.default.createElement("input", {
          id: id,
          name: name,
          placeholder: placeholder,
          type: "hidden",
          value: value || ''
        }))
      );
    };

    var GuestUploadFile = function GuestUploadFile(_ref4) {
      var _ref4$fileEntryTitle = _ref4.fileEntryTitle,
          fileEntryTitle = _ref4$fileEntryTitle === void 0 ? '' : _ref4$fileEntryTitle,
          _ref4$fileEntryURL = _ref4.fileEntryURL,
          fileEntryURL = _ref4$fileEntryURL === void 0 ? '' : _ref4$fileEntryURL,
          id = _ref4.id,
          name = _ref4.name,
          onBlur = _ref4.onBlur,
          onClearButtonClicked = _ref4.onClearButtonClicked,
          onFocus = _ref4.onFocus,
          onUploadSelectButtonClicked = _ref4.onUploadSelectButtonClicked,
          placeholder = _ref4.placeholder,
          progress = _ref4.progress,
          readOnly = _ref4.readOnly,
          value = _ref4.value;

      var _useMemo3 = (0, _react.useMemo)(function () {
        return transformFileEntryProperties({
          fileEntryTitle: fileEntryTitle,
          fileEntryURL: fileEntryURL,
          value: value
        });
      }, [fileEntryTitle, fileEntryURL, value]),
          _useMemo4 = _slicedToArray(_useMemo3, 1),
          transformedFileEntryTitle = _useMemo4[0];

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "liferay-ddm-form-field-document-library"
        }, /*#__PURE__*/_react.default.createElement(_form.ClayInput.Group, null, /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          prepend: true
        }, /*#__PURE__*/_react.default.createElement(_form.ClayInput, {
          disabled: true,
          type: "text",
          value: transformedFileEntryTitle || ''
        })), /*#__PURE__*/_react.default.createElement(_form.ClayInput.GroupItem, {
          append: true,
          shrink: true
        }, /*#__PURE__*/_react.default.createElement("label", {
          className: 'btn btn-secondary select-button' + (transformedFileEntryTitle ? ' clear-button-upload-on' : '') + (readOnly ? ' disabled' : ''),
          htmlFor: "".concat(name, "inputFileGuestUpload")
        }, Liferay.Language.get('select')), /*#__PURE__*/_react.default.createElement("input", {
          className: "input-file",
          disabled: readOnly,
          id: "".concat(name, "inputFileGuestUpload"),
          onBlur: onBlur,
          onChange: onUploadSelectButtonClicked,
          onFocus: onFocus,
          type: "file"
        })), transformedFileEntryTitle && /*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
          "aria-label": Liferay.Language.get('unselect-file'),
          className: "clear-button-upload",
          displayType: "secondary",
          onClick: onClearButtonClicked,
          symbol: "times"
        })), /*#__PURE__*/_react.default.createElement("input", {
          id: id,
          name: name,
          placeholder: placeholder,
          type: "hidden",
          value: value || ''
        }), progress !== 0 && /*#__PURE__*/_react.default.createElement(_progressBar.default, {
          value: progress
        }))
      );
    };

    var Main = function Main(_ref5) {
      var allowGuestUsers = _ref5.allowGuestUsers,
          initialDisplayErrors = _ref5.displayErrors,
          initialErrorMessage = _ref5.errorMessage,
          fieldName = _ref5.fieldName,
          fileEntryTitle = _ref5.fileEntryTitle,
          fileEntryURL = _ref5.fileEntryURL,
          guestUploadURL = _ref5.guestUploadURL,
          id = _ref5.id,
          itemSelectorURL = _ref5.itemSelectorURL,
          maximumRepetitions = _ref5.maximumRepetitions,
          maximumSubmissionLimitReached = _ref5.maximumSubmissionLimitReached,
          name = _ref5.name,
          onBlur = _ref5.onBlur,
          onChange = _ref5.onChange,
          onFocus = _ref5.onFocus,
          placeholder = _ref5.placeholder,
          readOnly = _ref5.readOnly,
          initialValid = _ref5.valid,
          _ref5$value = _ref5.value,
          value = _ref5$value === void 0 ? '{}' : _ref5$value,
          otherProps = _objectWithoutProperties(_ref5, ["allowGuestUsers", "displayErrors", "errorMessage", "fieldName", "fileEntryTitle", "fileEntryURL", "guestUploadURL", "id", "itemSelectorURL", "maximumRepetitions", "maximumSubmissionLimitReached", "name", "onBlur", "onChange", "onFocus", "placeholder", "readOnly", "valid", "value"]);

      var _usePage = (0, _dynamicDataMappingFormRenderer.usePage)(),
          pages = _usePage.pages,
          portletNamespace = _usePage.portletNamespace;

      var _useState = (0, _react.useState)(value),
          _useState2 = _slicedToArray(_useState, 2),
          currentValue = _useState2[0],
          setCurrentValue = _useState2[1];

      var _useState3 = (0, _react.useState)(initialErrorMessage),
          _useState4 = _slicedToArray(_useState3, 2),
          errorMessage = _useState4[0],
          setErrorMessage = _useState4[1];

      var _useState5 = (0, _react.useState)(initialDisplayErrors),
          _useState6 = _slicedToArray(_useState5, 2),
          displayErrors = _useState6[0],
          setDisplayErrors = _useState6[1];

      var _useState7 = (0, _react.useState)(initialValid),
          _useState8 = _slicedToArray(_useState7, 2),
          valid = _useState8[0],
          setValid = _useState8[1];

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

      var getErrorMessages = function getErrorMessages(errorMessage, isSignedIn) {
        var errorMessages = [errorMessage];

        if (!isSignedIn && !allowGuestUsers) {
          errorMessages.push(Liferay.Language.get('you-need-to-be-signed-in-to-edit-this-field'));
        } else if (maximumSubmissionLimitReached) {
          errorMessages.push(Liferay.Language.get('the-maximum-number-of-submissions-allowed-for-this-form-has-been-reached'));
        }

        return errorMessages.join(' ');
      };

      var isSignedIn = Liferay.ThemeDisplay.isSignedIn();
      (0, _react.useEffect)(function () {
        setDisplayErrors(initialDisplayErrors);
        setErrorMessage(getErrorMessages(initialErrorMessage, isSignedIn));
        setValid(initialValid); // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [initialDisplayErrors, initialErrorMessage, initialValid]);

      var handleVisibleChange = function handleVisibleChange(event) {
        if (event.selectedItem) {
          onFocus({}, event);
        } else {
          onBlur({}, event);
        }
      };

      var handleFieldChanged = function handleFieldChanged(event) {
        var selectedItem = event.selectedItem;

        if (selectedItem) {
          var _value = selectedItem.value;
          setCurrentValue(_value);
          onChange(event, _value);
        }
      };

      var handleSelectButtonClicked = function handleSelectButtonClicked(_ref6) {
        var portletNamespace = _ref6.portletNamespace;
        var itemSelectorDialog = new _frontendJsWeb.ItemSelectorDialog({
          eventName: "".concat(portletNamespace, "selectDocumentLibrary"),
          singleSelect: true,
          url: itemSelectorURL
        });
        itemSelectorDialog.on('selectedItemChange', handleFieldChanged);
        itemSelectorDialog.on('visibleChange', handleVisibleChange);
        itemSelectorDialog.open();
      };

      var configureErrorMessage = function configureErrorMessage(message) {
        setErrorMessage(message);
        var enable = message ? true : false;
        setDisplayErrors(enable);
        setValid(!enable);
      };

      var disableSubmitButton = function disableSubmitButton() {
        var disable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
        document.getElementById('ddm-form-submit').disabled = disable;
      };

      var handleGuestUploadFileChanged = function handleGuestUploadFileChanged(errorMessage, event, value) {
        configureErrorMessage(errorMessage);
        setCurrentValue(value);
        onChange(event, value ? value : '{}');
      };

      var isExceededUploadRequestSizeLimit = function isExceededUploadRequestSizeLimit(fileSize) {
        var uploadRequestSizeLimit = Liferay.PropsValues.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE;

        if (fileSize <= uploadRequestSizeLimit) {
          return false;
        }

        var errorMessage = Liferay.Util.sub(Liferay.Language.get('please-enter-a-file-with-a-valid-file-size-no-larger-than-x'), [Liferay.Util.formatStorage(uploadRequestSizeLimit)]);
        handleGuestUploadFileChanged(errorMessage, {}, null);
        return true;
      };

      var handleUploadSelectButtonClicked = function handleUploadSelectButtonClicked(event) {
        var file = event.target.files[0];

        if (isExceededUploadRequestSizeLimit(file.size)) {
          return;
        }

        var data = _defineProperty({}, "".concat(portletNamespace, "file"), file);

        _axios.default.post(guestUploadURL, (0, _fetch.convertToFormData)(data), {
          onUploadProgress: function onUploadProgress(event) {
            var progress = Math.round(event.loaded * 100 / event.total);
            setCurrentValue(null);
            setProgress(progress);
            disableSubmitButton();
          }
        }).then(function (response) {
          var _response$data = response.data,
              error = _response$data.error,
              file = _response$data.file;
          disableSubmitButton(false);

          if (error) {
            handleGuestUploadFileChanged(error.message, event, null);
          } else {
            handleGuestUploadFileChanged('', event, JSON.stringify(file));
          }

          setProgress(0);
        }).catch(function () {
          disableSubmitButton(false);
          setProgress(0);
        });
      };

      var hasCustomError = !isSignedIn && !allowGuestUsers || maximumSubmissionLimitReached;
      return (/*#__PURE__*/_react.default.createElement(_ReactFieldBase.FieldBase, _extends({}, otherProps, {
          displayErrors: hasCustomError ? true : displayErrors,
          errorMessage: errorMessage,
          id: id,
          name: name,
          overMaximumRepetitionsLimit: maximumRepetitions > 0 ? function checkMaximumRepetitions() {
            var visitor = new _dynamicDataMappingFormRenderer.PagesVisitor(pages);
            var repetitionsCounter = 0;
            visitor.mapFields(function (field) {
              if (fieldName === field.fieldName) {
                repetitionsCounter++;
              }
            }, true, true);
            return repetitionsCounter === maximumRepetitions;
          }() : false,
          readOnly: hasCustomError ? true : readOnly,
          valid: hasCustomError ? false : valid
        }), allowGuestUsers && !isSignedIn ? /*#__PURE__*/_react.default.createElement(GuestUploadFile, {
          fileEntryTitle: fileEntryTitle,
          fileEntryURL: fileEntryURL,
          id: id,
          name: name,
          onBlur: onBlur,
          onClearButtonClicked: function onClearButtonClicked(event) {
            setCurrentValue(null);
            onChange(event, '{}');
            var guestUploadInput = document.getElementById("".concat(name, "inputFileGuestUpload"));

            if (guestUploadInput) {
              guestUploadInput.value = '';
            }
          },
          onFocus: onFocus,
          onUploadSelectButtonClicked: function onUploadSelectButtonClicked(event) {
            return handleUploadSelectButtonClicked(event);
          },
          placeholder: placeholder,
          progress: progress,
          readOnly: hasCustomError ? true : readOnly,
          value: currentValue || ''
        }) : /*#__PURE__*/_react.default.createElement(DocumentLibrary, {
          fileEntryTitle: fileEntryTitle,
          fileEntryURL: fileEntryURL,
          id: id,
          name: name,
          onBlur: onBlur,
          onClearButtonClicked: function onClearButtonClicked(event) {
            setCurrentValue(null);
            onChange(event, '{}');
          },
          onFocus: onFocus,
          onSelectButtonClicked: function onSelectButtonClicked() {
            return handleSelectButtonClicked({
              itemSelectorURL: itemSelectorURL,
              portletNamespace: portletNamespace
            });
          },
          placeholder: placeholder,
          readOnly: hasCustomError ? true : readOnly,
          value: currentValue || ''
        }))
      );
    };

    Main.displayName = 'DocumentLibrary';
    var _default = Main;
    exports.default = _default;
    //# sourceMappingURL=DocumentLibrary.es.js.map
  }
});
//# sourceMappingURL=DocumentLibrary.es.js.map