"use strict";

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

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

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

var _slate = require("slate");

var _Image = _interopRequireDefault(require("@material-ui/icons/Image"));

var _component = _interopRequireDefault(require("./component"));

var _imageToolbar = _interopRequireDefault(require("./image-toolbar"));

var _insertImageHandler = _interopRequireDefault(require("./insert-image-handler"));

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

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

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

function ImagePlugin(opts) {
  var toolbar = opts.insertImageRequested && {
    icon: /*#__PURE__*/_react["default"].createElement(_Image["default"], null),
    onClick: function onClick(value, onChange) {
      log('[toolbar] onClick');

      var inline = _slate.Inline.create({
        type: 'image',
        isVoid: true,
        data: {
          loaded: false,
          src: undefined
        }
      });

      var change = value.change().insertInline(inline);
      onChange(change);
      opts.insertImageRequested(inline, function (onFinish, getValue) {
        return new _insertImageHandler["default"](inline, onFinish, getValue, onChange);
      });
    },
    supports: function supports(node) {
      return node.object === 'inline' && node.type === 'image';
    },
    customToolbar: function customToolbar(node, value, onToolbarDone) {
      var alignment = node.data.get('alignment');
      var alt = node.data.get('alt');
      var imageLoaded = node.data.get('loaded') !== false;

      var onChange = function onChange(newValues, done) {
        var update = _objectSpread(_objectSpread({}, node.data.toObject()), newValues);

        var change = value.change().setNodeByKey(node.key, {
          data: update
        });
        onToolbarDone(change, done);
      };

      var Tb = function Tb() {
        return /*#__PURE__*/_react["default"].createElement(_imageToolbar["default"], {
          disableImageAlignmentButtons: opts.disableImageAlignmentButtons,
          alt: alt,
          imageLoaded: imageLoaded,
          alignment: alignment || 'left',
          onChange: onChange
        });
      };

      return Tb;
    },
    showDone: true
  };
  return {
    name: 'image',
    toolbar: toolbar,
    deleteNode: function deleteNode(e, node, value, onChange) {
      e.preventDefault();

      if (opts.onDelete) {
        var update = node.data.merge(_slate.Data.create({
          deleteStatus: 'pending'
        }));
        var change = value.change().setNodeByKey(node.key, {
          data: update
        });
        onChange(change);
        opts.onDelete(node.data.get('src'), function (err, v) {
          if (!err) {
            change = v.change().removeNodeByKey(node.key);
          } else {
            log('[error]: ', err);
            change = v.change().setNodeByKey(node.key, node.data.merge(_slate.Data.create({
              deleteStatus: 'failed'
            })));
          }

          onChange(change);
        });
      } else {
        var _change = value.change().removeNodeByKey(node.key);

        onChange(_change);
      }
    },
    stopReset: function stopReset(value) {
      var imgPendingInsertion = value.document.findDescendant(function (n) {
        if (n.type !== 'image') {
          return;
        }

        return n.data.get('loaded') === false;
      });
      /** don't reset if there is an image pending insertion */

      return imgPendingInsertion !== undefined && imgPendingInsertion !== null;
    },
    renderNode: function renderNode(props) {
      if (props.node.type === 'image') {
        var all = Object.assign({
          onDelete: opts.onDelete,
          onFocus: opts.onFocus,
          onBlur: opts.onBlur,
          maxImageWidth: opts.maxImageWidth,
          maxImageHeight: opts.maxImageHeight
        }, props);
        return /*#__PURE__*/_react["default"].createElement(_component["default"], all);
      }
    },
    normalizeNode: function normalizeNode(node) {
      var textNodeMap = {};
      var updateNodesArray = [];
      var index = 0;
      if (node.object !== 'document') return;
      node.findDescendant(function (d) {
        if (d.object === 'text') {
          textNodeMap[index] = d;
        }

        if (d.type === 'image') {
          if (index > 0 && textNodeMap[index - 1] && textNodeMap[index - 1].text === '') {
            updateNodesArray.push(textNodeMap[index - 1]);
          }
        }

        index++;
      });
      if (!updateNodesArray.length) return;
      return function (change) {
        change.withoutNormalization(function () {
          updateNodesArray.forEach(function (n) {
            return change.insertTextByKey(n.key, 0, ' ');
          });
        });
      };
    }
  };
}

var serialization = {
  deserialize: function deserialize(el
  /*, next*/
  ) {
    var name = el.tagName.toLowerCase();
    if (name !== 'img') return;
    log('deserialize: ', name);
    var style = el.style || {
      width: '',
      height: '',
      margin: '',
      justifyContent: ''
    };
    var width = parseInt(style.width.replace('px', ''), 10) || null;
    var height = parseInt(style.height.replace('px', ''), 10) || null;
    var out = {
      object: 'inline',
      type: 'image',
      isVoid: true,
      data: {
        src: el.getAttribute('src'),
        width: width,
        height: height,
        margin: el.style.margin,
        justifyContent: el.style.justifyContent,
        alignment: el.getAttribute('alignment'),
        alt: el.getAttribute('alt')
      }
    };
    log('return object: ', out);
    return out;
  },
  serialize: function serialize(object
  /*, children*/
  ) {
    if (object.type !== 'image') return;
    var data = object.data;
    var src = data.get('src');
    var width = data.get('width');
    var height = data.get('height');
    var alignment = data.get('alignment') || 'left';
    var margin = data.get('margin');
    var justifyContent = data.get('margin');
    var alt = data.get('alt');
    var style = {};

    if (width) {
      style.width = "".concat(width, "px");
    }

    if (height) {
      style.height = "".concat(height, "px");
    }

    style.margin = margin;
    style.justifyContent = justifyContent;

    if (alignment) {
      switch (alignment) {
        case 'left':
          style.justifyContent = 'flex-start';
          style.margin = '0';
          break;

        case 'center':
          style.justifyContent = 'center';
          style.margin = '0 auto';
          break;

        case 'right':
          style.justifyContent = 'flex-end';
          style.margin = 'auto 0 0 auto';
          break;

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

    style.objectFit = 'contain';
    var props = {
      src: src,
      style: style,
      alignment: alignment,
      alt: alt
    };
    return /*#__PURE__*/_react["default"].createElement("img", props);
  }
};
exports.serialization = serialization;
//# sourceMappingURL=index.js.map