"use strict";

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); }

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

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

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

var _popup = _interopRequireDefault(require("../../../../popup"));

require("./index.css");

var _consts = require("./consts");

var _commond = require("./commond");

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

var _events = require("../../../consts/events");

var _getLocale = require("../../../../../utils/getLocale");

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var preCls = 'tita-rich-editor-color-selector';

function ColorSelector(_ref) {
  var editor = _ref.editor,
      config = _ref.config,
      color = _ref.color,
      background = _ref.background,
      onClickItem = _ref.onClickItem;
  var fontColors = (0, _react.useMemo)(function () {
    var colors = [];

    var _loop = function _loop(key) {
      if (key == 'default') return "continue";
      var c = _consts.FontColor[key];
      var cls = (0, _classnames["default"])("".concat(preCls, "__item"), config.icon, _defineProperty({}, "".concat(preCls, "__item--active"), color == c));
      colors.push( /*#__PURE__*/_react["default"].createElement("div", {
        key: c,
        className: cls,
        style: {
          color: c
        },
        onClick: function onClick() {
          onClickItem(editor.state.schema.marks[_index2.FONT_COLOR_SCHEMA_NAME], c);
        }
      }));
    };

    for (var key in _consts.FontColor) {
      var _ret = _loop(key);

      if (_ret === "continue") continue;
    }

    return colors;
  }, [color]);
  var backgroundColors = (0, _react.useMemo)(function () {
    var colors = [];

    var _loop2 = function _loop2(key) {
      if (key == 'default') return "continue";
      var color = _consts.BackgroundColor[key];
      var cls = (0, _classnames["default"])("".concat(preCls, "__item"), config.icon, _defineProperty({}, "".concat(preCls, "__item--active"), background == color));
      colors.push( /*#__PURE__*/_react["default"].createElement("div", {
        key: color,
        className: cls,
        style: {
          backgroundColor: color
        },
        onClick: function onClick(e) {
          e.stopPropagation();
          onClickItem(editor.state.schema.marks[_index2.BACKGROUND_COLOR_SCHEMA_NAME], color);
        }
      }));
    };

    for (var key in _consts.BackgroundColor) {
      var _ret2 = _loop2(key);

      if (_ret2 === "continue") continue;
    }

    return colors;
  }, [background]);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls,
    onClick: function onClick(e) {
      return e.stopPropagation();
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__title'
  }, (0, _getLocale.getLocale)('Tasks_Tab_MyS_Textcolor')), /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__color-box',
    style: {
      marginBottom: 10
    }
  }, fontColors), /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__title'
  }, (0, _getLocale.getLocale)('Rtx_Backgroundcolors')), /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__color-box'
  }, backgroundColors));
}

function ColorSelectorPop(_ref2) {
  var editor = _ref2.editor,
      config = _ref2.config;

  var _useState = (0, _react.useState)(),
      _useState2 = _slicedToArray(_useState, 2),
      activeColor = _useState2[0],
      setActiveColor = _useState2[1];

  var _useState3 = (0, _react.useState)(),
      _useState4 = _slicedToArray(_useState3, 2),
      activeBackground = _useState4[0],
      setActiveBackground = _useState4[1];

  var storedColor = (0, _react.useRef)({
    color: undefined,
    background: undefined
  });
  var handleClickItem = (0, _react.useCallback)(function (type, color) {
    var currentColor = type.name == _index2.FONT_COLOR_SCHEMA_NAME ? activeColor : activeBackground;
    var c = color === currentColor ? undefined : color;

    if (type.name == _index2.FONT_COLOR_SCHEMA_NAME) {
      storedColor.current.color = c;
      setActiveColor(c);
    } else {
      storedColor.current.background = c;
      setActiveBackground(c);
    }

    (0, _commond.setColor)(editor, type, color);
    editor.view.focus();
  }, [activeColor, activeBackground]);
  (0, _react.useEffect)(function () {
    editor.on(_events.EDITOR_STATE_CHANGE, function (state) {
      var _state$selection = state.selection,
          from = _state$selection.from,
          to = _state$selection.to,
          $from = _state$selection.$from;
      var fontColor = '';
      var backgroundColor = '';

      if (from == to) {
        var marks = state.storedMarks || $from.marks();
        marks.forEach(function (mark) {
          if (mark.type.name == _index2.FONT_COLOR_SCHEMA_NAME) {
            if (fontColor && fontColor != mark.attrs.color) fontColor = _consts.FontColor["default"];
            if (!fontColor) fontColor = mark.attrs.color;
          }

          if (mark.type.name == _index2.BACKGROUND_COLOR_SCHEMA_NAME) {
            if (backgroundColor && backgroundColor != mark.attrs.color) backgroundColor = _consts.BackgroundColor["default"];
            if (!backgroundColor) backgroundColor = mark.attrs.color;
          }
        });
      } else {
        state.doc.nodesBetween(from, to, function (node) {
          node.marks.forEach(function (mark) {
            if (mark.type.name == _index2.FONT_COLOR_SCHEMA_NAME) {
              if (fontColor && fontColor != mark.attrs.color) fontColor = _consts.FontColor["default"];
              if (!fontColor) fontColor = mark.attrs.color;
            }

            if (mark.type.name == _index2.BACKGROUND_COLOR_SCHEMA_NAME) {
              if (backgroundColor && backgroundColor != mark.attrs.color) backgroundColor = _consts.BackgroundColor["default"];
              if (!backgroundColor) backgroundColor = mark.attrs.color;
            }
          });
        });
      }

      if (fontColor && !backgroundColor) {
        backgroundColor = _consts.BackgroundColor["default"];
      }

      if (backgroundColor && !fontColor) {
        fontColor = _consts.FontColor["default"];
      }

      if (!fontColor && !backgroundColor) {
        fontColor = storedColor.current.color || _consts.FontColor["default"];
        backgroundColor = storedColor.current.background || _consts.BackgroundColor["default"];
      }

      fontColor && setActiveColor(fontColor);
      backgroundColor && setActiveBackground(backgroundColor);
    });
  }, []);
  var handleClickMenu = (0, _react.useCallback)(function () {
    (0, _commond.setColor)(editor, editor.state.schema.marks[_index2.FONT_COLOR_SCHEMA_NAME], activeColor);
    (0, _commond.setColor)(editor, editor.state.schema.marks[_index2.BACKGROUND_COLOR_SCHEMA_NAME], activeBackground);
    editor.view.focus();
  }, [activeColor, activeBackground]);
  return /*#__PURE__*/_react["default"].createElement(_popup["default"], {
    action: ["hover"],
    popupPlacement: "top",
    popup: /*#__PURE__*/_react["default"].createElement(ColorSelector, {
      editor: editor,
      config: config,
      color: activeColor,
      background: activeBackground,
      onClickItem: handleClickItem
    })
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__icon',
    style: {
      backgroundColor: activeBackground || _consts.BackgroundColor["default"],
      color: activeColor || _consts.FontColor["default"]
    },
    onClick: handleClickMenu
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: config.icon
  })));
}

var _default = function _default(editor, config) {
  return /*#__PURE__*/_react["default"].createElement(ColorSelectorPop, {
    editor: editor,
    config: config
  });
};

exports["default"] = _default;