"use strict";

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

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

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

var _lodash = require("lodash");

require("./index.less");

var _Iconfont = require("../../../common/Iconfont");

var _decorator = require("../../../decorator");

var _coreUtil = require("../../../utils/coreUtil");

var _mobx = require("../../../mobx");

var _commonUtil = require("../../../utils/commonUtil");

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

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

var __extends = void 0 && (void 0).__extends || function () {
  var _extendStatics = function extendStatics(d, b) {
    _extendStatics = Object.setPrototypeOf || {
      __proto__: []
    } instanceof Array && function (d, b) {
      d.__proto__ = b;
    } || function (d, b) {
      for (var p in b) {
        if (b.hasOwnProperty(p)) d[p] = b[p];
      }
    };

    return _extendStatics(d, b);
  };

  return function (d, b) {
    _extendStatics(d, b);

    function __() {
      this.constructor = d;
    }

    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
}();

var __assign = void 0 && (void 0).__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

var __decorate = void 0 && (void 0).__decorate || function (decorators, target, key, desc) {
  var c = arguments.length,
      r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
      d;
  if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
    if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  }
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};

var __spreadArrays = void 0 && (void 0).__spreadArrays || function () {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
    s += arguments[i].length;
  }

  for (var r = Array(s), k = 0, i = 0; i < il; i++) {
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
      r[k] = a[j];
    }
  }

  return r;
};

/** 从父级数组中 分离出 片段数组 */
var calcSplitRange = function calcSplitRange(parentRange, splitRange) {
  if (parentRange[0] == splitRange[0]) {
    if (parentRange[1] == splitRange[1]) {
      return parentRange;
    } else {
      return [[parentRange[0], splitRange[1]], [splitRange[1], parentRange[1]]];
    }
  }

  if (parentRange[1] == splitRange[1]) {
    return [[parentRange[0], splitRange[0]], [splitRange[0], parentRange[1]]];
  }

  return [[parentRange[0], splitRange[0]], [splitRange[0], splitRange[1]], [splitRange[1], parentRange[1]]];
};
/** 驱动配置面板渲染 */


var triggerTextConfigRender = function triggerTextConfigRender() {
  window.document.dispatchEvent(new Event('text-render', {
    bubbles: false
  }));
};
/** 初始化监听事件 */


var initSelectionEvent = function initSelectionEvent() {
  if (!window.document.onselectionchange) {
    window.document.onselectionchange = (0, _lodash.debounce)(function (e) {
      var _a;

      var _b, _c, _d, _e;
      /** 找到选中的text区域 并且注册过事件 */


      var findSelectionTarget = window._selectionTarget.find(function (_a) {
        var target = _a.target;
        return target == e.target.activeElement;
      });
      /** 所有选中状态清楚 */


      var clearSelection = function clearSelection() {
        _mobx.store.setState({
          textSelection: null
        });

        triggerTextConfigRender();
      };

      if (findSelectionTarget) {
        var range = window.getSelection().getRangeAt(0);
        var startOffset = range.startOffset,
            endOffset = range.endOffset,
            startContainer_1 = range.startContainer,
            endContainer = range.endContainer;
        /** 起始点=终点 取消 */

        if (startOffset == endOffset) {
          clearSelection();
          return;
        }
        /** 如果全部选中 取消 */


        if (startOffset == 0 && endOffset == findSelectionTarget.data.text.length) {
          clearSelection();
          return;
        }
        /** 判断起始点和结束点是否相同  */


        if (startContainer_1 == endContainer) {
          /** 如果还没有选中区域 */
          if (findSelectionTarget.data.specialContent.length == 0) {
            var nowRange_1 = [startOffset, endOffset].sort(function (a, b) {
              return a - b;
            });
            var rangeList = calcSplitRange([0, findSelectionTarget.data.text.length], nowRange_1);
            findSelectionTarget.data.specialContent = rangeList.map(function (range) {
              return {
                range: range,
                content: {}
              };
            });
            var findSelectionRange = (_b = findSelectionTarget.data.specialContent) === null || _b === void 0 ? void 0 : _b.find(function (c) {
              return JSON.stringify(c.range) == JSON.stringify(nowRange_1);
            });

            _mobx.store.setState({
              textSelection: findSelectionRange.content
            });
          } else {
            /** 如果已有选中区域 */
            var nowRange_2 = [startOffset, endOffset].sort(function (a, b) {
              return a - b;
            });
            var selectionRangeJSON_1 = Object.keys(findSelectionTarget.selectionRefMap).find(function (rangeTarget) {
              return findSelectionTarget.selectionRefMap[rangeTarget] == startContainer_1.parentNode;
            });
            var findSelectionRangeTarget_1 = (_c = findSelectionTarget.data.specialContent) === null || _c === void 0 ? void 0 : _c.find(function (c) {
              return JSON.stringify(c.range) == selectionRangeJSON_1;
            });
            /** 选中没配置过的区域 可以进行拆分 */

            if ((0, _lodash.isEmpty)(findSelectionRangeTarget_1.content)) {
              /** 计算偏移值 */
              nowRange_2[0] += findSelectionRangeTarget_1.range[0];
              nowRange_2[1] += findSelectionRangeTarget_1.range[0];
              /** 补充新的选中区域 */

              if (JSON.stringify(findSelectionRangeTarget_1.range) != JSON.stringify(nowRange_2)) {
                var rangeList = calcSplitRange(findSelectionRangeTarget_1.range, nowRange_2);
                var nowContentIndex = (_d = findSelectionTarget.data.specialContent) === null || _d === void 0 ? void 0 : _d.findIndex(function (c) {
                  return c == findSelectionRangeTarget_1;
                });

                (_a = findSelectionTarget.data.specialContent).splice.apply(_a, __spreadArrays([nowContentIndex, 1], rangeList.map(function (range) {
                  return {
                    range: range,
                    content: {}
                  };
                })));
              }

              var findSelectionRange = (_e = findSelectionTarget.data.specialContent) === null || _e === void 0 ? void 0 : _e.find(function (c) {
                return JSON.stringify(c.range) == JSON.stringify(nowRange_2);
              });

              _mobx.store.setState({
                textSelection: findSelectionRange.content
              });
            } else {
              /** 选中已经配置过的区域 不能拆分 */
              _mobx.store.setState({
                textSelection: findSelectionRangeTarget_1.content
              });
            }
          }
        } else {
          _mobx.store.setState({
            textSelection: null
          });
        }

        findSelectionTarget.refresh();
      }

      triggerTextConfigRender();
    }, 500);
  }
};
/** 添加选择区域监听目标 */


var appendSelectionTarget = function appendSelectionTarget(data) {
  if (!window._selectionTarget) {
    window._selectionTarget = [__assign({}, data)];
  } else {
    window._selectionTarget.push(__assign({}, data));
  }
};
/** 删除监听目标 */


var deleteSelectionTarget = function deleteSelectionTarget(deleteTarget) {
  window._selectionTarget = window._selectionTarget.filter(function (_a) {
    var target = _a.target;
    return target != deleteTarget;
  });
};

var Text =
/** @class */
function (_super) {
  __extends(Text, _super);

  function Text() {
    var _this = _super !== null && _super.apply(this, arguments) || this;

    _this.state = {};
    /** 分割区域dom映射 */

    _this.selectionRefMap = {};
    _this.textRef = /*#__PURE__*/_react["default"].createRef();
    /** 备份历史数据 比对不一致时渲染 */

    _this.preData = '';
    _this.preTextSelection = null;

    _this.contentStyle = function (content) {
      return {
        fontSize: content.fontSize,
        fontFamily: content.fontFamily,
        fontWeight: content.fontWeight,
        fontStyle: content.fontStyle,
        color: content.color,
        backgroundColor: content.backgroundColor,
        textAlign: content.textAlign,
        width: window.magicDesign.device == 'mobile' ? '100%' : content.width || 'fit-content'
      };
    };
    /** 创建关闭图标按钮 */


    _this.createHoverClose = function (node, onCloseClick) {
      if (onCloseClick === void 0) {
        onCloseClick = function onCloseClick() {};
      }

      node.className = 'select-container';
      var closeNode = document.createElement('span');
      closeNode.className = 'close-wrap';
      closeNode.contentEditable = 'false';
      var iconNode = document.createElement('span');
      iconNode.contentEditable = 'false';
      iconNode.className = (0, _Iconfont.convertIconClass)('icon-close-circle');
      iconNode.onclick = onCloseClick;
      closeNode.appendChild(iconNode);
      node.appendChild(closeNode);
    };

    _this.renderText = function (data) {
      if (!_this.textRef.current) return;

      _this.textRef.current.blur();
      /** 保留历史数据 */


      _this.preData = JSON.stringify(data);
      _this.preTextSelection = _mobx.store.textSelection;
      /** 渲染html */

      if (data.specialContent.length == 0) {
        _this.textRef.current.innerHTML = data.text;
      } else {
        _this.textRef.current.innerHTML = '';
        data.specialContent.forEach(function (c, index) {
          var _a;

          var node = document.createElement('span');
          node.style = (0, _commonUtil.styleStringify)(_this.contentStyle(c.content));
          node.innerText = (_a = data.text).slice.apply(_a, c.range);
          _this.selectionRefMap[JSON.stringify(c.range)] = node;

          _this.textRef.current.appendChild(node);
          /** 找到当前选中的区域 */


          if (_mobx.store.textSelection == c.content) {
            /** 添加删除按钮 */
            _this.createHoverClose(node, function () {
              /** 第一步去除选中区域 */
              _mobx.store.setState({
                textSelection: null
              });
              /** 清空区间配置 */


              data.specialContent[index].content = {};
              /** 合并区间无配置区间 */

              for (var i = 0; i < data.specialContent.length - 1;) {
                /** 如果本级和下级都是空值 那么合并 */
                if ((0, _lodash.isEmpty)(data.specialContent[i].content) && (0, _lodash.isEmpty)(data.specialContent[i + 1].content)) {
                  data.specialContent[i].range = [data.specialContent[i].range[0], data.specialContent[i + 1].range[1]];
                  data.specialContent.splice(i + 1, 1);
                } else {
                  i += 1;
                }
              }

              triggerTextConfigRender();
            });
          }
        });
      }
      /** 清除无用的node */


      Object.keys(_this.selectionRefMap).forEach(function (key) {
        if (!data.specialContent.find(function (c) {
          return JSON.stringify(c.range) == key;
        })) {
          Reflect.deleteProperty(_this.selectionRefMap, key);
        }
      });
    };

    return _this;
  }

  Text.prototype.componentDidMount = function () {
    var _this = this;

    this.renderText(this.props.data);
    initSelectionEvent();
    appendSelectionTarget({
      target: this.textRef.current,
      data: this.props.data,
      selectionRefMap: this.selectionRefMap,
      refresh: function refresh() {
        _this.renderText(_this.props.data);
      }
    });
  };

  Text.prototype.shouldComponentUpdate = function (nextProps) {
    var should1 = JSON.stringify(nextProps.data) != this.preData;
    var should2 = _mobx.store.textSelection != this.preTextSelection;
    var result = should1 || should2;

    if (result) {
      this.renderText(nextProps.data);
    }

    return result;
  };

  Text.prototype.componentWillUnmount = function () {
    deleteSelectionTarget(this.textRef.current);
  };

  Text.prototype.render = function () {
    var _this = this;

    var _a = this.props,
        data = _a.data,
        className = _a.className,
        readonly = _a.readonly,
        onTextInput = _a.onTextInput;

    var style = __assign(__assign({}, this.contentStyle(data.content)), {
      textDecorationLine: data.underline.open ? 'underline' : 'none',
      textDecorationColor: data.underline.textDecorationColor,
      textDecorationStyle: data.underline.textDecorationStyle
    });

    return /*#__PURE__*/_react["default"].createElement("div", {
      ref: this.textRef,
      className: (0, _classnames["default"])('m-meta-text', className),
      contentEditable: (0, _coreUtil.isDesignMode)() && !readonly,
      onInput: function onInput(e) {
        var text = e.target.textContent;
        data.text = text;
        /** 主动更新历史数据避免render */

        _this.preData = JSON.stringify(__assign(__assign({}, JSON.parse(_this.preData)), {
          text: text
        }));
        /** 通知变更 */

        onTextInput(text);
      },
      onKeyDown: function onKeyDown(e) {
        e.stopPropagation();
      },
      style: style,
      suppressContentEditableWarning: true
    });
  };

  Text.defaultProps = {
    readonly: false,
    onTextInput: function onTextInput() {}
  };
  Text = __decorate([_decorator.metaDecorator], Text);
  return Text;
}(_react["default"].Component);

var _default = Text;
exports["default"] = _default;