Liferay.Loader.define("item-selector-taglib@4.1.43/repository_entry_browser/js/ItemSelectorRepositoryEntryBrowser.es", ['module', 'exports', 'require', 'frontend-taglib-clay$clay-alert', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-metal-web$metal-dom', 'frontend-js-metal-web$metal-events', 'frontend-js-metal-web$metal-state', 'frontend-js-react-web$react-dom', '../../item_selector_preview/js/ItemSelectorPreview.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _clayAlert = require("frontend-taglib-clay$clay-alert");

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

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

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

    var _metalEvents = require("frontend-js-metal-web$metal-events");

    var _metalState = require("frontend-js-metal-web$metal-state");

    var _reactDom = _interopRequireDefault(require("frontend-js-react-web$react-dom"));

    var _ItemSelectorPreview = _interopRequireDefault(require("../../item_selector_preview/js/ItemSelectorPreview.es"));

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

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

    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }

    function _defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    function _createClass(Constructor, protoProps, staticProps) {
      if (protoProps) _defineProperties(Constructor.prototype, protoProps);if (staticProps) _defineProperties(Constructor, staticProps);return Constructor;
    }

    function _possibleConstructorReturn(self, call) {
      if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
      }return _assertThisInitialized(self);
    }

    function _assertThisInitialized(self) {
      if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }return self;
    }

    function _get(target, property, receiver) {
      if (typeof Reflect !== "undefined" && Reflect.get) {
        _get = Reflect.get;
      } else {
        _get = function _get(target, property, receiver) {
          var base = _superPropBase(target, property);if (!base) return;var desc = Object.getOwnPropertyDescriptor(base, property);if (desc.get) {
            return desc.get.call(receiver);
          }return desc.value;
        };
      }return _get(target, property, receiver || target);
    }

    function _superPropBase(object, property) {
      while (!Object.prototype.hasOwnProperty.call(object, property)) {
        object = _getPrototypeOf(object);if (object === null) break;
      }return object;
    }

    function _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

    function _inherits(subClass, superClass) {
      if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
      }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });if (superClass) _setPrototypeOf(subClass, superClass);
    }

    function _setPrototypeOf(o, p) {
      _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;return o;
      };return _setPrototypeOf(o, p);
    }

    var STR_DRAG_LEAVE = 'dragleave';
    var STR_DRAG_OVER = 'dragover';
    var STR_DROP = 'drop';
    var statusCode = Liferay.STATUS_CODE;
    /**
     * Handles the events in the Repository Entry Browser taglib.
     *
     * @abstract
     * @extends {PortletBase}
     */

    var ItemSelectorRepositoryEntryBrowser = /*#__PURE__*/function (_PortletBase) {
      _inherits(ItemSelectorRepositoryEntryBrowser, _PortletBase);

      function ItemSelectorRepositoryEntryBrowser() {
        _classCallCheck(this, ItemSelectorRepositoryEntryBrowser);

        return _possibleConstructorReturn(this, _getPrototypeOf(ItemSelectorRepositoryEntryBrowser).apply(this, arguments));
      }

      _createClass(ItemSelectorRepositoryEntryBrowser, [{
        key: "created",

        /**
         * @inheritDoc
         */
        value: function created() {
          this._eventHandler = new _metalEvents.EventHandler();
        }
        /**
         * @inheritDoc
         */

      }, {
        key: "attached",
        value: function attached() {
          var _this = this;

          AUI().use('liferay-item-selector-uploader', function (A) {
            _this._itemSelectorUploader = new A.LiferayItemSelectorUploader({
              rootNode: _this.rootNode
            });

            _this._bindEvents();
          });
          this.attachItemSelectorPreviewComponent();
        }
      }, {
        key: "attachItemSelectorPreviewComponent",
        value: function attachItemSelectorPreviewComponent() {
          var _this2 = this;

          var itemsNodes = Array.from(this.all('.item-preview'));
          var items = itemsNodes.map(function (node) {
            return node.dataset;
          });
          var clicableItems = Array.from(this.all('.icon-view'));

          if (items.length === clicableItems.length) {
            clicableItems.forEach(function (clicableItem, index) {
              clicableItem.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();

                _this2.openItemSelectorPreview(items, index);
              });
            });
          }

          this._itemSelectorPreviewContainer = this.one('.item-selector-preview-container');
        }
      }, {
        key: "openItemSelectorPreview",
        value: function openItemSelectorPreview(items, index) {
          var container = this._itemSelectorPreviewContainer;
          var data = {
            container: container,
            currentIndex: index,
            editItemURL: this.editItemURL,
            handleSelectedItem: this._onItemSelected.bind(this),
            headerTitle: this.closeCaption,
            items: items,
            uploadItemReturnType: this.uploadItemReturnType,
            uploadItemURL: this.uploadItemURL
          };
          (0, _frontendJsReactWeb.render)(_ItemSelectorPreview.default, data, container);
        }
      }, {
        key: "closeItemSelectorPreview",
        value: function closeItemSelectorPreview() {
          _reactDom.default.unmountComponentAtNode(this._itemSelectorPreviewContainer);
        }
        /**
         * @inheritDoc
         */

      }, {
        key: "detached",
        value: function detached() {
          _get(_getPrototypeOf(ItemSelectorRepositoryEntryBrowser.prototype), "detached", this).call(this);

          this._itemSelectorUploader.destroy();

          this._eventHandler.removeAllListeners();
        }
        /**
         * Bind events
         *
         * @private
         */

      }, {
        key: "_bindEvents",
        value: function _bindEvents() {
          var _this3 = this;

          this._eventHandler.add(_metalDom.default.delegate(this.rootNode, 'click', '.item-preview', function (event) {
            return _this3._onItemSelected(event.delegateTarget.dataset);
          }));

          var inputFileNode = this.one('input[type="file"]');

          if (inputFileNode) {
            this._eventHandler.add(inputFileNode.addEventListener('change', function (event) {
              _this3._validateFile(event.target.files[0]);
            }));
          }

          if (this.uploadItemURL) {
            var itemSelectorUploader = this._itemSelectorUploader;
            var rootNode = this.rootNode;

            this._eventHandler.add(itemSelectorUploader.after('itemUploadCancel', function () {
              _this3.closeItemSelectorPreview();
            }), itemSelectorUploader.after('itemUploadComplete', function (itemData) {
              var itemFile = itemData.file;
              var itemFileUrl = itemFile.url;
              var itemFileValue = itemFile.resolvedValue;

              if (!itemFileValue) {
                var imageValue = {
                  fileEntryId: itemFile.fileEntryId,
                  groupId: itemFile.groupId,
                  title: itemFile.title,
                  type: itemFile.type,
                  url: itemFileUrl,
                  uuid: itemFile.uuid
                };
                itemFileValue = JSON.stringify(imageValue);
              }

              Liferay.componentReady('ItemSelectorPreview').then(function () {
                Liferay.fire('updateCurrentItem', {
                  url: itemFileUrl,
                  value: itemFileValue
                });
              });
            }), itemSelectorUploader.after('itemUploadError', function (event) {
              _this3._onItemUploadError(event);
            }), rootNode.addEventListener(STR_DRAG_OVER, function (event) {
              return _this3._ddEventHandler(event);
            }), rootNode.addEventListener(STR_DRAG_LEAVE, function (event) {
              return _this3._ddEventHandler(event);
            }), rootNode.addEventListener(STR_DROP, function (event) {
              return _this3._ddEventHandler(event);
            }));
          }
        }
        /**
         * @private
         */

      }, {
        key: "_closeAlert",
        value: function _closeAlert() {
          if (this._alert && !this._alert.isDisposed()) {
            this._alert.emit('hide');

            this._alert = null;
          }

          clearTimeout(this._hideTimeout);
        }
        /**
         * Converts a String to a Number.
         *
         * @param  {Number | String}
         * @private
         * @return {Number}
         */

      }, {
        key: "_convertMaxFileSize",
        value: function _convertMaxFileSize(maxFileSize) {
          return parseInt(maxFileSize, 10);
        }
        /**
         * Handles drag and drop events.
         *
         * @param  {!Event}
         * @private
         */

      }, {
        key: "_ddEventHandler",
        value: function _ddEventHandler(event) {
          var dataTransfer = event.dataTransfer;

          if (dataTransfer && dataTransfer.types) {
            var dataTransferTypes = dataTransfer.types || [];

            if (dataTransferTypes.indexOf('Files') > -1 && dataTransferTypes.indexOf('text/html') === -1) {
              event.preventDefault();
              var type = event.type;
              var eventDrop = type === STR_DROP;
              var rootNode = this.rootNode;

              if (type === STR_DRAG_OVER) {
                rootNode.classList.add('drop-active');
              } else if (type === STR_DRAG_LEAVE || eventDrop) {
                rootNode.classList.remove('drop-active');

                if (eventDrop) {
                  this._validateFile(dataTransfer.files[0]);
                }
              }
            }
          }
        }
        /**
         * Returns the message to show when the upload fails.
         *
         * @param  {Object} error
         * @private
         * @return {String} error message
         */

      }, {
        key: "_getUploadErrorMessage",
        value: function _getUploadErrorMessage(error) {
          var message = Liferay.Language.get('an-unexpected-error-occurred-while-uploading-your-file');

          if (error && error.errorType) {
            var errorType = error.errorType;

            switch (errorType) {
              case statusCode.SC_FILE_ANTIVIRUS_EXCEPTION:
                if (error.message) {
                  message = error.message;
                }

                break;

              case statusCode.SC_FILE_EXTENSION_EXCEPTION:
                if (error.message) {
                  message = Liferay.Util.sub(Liferay.Language.get('please-enter-a-file-with-a-valid-extension-x'), [error.message]);
                } else {
                  message = Liferay.Language.get('please-enter-a-file-with-a-valid-file-type');
                }

                break;

              case statusCode.SC_FILE_NAME_EXCEPTION:
                message = Liferay.Language.get('please-enter-a-file-with-a-valid-file-name');
                break;

              case statusCode.SC_FILE_SIZE_EXCEPTION:
              case statusCode.SC_UPLOAD_REQUEST_CONTENT_LENGTH_EXCEPTION:
                message = Liferay.Util.sub(Liferay.Language.get('please-enter-a-file-with-a-valid-file-size-no-larger-than-x'), [Liferay.Util.formatStorage(this.maxFileSize)]);
                break;

              case statusCode.SC_UPLOAD_REQUEST_SIZE_EXCEPTION:
                {
                  var maxUploadRequestSize = Liferay.PropsValues.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE;
                  message = Liferay.Util.sub(Liferay.Language.get('request-is-larger-than-x-and-could-not-be-processed'), [Liferay.Util.formatStorage(maxUploadRequestSize)]);
                  break;
                }

              default:
                {
                  message = Liferay.Language.get('an-unexpected-error-occurred-while-uploading-your-file');
                }
            }
          }

          return message;
        }
        /**
         * Generates the JSON that the item viewer
         * need to show in the info panel.
         *
         * @param {File}
         * @return {JSON}
         */

      }, {
        key: "_getUploadFileMetadata",
        value: function _getUploadFileMetadata(file) {
          return {
            groups: [{
              data: [{
                key: Liferay.Language.get('format'),
                value: file.type
              }, {
                key: Liferay.Language.get('size'),
                value: Liferay.Util.formatStorage(file.size)
              }, {
                key: Liferay.Language.get('name'),
                value: file.name
              }],
              title: Liferay.Language.get('file-info')
            }]
          };
        }
        /**
         * Send the selected item.
         *
         * @param {Object} item
         * @private
         */

      }, {
        key: "_onItemSelected",
        value: function _onItemSelected(item) {
          this.emit('selectedItem', {
            data: {
              returnType: item.returntype,
              value: item.value
            }
          });
        }
        /**
         *
         * Handles the error during the item upload.
         *
         * @param {!Event}
         * @private
         */

      }, {
        key: "_onItemUploadError",
        value: function _onItemUploadError(event) {
          this.closeItemSelectorPreview();

          this._showError(this._getUploadErrorMessage(event.error));
        }
        /**
         * Reads the file.
         *
         * @param  {File}
         * @private
         */

      }, {
        key: "_previewFile",
        value: function _previewFile(file) {
          var _this4 = this;

          if (window.FileReader) {
            var reader = new FileReader();
            reader.addEventListener('loadend', function (event) {
              _this4._showFile(file, event.target.result);
            });
            reader.readAsDataURL(file);
          }
        }
        /**
         * Shows an error message
         *
         * @param {String} message
         * @private
         */

      }, {
        key: "_showError",
        value: function _showError(message) {
          var _this5 = this;

          this._alert = new _clayAlert.ClayAlert({
            closeable: true,
            destroyOnHide: true,
            message: message,
            spritemap: Liferay.ThemeDisplay.getPathThemeImages() + '/clay/icons.svg',
            style: 'danger',
            title: '',
            visible: true
          }, this.one('.message-container'));
          this._hideTimeout = setTimeout(function () {
            return _this5._closeAlert();
          }, this.hideAlertDelay);
        }
        /**
         * Shows the selected item in the Item Viewer and
         * uploads to the server.
         *
         * @param  {File} file
         * @param  {String} Preview of the item in Base64 code
         */

      }, {
        key: "_showFile",
        value: function _showFile(file, preview) {
          if (!file.type.match(/image.*/)) {
            preview = Liferay.ThemeDisplay.getPathThemeImages() + '/file_system/large/default.png';
          }

          var item = {
            base64: preview,
            metadata: JSON.stringify(this._getUploadFileMetadata(file)),
            returntype: this.uploadItemReturnType,
            title: file.name,
            value: preview
          };
          this.openItemSelectorPreview([item], 0);

          this._itemSelectorUploader.startUpload(file, this.uploadItemURL);
        }
        /**
         * Validates file's extension and size.
         *
         * @param {File} file The selected file
         * @private
         */

      }, {
        key: "_validateFile",
        value: function _validateFile(file) {
          var errorMessage = '';
          var fileExtension = file.name.split('.').pop().toLowerCase();
          var validExtensions = this.validExtensions;

          if (validExtensions === '*' || validExtensions.indexOf(fileExtension) != -1) {
            var maxFileSize = this.maxFileSize;

            if (file.size <= maxFileSize) {
              this._previewFile(file);
            } else {
              errorMessage = Liferay.Util.sub(Liferay.Language.get('please-enter-a-file-with-a-valid-file-size-no-larger-than-x'), [Liferay.Util.formatStorage(maxFileSize)]);
            }
          } else {
            errorMessage = Liferay.Util.sub(Liferay.Language.get('please-enter-a-file-with-a-valid-extension-x'), [validExtensions]);
          }

          if (errorMessage) {
            var inputTypeFile = this.one('input[type="file"]');

            if (inputTypeFile) {
              inputTypeFile.value = '';
            }

            this._showError(errorMessage);
          }
        }
      }]);

      return ItemSelectorRepositoryEntryBrowser;
    }(_frontendJsWeb.PortletBase);
    /**
     * State definition.
     *
     * @static
     * @type {!Object}
     */

    ItemSelectorRepositoryEntryBrowser.STATE = {
      /**
       * Text to show near the close icon in the Item Viewer
       *
       * @instance
       * @memberof ItemSelectorRepositoryEntryBrowser
       * @type {String}
       */
      closeCaption: _metalState.Config.string(),

      /**
       * Url to edit the item.
       *
       * @instance
       * @memberof ItemSelectorRepositoryEntryBrowser
       * @type {String}
       */
      editItemURL: _metalState.Config.string(),

      /**
       * Time to hide the alert messages.
       *
       * @type {Number} milliseconds
       */
      hideAlertDelay: _metalState.Config.number().value(5000).internal(),

      /**
       * Maximum allowed file size to drop in the item selector.
       *
       * @instance
       * @memberof ItemSelectorRepositoryEntryBrowser
       * @type {Number | String}
       */
      maxFileSize: _metalState.Config.oneOfType([_metalState.Config.number(), _metalState.Config.string()]).setter('_convertMaxFileSize').value(Liferay.PropsValues.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE),

      /**
       * The return type for the uploaded item.
       *
       * @instance
       * @memberof ItemSelectorRepositoryEntryBrowser
       * @type {String}
       */
      uploadItemReturnType: _metalState.Config.string(),

      /**
       * URL to upload an item.
       *
       * @instance
       * @memberof ItemSelectorRepositoryEntryBrowser
       * @type {String}
       */
      uploadItemURL: _metalState.Config.string(),

      /**
       * Valid extensions for files uploaded to the Item Selector.
       *
       * @instance
       * @memberof ItemSelectorRepositoryEntryBrowser
       * @type {String}
       */
      validExtensions: _metalState.Config.string().value('*')
    };
    var _default = ItemSelectorRepositoryEntryBrowser;
    exports.default = _default;
    //# sourceMappingURL=ItemSelectorRepositoryEntryBrowser.es.js.map
  }
});
//# sourceMappingURL=ItemSelectorRepositoryEntryBrowser.es.js.map