"use strict";

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

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

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 _styles = require("@material-ui/core/styles");

var _editableHtml = require("@pie-lib/pie-toolbox/editable-html");

var _markupUtils = require("./markupUtils");

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 findSlateNode = function findSlateNode(key) {
  return window.document.querySelector('[data-key="' + key + '"]');
};

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

  var _super = _createSuper(ECRToolbar);

  function ECRToolbar() {
    var _this;

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

    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), "state", {
      markup: '',
      toolbarStyle: {}
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDone", function (markup) {
      var _this$props = _this.props,
          node = _this$props.node,
          value = _this$props.value,
          onToolbarDone = _this$props.onToolbarDone,
          onChangeResponse = _this$props.onChangeResponse;
      var sanitizedMarkup = (0, _markupUtils.stripHtmlTags)(markup);

      _this.setState({
        markup: sanitizedMarkup
      });

      var updatedData = _objectSpread(_objectSpread({}, node.data.toJSON()), {}, {
        value: sanitizedMarkup
      });

      var change = value.change().setNodeByKey(node.key, {
        data: updatedData
      });
      var nextText = value.document.getNextText(node.key);
      change.moveFocusTo(nextText.key, 0).moveAnchorTo(nextText.key, 0);
      onToolbarDone(change, true);
      onChangeResponse(sanitizedMarkup);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onRespAreaChange", function (respAreaMarkup) {
      _this.setState({
        respAreaMarkup: respAreaMarkup
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onKeyDown", function (event) {
      if (event.key === 'Enter') {
        _this.onAddChoice();

        return false;
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onBlur", function () {
      if (_this.clickedInside) {
        _this.clickedInside = false;
        return;
      }
    });
    return _this;
  }

  (0, _createClass2["default"])(ECRToolbar, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props2 = this.props,
          correctChoice = _this$props2.correctChoice,
          node = _this$props2.node;
      var choice = correctChoice || {};
      var domNode = findSlateNode(node.key);

      if (domNode) {
        //eslint-disable-next-line
        var domNodeRect = domNode.getBoundingClientRect();
        var editor = domNode.closest('[data-slate-editor]');
        var editorRect = editor.getBoundingClientRect();
        var top = domNodeRect.top - editorRect.top;
        var left = domNodeRect.left - editorRect.left;
        this.setState({
          markup: choice.label,
          toolbarStyle: {
            position: 'absolute',
            top: "".concat(top + domNodeRect.height + 20, "px"),
            left: "".concat(left + 20, "px"),
            width: "".concat(domNodeRect.width - 4, "px")
          }
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props3 = this.props,
          classes = _this$props3.classes,
          maxLengthPerChoiceEnabled = _this$props3.maxLengthPerChoiceEnabled,
          pluginProps = _this$props3.pluginProps,
          spellCheck = _this$props3.spellCheck;
      var _this$state = this.state,
          markup = _this$state.markup,
          toolbarStyle = _this$state.toolbarStyle;
      var inputProps = maxLengthPerChoiceEnabled ? {} : {
        maxLength: 25
      };
      return /*#__PURE__*/_react["default"].createElement("div", {
        style: toolbarStyle
      }, /*#__PURE__*/_react["default"].createElement(_editableHtml.EditableHtml, (0, _extends2["default"])({
        autoFocus: true,
        className: classes.markup,
        disableUnderline: true,
        onChange: function onChange(respAreaMarkup) {
          if (_this2.preventDone) {
            return;
          }

          _this2.onRespAreaChange(respAreaMarkup);
        },
        onDone: function onDone(val) {
          if (_this2.preventDone) {
            return;
          }

          _this2.onDone(val);
        },
        onBlur: function onBlur(e) {
          var inInInsertCharacter = e.relatedTarget && e.relatedTarget.closest('.insert-character-dialog');
          _this2.preventDone = inInInsertCharacter;

          _this2.onBlur(e);
        },
        onKeyDown: this.onKeyDown,
        markup: markup || '',
        activePlugins: ['languageCharacters'],
        pluginProps: pluginProps,
        languageCharactersProps: [{
          language: 'spanish'
        }],
        minHeight: '10px',
        maxHeight: '10px',
        spellCheck: spellCheck,
        toolbarOpts: {
          minWidth: 'auto'
        }
      }, inputProps)));
    }
  }]);
  return ECRToolbar;
}(_react["default"].Component);

exports.ECRToolbar = ECRToolbar;
(0, _defineProperty2["default"])(ECRToolbar, "propTypes", {
  correctChoice: _propTypes["default"].object,
  classes: _propTypes["default"].object,
  node: _propTypes["default"].object,
  onDone: _propTypes["default"].func,
  onChangeResponse: _propTypes["default"].func.isRequired,
  onToolbarDone: _propTypes["default"].func.isRequired,
  value: _propTypes["default"].shape({
    change: _propTypes["default"].func.isRequired,
    document: _propTypes["default"].shape({
      getNextText: _propTypes["default"].func.isRequired
    })
  }),
  maxLengthPerChoiceEnabled: _propTypes["default"].bool,
  pluginProps: _propTypes["default"].object,
  spellCheck: _propTypes["default"].bool
});
var StyledECRToolbar = (0, _styles.withStyles)(function (theme) {
  return {
    markup: {
      backgroundColor: theme.palette.common.white,
      outline: 'none',
      lineHeight: '10px'
    }
  };
})(ECRToolbar);
var _default = StyledECRToolbar;
exports["default"] = _default;
//# sourceMappingURL=ecr-toolbar.js.map