'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _offsetKey = require('../utils/offset-key');

var _offsetKey2 = _interopRequireDefault(_offsetKey);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Leaf.
 */

var Leaf = function (_React$Component) {
  _inherits(Leaf, _React$Component);

  function Leaf() {
    _classCallCheck(this, Leaf);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(Leaf).apply(this, arguments));
  }

  _createClass(Leaf, [{
    key: 'shouldComponentUpdate',


    /**
     * Should component update?
     *
     * @param {Object} props
     * @return {Boolean} shouldUpdate
     */

    value: function shouldComponentUpdate(props) {
      var start = props.start;
      var end = props.end;
      var node = props.node;
      var state = props.state;
      var selection = state.selection;


      var should = selection.hasEdgeBetween(node, start, end) || props.start != this.props.start || props.end != this.props.end || props.text != this.props.text || props.marks != this.props.marks;

      return should;
    }

    /**
     * Properties.
     */

  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.updateSelection();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.updateSelection();
    }
  }, {
    key: 'updateSelection',
    value: function updateSelection() {
      var state = this.props.state;
      var selection = state.selection;

      // If the selection is not focused we have nothing to do.

      if (!selection.isFocused) return;

      var anchorOffset = selection.anchorOffset;
      var focusOffset = selection.focusOffset;
      var _props = this.props;
      var node = _props.node;
      var start = _props.start;
      var end = _props.end;

      // If neither matches, the selection doesn't start or end here, so exit.

      var hasStart = selection.hasStartBetween(node, start, end);
      var hasEnd = selection.hasEndBetween(node, start, end);
      if (!hasStart && !hasEnd) return;

      // We have a selection to render, so prepare a few things...
      var native = window.getSelection();
      var el = _reactDom2.default.findDOMNode(this).firstChild;

      // If both the start and end are here, set the selection all at once.
      if (hasStart && hasEnd) {
        native.removeAllRanges();
        var range = document.createRange();
        range.setStart(el, anchorOffset - start);
        native.addRange(range);
        native.extend(el, focusOffset - start);
        return;
      }

      // If the selection is forward, we can set things in sequence. In
      // the first leaf to render, reset the selection and set the new start. And
      // then in the second leaf to render, extend to the new end.
      if (selection.isForward) {
        if (hasStart) {
          native.removeAllRanges();
          var _range = document.createRange();
          _range.setStart(el, anchorOffset - start);
          native.addRange(_range);
        } else if (hasEnd) {
          native.extend(el, focusOffset - start);
        }
      }

      // Otherwise, if the selection is backward, we need to hack the order a bit.
      // In the first leaf to render, set a phony start anchor to store the true
      // end position. And then in the second leaf to render, set the start and
      // extend the end to the stored value.
      else {
          if (hasEnd) {
            native.removeAllRanges();
            var _range2 = document.createRange();
            _range2.setStart(el, focusOffset - start);
            native.addRange(_range2);
          } else if (hasStart) {
            var endNode = native.focusNode;
            var endOffset = native.focusOffset;
            native.removeAllRanges();
            var _range3 = document.createRange();
            _range3.setStart(el, anchorOffset - start);
            native.addRange(_range3);
            native.extend(endNode, endOffset);
          }
        }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props;
      var node = _props2.node;
      var text = _props2.text;
      var marks = _props2.marks;
      var start = _props2.start;
      var end = _props2.end;
      var renderMark = _props2.renderMark;

      var offsetKey = _offsetKey2.default.stringify({
        key: node.key,
        start: start,
        end: end
      });

      var style = marks.reduce(function (memo, mark) {
        return _extends({}, memo, renderMark(mark));
      }, {});

      return _react2.default.createElement(
        'span',
        {
          'data-offset-key': offsetKey,
          style: style
        },
        text || _react2.default.createElement('br', null)
      );
    }
  }]);

  return Leaf;
}(_react2.default.Component);

/**
 * Export.
 */

Leaf.propTypes = {
  end: _react2.default.PropTypes.number.isRequired,
  marks: _react2.default.PropTypes.object.isRequired,
  node: _react2.default.PropTypes.object.isRequired,
  renderMark: _react2.default.PropTypes.func.isRequired,
  start: _react2.default.PropTypes.number.isRequired,
  state: _react2.default.PropTypes.object.isRequired,
  text: _react2.default.PropTypes.string.isRequired
};
exports.default = Leaf;