Liferay.Loader.define("dynamic-data-mapping-form-field-type@5.0.45/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', 'dynamic-data-mapping-form-renderer', '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 _dynamicDataMappingFormRenderer = require("dynamic-data-mapping-form-renderer");

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

    function getDocumentLibrarySelectorURL(_ref) {
      var groupId = _ref.groupId,
          itemSelectorAuthToken = _ref.itemSelectorAuthToken,
          portletNamespace = _ref.portletNamespace;
      var criterionJSON = {
        desiredItemSelectorReturnTypes: 'com.liferay.item.selector.criteria.FileEntryItemSelectorReturnType,com.liferay.item.selector.criteria.FileEntryItemSelectorReturnType'
      };
      var uploadCriterionJSON = {
        URL: getUploadURL(),
        desiredItemSelectorReturnTypes: 'com.liferay.item.selector.criteria.FileEntryItemSelectorReturnType,com.liferay.item.selector.criteria.FileEntryItemSelectorReturnType'
      };
      var documentLibrarySelectorParameters = {
        '0_json': JSON.stringify(criterionJSON),
        '1_json': JSON.stringify(criterionJSON),
        '2_json': JSON.stringify(uploadCriterionJSON),
        criteria: 'com.liferay.item.selector.criteria.file.criterion.FileItemSelectorCriterion',
        doAsGroupId: groupId,
        itemSelectedEventName: "".concat(portletNamespace, "selectDocumentLibrary"),
        p_p_auth: itemSelectorAuthToken,
        p_p_id: Liferay.PortletKeys.ITEM_SELECTOR,
        p_p_mode: 'view',
        p_p_state: 'pop_up',
        refererGroupId: groupId
      };
      var documentLibrarySelectorURL = (0, _frontendJsWeb.createPortletURL)(themeDisplay.getLayoutRelativeControlPanelURL(), documentLibrarySelectorParameters);
      return documentLibrarySelectorURL.toString();
    }

    function getUploadURL() {
      var uploadParameters = {
        cmd: 'add_temp',
        'javax.portlet.action': '/document_library/upload_file_entry',
        p_auth: Liferay.authToken,
        p_p_id: Liferay.PortletKeys.DOCUMENT_LIBRARY
      };
      var uploadURL = (0, _frontendJsWeb.createActionURL)(themeDisplay.getLayoutRelativeURL(), uploadParameters);
      return uploadURL.toString();
    }

    var CardItem = function CardItem(_ref2) {
      var fileEntryTitle = _ref2.fileEntryTitle,
          fileEntryURL = _ref2.fileEntryURL;
      return _react["default"].createElement(_card["default"], {
        horizontal: true
      }, _react["default"].createElement(_card["default"].Body, null, _react["default"].createElement("div", {
        className: "card-col-content card-col-gutters"
      }, _react["default"].createElement("h4", {
        className: "text-truncate",
        title: fileEntryTitle
      }, fileEntryTitle)), _react["default"].createElement("div", {
        className: "card-col-field"
      }, _react["default"].createElement("a", {
        download: fileEntryTitle,
        href: fileEntryURL
      }, _react["default"].createElement(_icon["default"], {
        symbol: "download"
      })))));
    };

    function transformFileEntryProperties(_ref3) {
      var fileEntryTitle = _ref3.fileEntryTitle,
          fileEntryURL = _ref3.fileEntryURL,
          value = _ref3.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 [fileEntryTitle, fileEntryURL];
    }

    var DocumentLibrary = function DocumentLibrary(_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,
          onClearButtonClicked = _ref4.onClearButtonClicked,
          onSelectButtonClicked = _ref4.onSelectButtonClicked,
          placeholder = _ref4.placeholder,
          readOnly = _ref4.readOnly,
          value = _ref4.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 _react["default"].createElement("div", {
        className: "liferay-ddm-form-field-document-library"
      }, transformedFileEntryURL && readOnly ? _react["default"].createElement(CardItem, {
        fileEntryTitle: transformedFileEntryTitle,
        fileEntryURL: transformedFileEntryURL
      }) : _react["default"].createElement(_form.ClayInput.Group, null, _react["default"].createElement(_form.ClayInput.GroupItem, {
        prepend: true
      }, _react["default"].createElement(_form.ClayInput, {
        "aria-label": Liferay.Language.get('file'),
        className: "field",
        disabled: true,
        id: "".concat(name, "inputFile"),
        value: transformedFileEntryTitle || ''
      })), _react["default"].createElement(_form.ClayInput.GroupItem, {
        append: true,
        shrink: true
      }, _react["default"].createElement(_button["default"], {
        className: "select-button",
        disabled: readOnly,
        displayType: "secondary",
        onClick: onSelectButtonClicked
      }, _react["default"].createElement("span", {
        className: "lfr-btn-label"
      }, Liferay.Language.get('select')))), transformedFileEntryTitle && _react["default"].createElement(_form.ClayInput.GroupItem, {
        append: true,
        shrink: true
      }, _react["default"].createElement(_button.ClayButtonWithIcon, {
        "aria-label": Liferay.Language.get('unselect-file'),
        className: "clear-button",
        displayType: "secondary",
        onClick: onClearButtonClicked,
        symbol: "times"
      }))), _react["default"].createElement(_form.ClayInput, {
        id: id ? id : name,
        name: name,
        placeholder: placeholder,
        type: "hidden",
        value: value || ''
      }));
    };

    var Main = function Main(_ref5) {
      var displayErrors = _ref5.displayErrors,
          errorMessage = _ref5.errorMessage,
          fileEntryTitle = _ref5.fileEntryTitle,
          fileEntryURL = _ref5.fileEntryURL,
          groupId = _ref5.groupId,
          id = _ref5.id,
          itemSelectorAuthToken = _ref5.itemSelectorAuthToken,
          name = _ref5.name,
          onBlur = _ref5.onBlur,
          onChange = _ref5.onChange,
          onFocus = _ref5.onFocus,
          placeholder = _ref5.placeholder,
          readOnly = _ref5.readOnly,
          valid = _ref5.valid,
          _ref5$value = _ref5.value,
          value = _ref5$value === void 0 ? '{}' : _ref5$value,
          otherProps = _objectWithoutProperties(_ref5, ["displayErrors", "errorMessage", "fileEntryTitle", "fileEntryURL", "groupId", "id", "itemSelectorAuthToken", "name", "onBlur", "onChange", "onFocus", "placeholder", "readOnly", "valid", "value"]);

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

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

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

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

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

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

      var isSignedIn = Liferay.ThemeDisplay.isSignedIn();
      return _react["default"].createElement(_ReactFieldBase.FieldBase, _extends({}, otherProps, {
        displayErrors: isSignedIn ? displayErrors : true,
        errorMessage: function getErrorMessages(errorMessage, isSignedIn) {
          var errorMessages = [errorMessage];

          if (!isSignedIn) {
            errorMessages.push(Liferay.Language.get('you-need-to-be-signed-in-to-edit-this-field'));
          }

          return errorMessages.join(' ');
        }(errorMessage, isSignedIn),
        id: id,
        name: name,
        readOnly: isSignedIn ? readOnly : true,
        valid: isSignedIn ? valid : false
      }), _react["default"].createElement(DocumentLibrary, {
        fileEntryTitle: fileEntryTitle,
        fileEntryURL: fileEntryURL,
        id: id,
        name: name,
        onClearButtonClicked: function onClearButtonClicked(event) {
          setCurrentValue(null);
          onChange(event, '{}');
        },
        onSelectButtonClicked: function onSelectButtonClicked() {
          return handleSelectButtonClicked({
            itemSelectorAuthToken: itemSelectorAuthToken,
            portletNamespace: portletNamespace
          });
        },
        placeholder: placeholder,
        readOnly: isSignedIn ? readOnly : true,
        value: currentValue || ''
      }));
    };

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