"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.Component = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _LinearProgress = _interopRequireDefault(require("@material-ui/core/LinearProgress"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _react = _interopRequireDefault(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _debug = _interopRequireDefault(require("debug"));

var _styles = require("@material-ui/core/styles");

var _slatePropTypes = _interopRequireDefault(require("slate-prop-types"));

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var log = (0, _debug["default"])('@pie-lib:editable-html:plugins:image:component');

var size = function size(s) {
  return s ? "".concat(s, "px") : 'auto';
};

var Component = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(Component, _React$Component);

  var _super = _createSuper(Component);

  function Component() {
    var _this;

    (0, _classCallCheck2["default"])(this, Component);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getWidth", function (percent) {
      var multiplier = percent / 100;
      return _this.img.naturalWidth * multiplier;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getHeight", function (percent) {
      var multiplier = percent / 100;
      return _this.img.naturalHeight * multiplier;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getPercentFromWidth", function (width) {
      var floored = width / _this.img.naturalWidth * 4;
      return parseInt(floored.toFixed(0) * 25, 10);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "applySizeData", function () {
      var _this$props = _this.props,
          node = _this$props.node,
          editor = _this$props.editor;
      var update = node.data;
      var w = update.get('width');

      if (w) {
        update = update.set('resizePercent', _this.getPercentFromWidth(w));
      }

      log('[applySizeData] update: ', update);

      if (!update.equals(node.data)) {
        editor.change(function (c) {
          return c.setNodeByKey(node.key, {
            data: update
          });
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "initialiseResize", function () {
      window.addEventListener('mousemove', _this.startResizing, false);
      window.addEventListener('mouseup', _this.stopResizing, false);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "loadImage", function () {
      var _ref = _this.props || {},
          maxImageWidth = _ref.maxImageWidth,
          maxImageHeight = _ref.maxImageHeight;

      maxImageWidth = maxImageWidth || 700;
      maxImageHeight = maxImageHeight || 900;
      var box = _this.img; //on first load

      if (!box.style.width || box.style.width === 'auto') {
        var dimensions = {
          width: box && box.naturalWidth || 100,
          height: box && box.naturalHeight || 100
        };

        var _this$updateImageDime = _this.updateImageDimensions(dimensions, {
          width: dimensions.width < maxImageWidth ? dimensions.width : maxImageWidth,
          height: dimensions.height < maxImageHeight ? dimensions.height : maxImageHeight
        }, true),
            width = _this$updateImageDime.width,
            height = _this$updateImageDime.height;

        box.style.width = "".concat(width, "px");
        box.style.height = "".concat(height, "px");

        _this.setState({
          dimensions: {
            height: height,
            width: width
          }
        });

        var _this$props2 = _this.props,
            node = _this$props2.node,
            editor = _this$props2.editor;
        var update = node.data;
        update = update.set('width', width);
        update = update.set('height', height);

        if (!update.equals(node.data)) {
          editor.change(function (c) {
            return c.setNodeByKey(node.key, {
              data: update
            });
          });
        }
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "startResizing", function (e) {
      var bounds = e.target.getBoundingClientRect();
      var box = _this.img;
      var dimensions = {
        width: box && box.naturalWidth || 100,
        height: box && box.naturalHeight || 100
      };

      var _this$updateImageDime2 = _this.updateImageDimensions(dimensions, {
        width: e.clientX - bounds.left,
        height: e.clientY - bounds.top
      }, true),
          width = _this$updateImageDime2.width,
          height = _this$updateImageDime2.height;

      var hasMinimumWidth = width > 50 && height > 50;
      var hasDimensionsConstraints = width <= 700 && height <= 900;

      if (hasMinimumWidth && hasDimensionsConstraints && box) {
        box.style.width = "".concat(width, "px");
        box.style.height = "".concat(height, "px");

        _this.setState({
          dimensions: {
            height: height,
            width: width
          }
        });

        var _this$props3 = _this.props,
            node = _this$props3.node,
            editor = _this$props3.editor;
        var update = node.data;
        update = update.set('width', width);
        update = update.set('height', height);

        if (!update.equals(node.data)) {
          editor.change(function (c) {
            return c.setNodeByKey(node.key, {
              data: update
            });
          });
        }
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "stopResizing", function () {
      window.removeEventListener('mousemove', _this.startResizing, false);
      window.removeEventListener('mouseup', _this.stopResizing, false);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateImageDimensions", function (initialDim, nextDim, keepAspectRatio, resizeType) {
      // if we want to keep image aspect ratio
      if (keepAspectRatio) {
        var imageAspectRatio = initialDim.width / initialDim.height;

        if (resizeType === 'height') {
          // if we want to change image height => we update the width accordingly
          return {
            width: nextDim.height * imageAspectRatio,
            height: nextDim.height
          };
        } // if we want to change image width => we update the height accordingly


        return {
          width: nextDim.width,
          height: nextDim.width / imageAspectRatio
        };
      } // if we don't want to keep aspect ratio, we just update both values


      return {
        width: nextDim.width,
        height: nextDim.height
      };
    });
    return _this;
  }

  (0, _createClass2["default"])(Component, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.applySizeData();
      var resizeHandle = this.resize;

      if (resizeHandle) {
        resizeHandle.addEventListener('mousedown', this.initialiseResize, false);
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.applySizeData();
    }
  }, {
    key: "getSize",
    value: function getSize(data) {
      return {
        width: size(data.get('width')),
        height: size(data.get('height')),
        objectFit: 'contain'
      };
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props4 = this.props,
          node = _this$props4.node,
          editor = _this$props4.editor,
          classes = _this$props4.classes,
          attributes = _this$props4.attributes,
          onFocus = _this$props4.onFocus;
      var active = editor.value.isFocused && editor.value.selection.hasEdgeIn(node);
      var src = node.data.get('src');
      var loaded = node.data.get('loaded') !== false;
      var deleteStatus = node.data.get('deleteStatus');
      var alignment = node.data.get('alignment');
      var percent = node.data.get('percent');
      var alt = node.data.get('alt');
      var justifyContent;

      switch (alignment) {
        case 'left':
          justifyContent = 'flex-start';
          break;

        case 'center':
          justifyContent = 'center';
          break;

        case 'right':
          justifyContent = 'flex-end';
          break;

        default:
          justifyContent = 'flex-start';
          break;
      }

      log('[render] node.data:', node.data);
      var size = this.getSize(node.data);
      log('[render] style:', size);
      var className = (0, _classnames["default"])(classes.root, !loaded && classes.loading, deleteStatus === 'pending' && classes.pendingDelete);
      var progressClasses = (0, _classnames["default"])(classes.progress, loaded && classes.hideProgress);
      return [/*#__PURE__*/_react["default"].createElement("span", {
        key: 'sp1'
      }, "\xA0"), /*#__PURE__*/_react["default"].createElement("div", {
        key: 'comp',
        onFocus: onFocus,
        className: className,
        style: {
          justifyContent: justifyContent
        }
      }, /*#__PURE__*/_react["default"].createElement(_LinearProgress["default"], {
        mode: "determinate",
        value: percent > 0 ? percent : 0,
        className: progressClasses
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.imageContainer
      }, /*#__PURE__*/_react["default"].createElement("img", (0, _extends2["default"])({}, attributes, {
        className: (0, _classnames["default"])(classes.image, active && classes.active),
        ref: function ref(_ref2) {
          _this2.img = _ref2;
        },
        src: src,
        style: size,
        onLoad: this.loadImage,
        alt: alt
      })), /*#__PURE__*/_react["default"].createElement("div", {
        ref: function ref(_ref3) {
          _this2.resize = _ref3;
        },
        className: (0, _classnames["default"])(classes.resize, 'resize')
      }))), /*#__PURE__*/_react["default"].createElement("span", {
        key: 'sp2'
      }, "\xA0")];
    }
  }]);
  return Component;
}(_react["default"].Component);

exports.Component = Component;
(0, _defineProperty2["default"])(Component, "propTypes", {
  node: _slatePropTypes["default"].node.isRequired,
  editor: _propTypes["default"].shape({
    change: _propTypes["default"].func.isRequired,
    value: _propTypes["default"].object
  }).isRequired,
  classes: _propTypes["default"].object.isRequired,
  attributes: _propTypes["default"].object,
  onFocus: _propTypes["default"].func,
  onBlur: _propTypes["default"].func,
  maxImageWidth: _propTypes["default"].number,
  maxImageHeight: _propTypes["default"].number
});

var styles = function styles(theme) {
  return {
    portal: {
      position: 'absolute',
      opacity: 0,
      transition: 'opacity 200ms linear'
    },
    floatingButtonRow: {
      backgroundColor: theme.palette.background.paper,
      borderRadius: '1px',
      display: 'flex',
      padding: '10px',
      border: "solid 1px ".concat(theme.palette.grey[200]),
      boxShadow: '0px 1px 5px 0px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 3px 1px -2px rgba(0, 0, 0, 0.12)'
    },
    progress: {
      position: 'absolute',
      left: '0',
      width: 'fit-content',
      top: '0%',
      transition: 'opacity 200ms linear'
    },
    hideProgress: {
      opacity: 0
    },
    loading: {
      opacity: 0.3
    },
    pendingDelete: {
      opacity: 0.3
    },
    root: {
      position: 'relative',
      border: "solid 1px ".concat(theme.palette.common.white),
      display: 'flex',
      transition: 'opacity 200ms linear'
    },
    "delete": {
      position: 'absolute',
      right: 0
    },
    imageContainer: {
      position: 'relative',
      width: 'fit-content',
      display: 'flex',
      alignItems: 'center',
      '&&:hover > .resize': {
        display: 'block'
      }
    },
    active: {
      border: "solid 1px ".concat(theme.palette.primary.main)
    },
    resize: {
      backgroundColor: theme.palette.primary.main,
      cursor: 'col-resize',
      height: '35px',
      width: '5px',
      borderRadius: 8,
      marginLeft: '5px',
      marginRight: '10px',
      display: 'none'
    },
    drawableHeight: {
      minHeight: 350
    }
  };
};

var _default = (0, _styles.withStyles)(styles)(Component);

exports["default"] = _default;
//# sourceMappingURL=component.js.map