"use strict";

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

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

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

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

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

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

var _reactDom = _interopRequireDefault(require("react-dom"));

var _slate = require("slate");

var _Theaters = _interopRequireDefault(require("@material-ui/icons/Theaters"));

var _VolumeUp = _interopRequireDefault(require("@material-ui/icons/VolumeUp"));

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

var _mediaDialog = _interopRequireDefault(require("./media-dialog"));

var _mediaToolbar = _interopRequireDefault(require("./media-toolbar"));

var _mediaWrapper = _interopRequireDefault(require("./media-wrapper"));

var _excluded = ["type", "callback", "opts"],
    _excluded2 = ["src", "height", "width", "editing", "tag"];

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

var removeDialogs = function removeDialogs() {
  var prevDialogs = document.querySelectorAll('.insert-media-dialog');
  prevDialogs.forEach(function (s) {
    return s.remove();
  });
};

var insertDialog = function insertDialog(props) {
  var newEl = document.createElement('div');
  var type = props.type,
      callback = props.callback,
      opts = props.opts,
      rest = (0, _objectWithoutProperties2["default"])(props, _excluded);
  var initialBodyOverflow = document.body.style.overflow;
  removeDialogs();
  newEl.className = 'insert-media-dialog';
  document.body.style.overflow = 'hidden';

  var handleClose = function handleClose(val, data) {
    callback(val, data);
    newEl.remove();
    document.body.style.overflow = initialBodyOverflow;
  };

  var el = /*#__PURE__*/_react["default"].createElement(_mediaDialog["default"], (0, _extends2["default"])({}, rest, {
    uploadSoundSupport: opts.uploadSoundSupport,
    type: type,
    disablePortal: true,
    open: true,
    handleClose: handleClose
  }));

  _reactDom["default"].render(el, newEl);

  document.body.appendChild(newEl);
};

exports.insertDialog = insertDialog;
var types = ['audio', 'video'];

function MediaPlugin(type, opts) {
  var toolbar = {
    icon: type === 'audio' ? /*#__PURE__*/_react["default"].createElement(_VolumeUp["default"], null) : /*#__PURE__*/_react["default"].createElement(_Theaters["default"], null),
    onClick: function onClick(value, onChange) {
      log('[toolbar] onClick');

      var inline = _slate.Inline.create({
        type: type,
        isVoid: true,
        data: {
          editing: false,
          ends: undefined,
          height: undefined,
          title: undefined,
          starts: undefined,
          src: undefined,
          url: undefined,
          width: undefined
        }
      });

      var change = value.change().insertInline(inline);
      onChange(change);
      insertDialog({
        type: type,
        opts: opts,
        callback: function callback(val, data) {
          var nodeIsThere = change.value.document.findDescendant(function (d) {
            return d.key === inline.key;
          });

          if (nodeIsThere) {
            if (!val) {
              var c = change.removeNodeByKey(inline.key);
              onChange(c, function () {
                return opts.focus();
              });
            } else {
              var _c = change.setNodeByKey(inline.key, {
                data: data
              });

              onChange(_c, function () {
                return opts.focus('beginning', nodeIsThere);
              });
            }
          } else {
            opts.focus();
          }
        }
      });
    },
    supports: function supports(node) {
      return node.object === 'inline' && node.type === type;
    }
  };
  return {
    name: type,
    toolbar: toolbar,
    deleteNode: function deleteNode(e, node, value, onChange) {
      e.preventDefault();
      var change = value.change().removeNodeByKey(node.key);
      onChange(change);
    },
    renderNode: function renderNode(props) {
      if (props.node.type === type) {
        var node = props.node,
            key = props.key;
        var data = node.data;
        var jsonData = data.toJSON();
        var src = jsonData.src,
            height = jsonData.height,
            width = jsonData.width,
            editing = jsonData.editing,
            tag = jsonData.tag,
            rest = (0, _objectWithoutProperties2["default"])(jsonData, _excluded2);

        var handleEdit = function handleEdit() {
          var change = opts.createChange();
          var c = change.setNodeByKey(key, {
            data: _objectSpread(_objectSpread({}, jsonData), {}, {
              editing: true
            })
          });
          opts.onChange(c, function () {
            insertDialog(_objectSpread(_objectSpread({}, jsonData), {}, {
              edit: true,
              type: type,
              opts: opts,
              callback: function callback(val, data) {
                var key = node.key;
                var nodeIsThere = change.value.document.findDescendant(function (d) {
                  return d.type === type && d.data.get('editing');
                });

                if (nodeIsThere && val) {
                  var _c2 = change.setNodeByKey(key, {
                    data: data,
                    editing: false
                  });

                  opts.onChange(_c2, function () {
                    return opts.focus('beginning', nodeIsThere);
                  });
                } else {
                  opts.focus();
                }
              }
            }));
          });
        };

        var handleDelete = function handleDelete() {
          var change = opts.createChange();
          var c = change.removeNodeByKey(node.key);
          opts.onChange(c);
        };

        var style = {};

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

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

        if (tag === 'audio') {
          return /*#__PURE__*/_react["default"].createElement(_mediaWrapper["default"], (0, _extends2["default"])({
            editor: true,
            "data-type": type,
            width: style.width
          }, rest), /*#__PURE__*/_react["default"].createElement("audio", {
            controls: "controls"
          }, /*#__PURE__*/_react["default"].createElement("source", {
            type: "audio/mp3",
            src: src
          })), /*#__PURE__*/_react["default"].createElement(_mediaToolbar["default"], {
            hideEdit: true,
            onRemove: handleDelete
          }));
        }

        return /*#__PURE__*/_react["default"].createElement(_mediaWrapper["default"], (0, _extends2["default"])({
          editor: true,
          "data-type": type,
          width: style.width
        }, rest), /*#__PURE__*/_react["default"].createElement("iframe", (0, _extends2["default"])({
          frameBorder: "0",
          allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",
          allowFullScreen: true,
          src: src,
          editing: editing ? 1 : 0
        }, rest, style)), /*#__PURE__*/_react["default"].createElement(_mediaToolbar["default"], {
          onEdit: handleEdit,
          onRemove: handleDelete
        }));
      }
    },
    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;
        }

        var isMedia = types.indexOf(d.type) >= 0;

        if (isMedia) {
          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 type = el.dataset && el.dataset.type;
    var tag = 'iframe';
    var src;
    var typeIndex = types.indexOf(type);

    if (typeIndex < 0) {
      if (el instanceof Element && el.tagName.toLowerCase() === 'audio') {
        var _el$firstChild;

        type = 'audio';
        tag = 'audio';
        src = (_el$firstChild = el.firstChild) === null || _el$firstChild === void 0 ? void 0 : _el$firstChild.getAttribute('src');
      } else {
        return;
      }
    }

    var _ref = el.dataset || {},
        ends = _ref.ends,
        starts = _ref.starts,
        title = _ref.title,
        editing = _ref.editing,
        url = _ref.url;

    log('deserialize: ', name);
    var width = parseInt(el.getAttribute('width'), 10) || null;
    var height = parseInt(el.getAttribute('height'), 10) || null;
    var out = {
      object: 'inline',
      type: type,
      isVoid: true,
      data: {
        tag: tag,
        src: src || el.getAttribute('src'),
        editing: editing,
        ends: ends,
        height: height,
        starts: starts,
        title: title,
        width: width,
        url: url
      }
    };
    log('return object: ', out);
    return out;
  },
  serialize: function serialize(object
  /*, children*/
  ) {
    var typeIndex = types.indexOf(object.type);
    if (typeIndex < 0) return;
    var type = types[typeIndex];
    var data = object.data;
    var editing = data.get('editing');
    var tag = data.get('tag');
    var ends = data.get('ends');
    var src = data.get('src');
    var starts = data.get('starts');
    var title = data.get('title');
    var width = data.get('width');
    var height = data.get('height');
    var url = data.get('url');
    var style = {};

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

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

    var divProps = {
      'data-editing': editing,
      'data-ends': ends,
      'data-starts': starts,
      'data-title': title,
      'data-url': url
    };

    var props = _objectSpread(_objectSpread({}, style), {}, {
      src: src
    });

    if (tag === 'audio') {
      return /*#__PURE__*/_react["default"].createElement("audio", {
        controls: "controls"
      }, /*#__PURE__*/_react["default"].createElement("source", {
        type: "audio/mp3",
        src: src
      }));
    }

    return /*#__PURE__*/_react["default"].createElement("iframe", (0, _extends2["default"])({
      "data-type": type,
      src: src
    }, divProps, {
      frameBorder: "0",
      allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",
      allowFullScreen: true
    }, props));
  }
};
exports.serialization = serialization;
//# sourceMappingURL=index.js.map