"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "ALL_PLUGINS", {
  enumerable: true,
  get: function get() {
    return _editor.ALL_PLUGINS;
  }
});
Object.defineProperty(exports, "DEFAULT_PLUGINS", {
  enumerable: true,
  get: function get() {
    return _editor.DEFAULT_PLUGINS;
  }
});
Object.defineProperty(exports, "Editor", {
  enumerable: true,
  get: function get() {
    return _editor["default"];
  }
});
exports["default"] = void 0;
Object.defineProperty(exports, "htmlToValue", {
  enumerable: true,
  get: function get() {
    return _serialization.htmlToValue;
  }
});
Object.defineProperty(exports, "valueToHtml", {
  enumerable: true,
  get: function get() {
    return _serialization.valueToHtml;
  }
});

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 _react = _interopRequireDefault(require("react"));

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

var _editor = _interopRequireWildcard(require("./editor"));

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

var _parseHtml = require("./parse-html");

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

var _slate = require("slate");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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

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');
/**
 * Export lower level Editor and serialization functions.
 */

/**
 * Wrapper around the editor that exposes a `markup` and `onChange(markup:string)` api.
 * Because of the mismatch between the markup and the `Value` we need to convert the incoming markup to a value and
 * compare it. TODO: This is an interim fix, we'll need to strip back `Editor` and look how best to maintain the
 * `markup` api whilst avoiding the serialization mismatch. We should be making better use of schemas w/ normalize.
 */
var EditableHtml = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(EditableHtml, _React$Component);

  var _super = _createSuper(EditableHtml);

  function EditableHtml(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, EditableHtml);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runSerializationOnMarkup", function () {
      if (!_this.props.markup) {
        return;
      }

      var v = (0, _serialization.htmlToValue)((0, _serialization.reduceMultipleBrs)(_this.props.markup));

      _this.setState({
        value: v
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChange", function (value, done) {
      var html = (0, _serialization.valueToHtml)(value);
      var htmlParsed = (0, _parseHtml.parseDegrees)(html);

      if (html !== _this.props.markup && _this.props.onChange) {
        _this.props.onChange(htmlParsed);
      }

      if (done && _this.props.onDone) {
        _this.props.onDone(htmlParsed);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "focus", function (position, node) {
      var select = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      if (_this.editorRef) {
        _this.editorRef.change(function (c) {
          var lastText = node ? c.value.document.getNextText(node.key) : c.value.document.getLastText();
          var editorDOM = document.querySelector("[data-key=\"".concat(_this.editorRef.value.document.key, "\"]"));

          if (editorDOM !== document.activeElement) {
            document.activeElement.blur();
          }

          c.focus();

          if (position === 'end' && lastText) {
            var _lastText$text, _lastText$text2;

            c.moveFocusTo(lastText.key, (_lastText$text = lastText.text) === null || _lastText$text === void 0 ? void 0 : _lastText$text.length).moveAnchorTo(lastText.key, (_lastText$text2 = lastText.text) === null || _lastText$text2 === void 0 ? void 0 : _lastText$text2.length);

            if (select) {
              var _lastText$text3;

              var range = _slate.Range.fromJSON({
                anchorKey: lastText.key,
                anchorOffset: 0,
                focusKey: lastText.key,
                focusOffset: (_lastText$text3 = lastText.text) === null || _lastText$text3 === void 0 ? void 0 : _lastText$text3.length,
                isFocused: true,
                isBackward: false
              });

              c.select(range);
            }
          }

          if (position === 'beginning' && lastText) {
            c.moveFocusTo(lastText.key, 0).moveAnchorTo(lastText.key, 0);
          }

          editorDOM.focus();
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "finishEditing", function () {
      if (_this.editorRef) {
        _this.editorRef.props.onEditingDone();
      }
    });

    if (props.extraCSSRules) {
      Object.assign(_serialization.extraCSSRulesOpts, _this.props.extraCSSRules);
    }

    var _v = (0, _serialization.htmlToValue)(props.markup);

    _this.state = {
      value: _v
    };
    return _this;
  } // eslint-disable-next-line react/no-deprecated


  (0, _createClass2["default"])(EditableHtml, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(props) {
      if (!props.allowValidation && props.markup === this.props.markup) {
        return;
      }

      var v = (0, _serialization.htmlToValue)(props.markup);
      var current = (0, _serialization.htmlToValue)(this.props.markup);

      if (v.equals && !v.equals(current)) {
        this.setState({
          value: v
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var value = this.state.value;
      var _this$props = this.props,
          toolbarOpts = _this$props.toolbarOpts,
          error = _this$props.error;

      if (toolbarOpts) {
        toolbarOpts.error = error;
      }

      var props = _objectSpread(_objectSpread({}, this.props), {}, {
        markup: null,
        value: value,
        onChange: this.onChange,
        focus: this.focus,
        runSerializationOnMarkup: this.runSerializationOnMarkup
      });

      return /*#__PURE__*/_react["default"].createElement(_editor["default"], (0, _extends2["default"])({
        onRef: function onRef(ref) {
          if (ref) {
            _this2.rootRef = ref;
          }
        },
        editorRef: function editorRef(ref) {
          return ref && (_this2.editorRef = ref);
        }
      }, props));
    }
  }]);
  return EditableHtml;
}(_react["default"].Component);

exports["default"] = EditableHtml;
(0, _defineProperty2["default"])(EditableHtml, "propTypes", {
  error: _propTypes["default"].any,
  onChange: _propTypes["default"].func.isRequired,
  onDone: _propTypes["default"].func,
  markup: _propTypes["default"].string.isRequired,
  allowValidation: _propTypes["default"].bool,
  toolbarOpts: _propTypes["default"].object,
  extraCSSRules: _propTypes["default"].shape({
    names: _propTypes["default"].arrayOf(_propTypes["default"].string),
    rules: _propTypes["default"].string
  })
});
(0, _defineProperty2["default"])(EditableHtml, "defaultProps", {
  onDone: function onDone() {},
  allowValidation: false
});
//# sourceMappingURL=index.js.map