Liferay.Loader.define("frontend-image-editor-web@4.0.37/EffectsComponent.es", ['module', 'exports', 'require', 'frontend-js-metal-web$metal', 'frontend-js-metal-web$metal-component', 'frontend-js-metal-web$metal-soy', './EffectsComponent.soy', './EffectsControls.soy'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

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

    var _metalComponent = _interopRequireDefault(require("frontend-js-metal-web$metal-component"));

    var _metalSoy = _interopRequireDefault(require("frontend-js-metal-web$metal-soy"));

    var _EffectsComponent = _interopRequireDefault(require("./EffectsComponent.soy"));

    require("./EffectsControls.soy");

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

    /**
     * Creates an Effects component.
     */
    var EffectsComponent = /*#__PURE__*/function (_Component) {
      _inherits(EffectsComponent, _Component);

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

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

      _createClass(EffectsComponent, [{
        key: "attached",

        /**
         * @inheritDoc
         */
        value: function attached() {
          var _this = this;

          this.cache_ = {};

          _metal.async.nextTick(function () {
            _this.getImageEditorImageData().then(function (imageData) {
              return Promise.resolve(_this.generateThumbnailImageData_(imageData));
            }).then(function (previewImageData) {
              return _this.generateThumbnails_(previewImageData);
            }).then(function () {
              return _this.prefetchEffects_();
            });
          });
        }
        /**
         * @inheritDoc
         */

      }, {
        key: "detached",
        value: function detached() {
          this.cache_ = {};
        }
        /**
         * Returns <code>true</code> if the carousel can be scrolled to the right.
         *
         * @private
         * @return {boolean} <code>True</code> if the carousel can be scrolled to
         * the right; <code>false</code> otherwise.
         */

      }, {
        key: "canScrollForward_",
        value: function canScrollForward_() {
          var carousel = this.refs.carousel;
          var continer = this.refs.carouselContainer;
          var offset = Math.abs(parseInt(carousel.style.marginLeft || 0, 10));
          var viewportWidth = parseInt(continer.offsetWidth, 10);
          var maxContentWidth = parseInt(carousel.offsetWidth, 10);
          return offset + viewportWidth < maxContentWidth;
        }
        /**
         * Generates a thumbnail for a given effect.
         *
         * @param  {String} effect The effect to generate the thumbnail for.
         * @param  {ImageData} imageData The image data to which the effect is applied.
         * @return {Promise} A promise that resolves when the thumbnail
         * is generated.
         */

      }, {
        key: "generateThumbnail_",
        value: function generateThumbnail_(effect, imageData) {
          var _this2 = this;

          var promise = this.spawnWorker_({
            effect: effect,
            imageData: imageData
          });
          promise.then(function (imageData) {
            var canvas = _this2.element.querySelector('#' + _this2.ref + effect + ' canvas');

            canvas.getContext('2d').putImageData(imageData, 0, 0);
          });
          return promise;
        }
        /**
         * Generates the complete set of thumbnails for the component effects.
         *
         * @param  {ImageData} imageData The thumbnail image data (small version).
         * @return {Promise} A promise that resolves when the thumbnails
         * are generated.
         */

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

          return Promise.all(this.effects.map(function (effect) {
            return _this3.generateThumbnail_(effect, imageData);
          }));
        }
        /**
         * Generates a resized version of the image data to generate the thumbnails
         * more efficiently.
         *
         * @param  {ImageData} imageData The original image data.
         * @return {ImageData} The resized image data.
         */

      }, {
        key: "generateThumbnailImageData_",
        value: function generateThumbnailImageData_(imageData) {
          var thumbnailSize = this.thumbnailSize;
          var imageWidth = imageData.width;
          var imageHeight = imageData.height;
          var rawCanvas = document.createElement('canvas');
          rawCanvas.width = imageWidth;
          rawCanvas.height = imageHeight;
          rawCanvas.getContext('2d').putImageData(imageData, 0, 0);
          var commonSize = imageWidth > imageHeight ? imageHeight : imageWidth;
          var canvas = document.createElement('canvas');
          canvas.width = thumbnailSize;
          canvas.height = thumbnailSize;
          var context = canvas.getContext('2d');
          context.drawImage(rawCanvas, imageWidth - commonSize, imageHeight - commonSize, commonSize, commonSize, 0, 0, thumbnailSize, thumbnailSize);
          return context.getImageData(0, 0, thumbnailSize, thumbnailSize);
        }
        /**
         * Prefetches all the effect results.
         *
         * @return {Promise} A promise that resolves when all the effects
         * are prefetched.
         */

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

          return new Promise(function (resolve) {
            if (!_this4.isDisposed()) {
              var missingEffects = _this4.effects.filter(function (effect) {
                return !_this4.cache_[effect];
              });

              if (!missingEffects.length) {
                resolve();
              } else {
                _this4.getImageEditorImageData().then(function (imageData) {
                  return _this4.process(imageData, missingEffects[0]);
                }).then(function () {
                  return _this4.prefetchEffects_();
                });
              }
            }
          });
        }
        /**
         * Applies the selected effect to the image.
         *
         * @param  {ImageData} imageData The image data representation of the image.
         * @return {Promise} A promise that resolves when the webworker
         * finishes processing the image.
         */

      }, {
        key: "preview",
        value: function preview(imageData) {
          return this.process(imageData);
        }
        /**
         * Notifies the editor that the component wants to generate a new preview of
         * the current image.
         *
         * @param  {MouseEvent} event The mouse event.
         */

      }, {
        key: "previewEffect",
        value: function previewEffect(event) {
          this.currentEffect_ = event.delegateTarget.getAttribute('data-effect');
          this.requestImageEditorPreview();
        }
        /**
         * Applies the selected effect to the image.
         *
         * @param  {ImageData} imageData The image data representation of the image.
         * @param {String} effectName The effect to apply to the image.
         * @return {Promise} A promise that resolves when the webworker
         * finishes processing the image.
         */

      }, {
        key: "process",
        value: function process(imageData, effectName) {
          var effect = effectName || this.currentEffect_;
          var promise = this.cache_[effect];

          if (!promise) {
            promise = this.spawnWorker_({
              effect: effect,
              imageData: imageData
            });
            this.cache_[effect] = promise;
          }

          return promise;
        }
        /**
         * Makes the carousel scroll left to reveal options of the visible area.
         *
         * @return void
         */

      }, {
        key: "scrollLeft",
        value: function scrollLeft() {
          var carousel = this.refs.carousel;
          var itemWidth = this.refs.carouselFirstItem.offsetWidth || 0;
          var marginLeft = parseInt(carousel.style.marginLeft || 0, 10);

          if (marginLeft < 0) {
            var newMarginValue = Math.min(marginLeft + itemWidth, 0);
            this.carouselOffset = newMarginValue + 'px';
          }
        }
        /**
         * Makes the carousel scroll right to reveal options of the visible area.
         *
         * @return void
         */

      }, {
        key: "scrollRight",
        value: function scrollRight() {
          if (this.canScrollForward_()) {
            var carousel = this.refs.carousel;
            var itemWidth = this.refs.carouselFirstItem.offsetWidth || 0;
            var marginLeft = parseInt(carousel.style.marginLeft || 0, 10);
            this.carouselOffset = marginLeft - itemWidth + 'px';
          }
        }
        /**
         * Spawns a webworker to process the image in a different thread.
         *
         * @param  {String} workerURI The URI of the worker to spawn.
         * @param  {Object} message The image and effect preset.
         * @return {Promise} A promise that resolves when the webworker
         * finishes processing the image.
         */

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

          return new Promise(function (resolve) {
            var processWorker = new Worker(_this5.modulePath + '/EffectsWorker.js');

            processWorker.onmessage = function (event) {
              return resolve(event.data);
            };

            processWorker.postMessage(message);
          });
        }
      }]);

      return EffectsComponent;
    }(_metalComponent.default);
    /**
     * State definition.
     *
     * @static
     * @type {!Object}
     */

    EffectsComponent.STATE = {
      /**
       * Offset in pixels (<code>px</code> postfix) for the carousel item.
       *
       * @type {String}
       */
      carouselOffset: {
        validator: _metal.core.isString,
        value: '0'
      },

      /**
       * Array of available effects.
       *
       * @type {Object}
       */
      effects: {
        validator: _metal.core.isArray,
        value: ['none', 'ruby', 'absinthe', 'chroma', 'atari', 'tripel', 'ailis', 'flatfoot', 'pyrexia', 'umbra', 'rouge', 'idyll', 'glimmer', 'elysium', 'nucleus', 'amber', 'paella', 'aureus', 'expanse', 'orchid']
      },

      /**
       * Injected helper that retrieves the editor image data.
       *
       * @type {Function}
       */
      getImageEditorImageData: {
        validator: _metal.core.isFunction
      },

      /**
       * Path of this module.
       *
       * @type {Function}
       */
      modulePath: {
        validator: _metal.core.isString
      },

      /**
       * Injected helper that retrieves the editor image data.
       *
       * @type {Function}
       */
      requestImageEditorPreview: {
        validator: _metal.core.isFunction
      },

      /**
       * Size of the thumbnails (size x size).
       *
       * @type {Number}
       */
      thumbnailSize: {
        validator: _metal.core.isNumber,
        value: 55
      }
    };

    _metalSoy.default.register(EffectsComponent, _EffectsComponent.default);

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