"use strict";

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

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

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 _propTypes = _interopRequireDefault(require("prop-types"));

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

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

var _mathquill = _interopRequireDefault(require("@pie-framework/mathquill"));

var _index = require("../index");

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

if (typeof window !== 'undefined') {
  MQ = _mathquill["default"].getInterface(2);
}

var log = (0, _debug["default"])('pie-lib:math-input:mq:static');
var REGEX = /\\MathQuillMathField\[r\d*\]\{(.*?)\}/g;
var WHITESPACE_REGEX = / /g;

function stripSpaces() {
  var string = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return string.replace(WHITESPACE_REGEX, '');
}
/**
 * Wrapper for MathQuill MQ.MathField.
 */


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

  var _super = _createSuper(Static);

  function Static() {
    var _this;

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

    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), "onFocus", function (e) {
      try {
        var rootBlock = e.target.parentElement.nextSibling;
        var id = parseInt(rootBlock.getAttribute('mathquill-block-id'), 10);

        if (!id) {
          rootBlock = rootBlock.parentElement;
          id = parseInt(rootBlock.getAttribute('mathquill-block-id'), 10);
        }

        var innerField = _this.mathField.innerFields.find(function (f) {
          return f.id === id;
        });

        if (innerField) {
          var name = _this.props.getFieldName(innerField, _this.mathField.innerFields);

          if (_this.props.setInput) {
            _this.props.setInput(innerField);
          }

          _this.props.onSubFieldFocus(name, innerField);
        }
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error('error finding root block', err.message);
      }
    });
    return _this;
  }

  (0, _createClass2["default"])(Static, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.update();
      (0, _index.updateSpans)();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.update();
      (0, _index.updateSpans)();
    }
  }, {
    key: "onInputEdit",
    value: function onInputEdit(field) {
      if (!this.mathField) {
        return;
      }

      var name = this.props.getFieldName(field, this.mathField.innerFields);

      if (this.props.onSubFieldChange) {
        // eslint-disable-next-line no-useless-escape
        var regexMatch = field.latex().match(/[0-9]\\ \\frac\{[^\{]*\}\{ \}/);

        if (this.input && regexMatch && regexMatch !== null && regexMatch !== void 0 && regexMatch.length) {
          try {
            field.__controller.cursor.insLeftOf(field.__controller.cursor.parent[-1].parent);

            field.el().dispatchEvent(new KeyboardEvent('keydown', {
              keyCode: 8
            }));
          } catch (e) {
            // eslint-disable-next-line no-console
            console.error(e.toString());
          }
        } else {
          this.props.onSubFieldChange(name, field.latex());
        }
      }
    }
  }, {
    key: "update",
    value: function update() {
      if (!MQ) {
        throw new Error('MQ is not defined - but component has mounted?');
      } // this.input.innerHTML = this.props.latex;


      if (!this.mathField) {
        this.mathField = MQ.StaticMath(this.input, {
          handlers: {
            edit: this.onInputEdit.bind(this)
          }
        });
      }

      try {
        this.mathField.parseLatex(this.props.latex);
        this.mathField.latex(this.props.latex);
      } catch (e) {
        // default latex if received has errors
        this.mathField.latex('\\MathQuillMathField[r1]{}');
      }
    }
  }, {
    key: "blur",
    value: function blur() {
      log('blur mathfield');
      this.mathField.blur();
    }
  }, {
    key: "focus",
    value: function focus() {
      log('focus mathfield...');
      this.mathField.focus();
    }
  }, {
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(nextProps) {
      try {
        var parsedLatex = this.mathField.parseLatex(nextProps.latex);
        var stripped = stripSpaces(parsedLatex);
        var newFieldCount = (nextProps.latex.match(REGEX) || []).length;
        var out = stripped !== stripSpaces(this.mathField.latex().trim()) || newFieldCount !== Object.keys(this.mathField.innerFields).length / 2;
        log('[shouldComponentUpdate] ', out);
        return out;
      } catch (e) {
        // eslint-disable-next-line no-console
        console.warn('Error parsing latex:', e.message, 'skip update'); // eslint-disable-next-line no-console

        console.warn(e);
        return false;
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          onBlur = _this$props.onBlur,
          className = _this$props.className;
      return /*#__PURE__*/_react["default"].createElement("span", {
        className: className,
        onFocus: this.onFocus,
        onBlur: onBlur,
        ref: function ref(r) {
          return _this2.input = r;
        }
      });
    }
  }]);
  return Static;
}(_react["default"].Component);

exports["default"] = Static;
(0, _defineProperty2["default"])(Static, "propTypes", {
  latex: _propTypes["default"].string.isRequired,
  onFocus: _propTypes["default"].func,
  onBlur: _propTypes["default"].func,
  className: _propTypes["default"].string,
  getFieldName: _propTypes["default"].func,
  onSubFieldChange: _propTypes["default"].func,
  onSubFieldFocus: _propTypes["default"].func,
  setInput: _propTypes["default"].func
});
(0, _defineProperty2["default"])(Static, "defaultProps", {
  getFieldName: function getFieldName() {}
});
//# sourceMappingURL=static.js.map