"use strict";

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

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

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

var _icons = _interopRequireDefault(require("./icons"));

var _serialization = require("./../../serialization");

var toggleToRichText = function toggleToRichText(value, onChange, dismiss) {
  var plainText = value.document.text;
  var slateValue = dismiss ? value : (0, _serialization.htmlToValue)(plainText);
  var change = value.change().selectAll()["delete"]().insertFragment(slateValue.document);
  onChange(change);
};

function HtmlPlugin(opts) {
  var isHtmlMode = opts.isHtmlMode,
      isEditedInHtmlMode = opts.isEditedInHtmlMode,
      toggleHtmlMode = opts.toggleHtmlMode,
      handleAlertDialog = opts.handleAlertDialog,
      currentValue = opts.currentValue;

  var handleHtmlModeOn = function handleHtmlModeOn(value, onChange) {
    var dialogProps = {
      title: 'Warning',
      text: 'Returning to rich text mode without saving will cause edits to be lost.',
      onConfirmText: 'Dismiss changes',
      onCloseText: 'Continue Editing',
      onConfirm: function onConfirm() {
        handleAlertDialog(false);
        toggleToRichText(currentValue, onChange, true);
        toggleHtmlMode();
      },
      onClose: function onClose() {
        handleAlertDialog(false);
      }
    };
    handleAlertDialog(true, dialogProps);
  };

  var handleHtmlModeOff = function handleHtmlModeOff(value, onChange) {
    var change = value.change().selectAll()["delete"]().insertText((0, _serialization.valueToHtml)(value));
    onChange(change);
  };

  return {
    name: 'html',
    toolbar: {
      icon: /*#__PURE__*/_react["default"].createElement(_icons["default"], {
        isHtmlMode: isHtmlMode
      }),
      ariaLabel: 'Html editor',
      buttonStyles: {
        margin: '0 20px 0 auto'
      },
      type: 'html',
      onClick: function onClick(value, onChange) {
        if (isHtmlMode) {
          if (isEditedInHtmlMode) {
            handleHtmlModeOn(value, onChange);
          } else {
            toggleToRichText(value, onChange);
            toggleHtmlMode();
          }
        } else {
          handleHtmlModeOff(value, onChange);
          toggleHtmlMode();
        }
      }
    }
  };
}
//# sourceMappingURL=index.js.map