"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.Text = 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 _builder = require("./builder");

var _yellow = _interopRequireDefault(require("@material-ui/core/colors/yellow"));

var _green = _interopRequireDefault(require("@material-ui/core/colors/green"));

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

var _classnames = _interopRequireDefault(require("classnames"));

var _selectionUtils = require("./selection-utils");

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:text-select:token-text');
var Text = (0, _styles.withStyles)(function () {
  return {
    predefined: {
      cursor: 'pointer',
      backgroundColor: _yellow["default"][100],
      border: "dashed 0px ".concat(_yellow["default"][700]),
      // we need this for nested tokenized elements like paragraphs, where p is inside span
      '& *': {
        cursor: 'pointer',
        backgroundColor: _yellow["default"][100],
        border: "dashed 0px ".concat(_yellow["default"][700])
      }
    },
    correct: {
      backgroundColor: _green["default"][500],
      '& *': {
        backgroundColor: _green["default"][500]
      }
    }
  };
})(function (_ref) {
  var text = _ref.text,
      predefined = _ref.predefined,
      classes = _ref.classes,
      onClick = _ref.onClick,
      correct = _ref.correct;
  var formattedText = (text || '').replace(/\n/g, '<br>');

  if (predefined) {
    var className = (0, _classnames["default"])(classes.predefined, correct && classes.correct);
    return /*#__PURE__*/_react["default"].createElement("span", {
      onClick: onClick,
      className: className,
      dangerouslySetInnerHTML: {
        __html: formattedText
      }
    });
  } else {
    return /*#__PURE__*/_react["default"].createElement("span", {
      dangerouslySetInnerHTML: {
        __html: formattedText
      }
    });
  }
});
exports.Text = Text;
var notAllowedCharacters = ['\n', ' ', '\t'];

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

  var _super = _createSuper(TokenText);

  function TokenText() {
    var _this;

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

    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), "onClick", function (event) {
      var _this$props = _this.props,
          onSelectToken = _this$props.onSelectToken,
          text = _this$props.text,
          tokens = _this$props.tokens;
      event.preventDefault();

      if (typeof window === 'undefined') {
        return;
      }

      var selection = window.getSelection();
      var textSelected = selection.toString();

      if (textSelected.length > 0 && notAllowedCharacters.indexOf(textSelected) < 0) {
        if (_this.root) {
          var offset = (0, _selectionUtils.getCaretCharacterOffsetWithin)(_this.root);
          /*
           Since we implemented new line functionality (\n) using <br /> dom elements
           and window.getSelection is not taking that into consideration, the offset might
           be off by a few characters.
            To combat that, we check if the selected text is right at the beginning of the offset.
            If it's not, we add the additional offset in order for that to be accurate
           */

          var newLineOffset = text.slice(offset).indexOf(textSelected);
          offset += newLineOffset;

          if (offset !== undefined) {
            var endIndex = offset + textSelected.length;

            if (endIndex <= text.length) {
              var i = (0, _builder.intersection)({
                start: offset,
                end: endIndex
              }, tokens);

              if (i.hasOverlap) {
                log('hasOverlap  - do nothing');
                (0, _selectionUtils.clearSelection)();
              } else {
                var tokensToRemove = i.surroundedTokens;
                var token = {
                  text: textSelected,
                  start: offset,
                  end: endIndex
                };
                onSelectToken(token, tokensToRemove);
                (0, _selectionUtils.clearSelection)();
              }
            }
          }
        }
      }
    });
    return _this;
  }

  (0, _createClass2["default"])(TokenText, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props2 = this.props,
          text = _this$props2.text,
          tokens = _this$props2.tokens,
          className = _this$props2.className,
          onTokenClick = _this$props2.onTokenClick;
      var normalized = (0, _builder.normalize)(text, tokens);
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: className,
        ref: function ref(r) {
          return _this2.root = r;
        },
        onClick: this.onClick
      }, normalized.map(function (t, index) {
        return /*#__PURE__*/_react["default"].createElement(Text, (0, _extends2["default"])({
          key: index
        }, t, {
          onClick: function onClick() {
            return onTokenClick(t);
          }
        }));
      }));
    }
  }]);
  return TokenText;
}(_react["default"].Component);

exports["default"] = TokenText;
(0, _defineProperty2["default"])(TokenText, "propTypes", {
  text: _propTypes["default"].string.isRequired,
  tokens: _propTypes["default"].array.isRequired,
  onTokenClick: _propTypes["default"].func.isRequired,
  onSelectToken: _propTypes["default"].func.isRequired,
  className: _propTypes["default"].string
});
//# sourceMappingURL=token-text.js.map