"use strict";

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

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

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

var _isHotkey = _interopRequireDefault(require("is-hotkey"));

var _ahooks = require("ahooks");

var _hooks = require("@parallel-line/common/es/hooks");

var _utils = require("./utils");

var _components = require("./components");

var _slate = require("./slate");

var _excluded = ["placeholder", "defaultValue"];

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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

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

var HOTKEYS = {
  'mod+b': 'bold',
  'mod+i': 'italic',
  'mod+u': 'underline'
};

function RichTextEditor(props) {
  var disabled = props.disabled,
      _props$placeholder = props.placeholder,
      placeholder = _props$placeholder === void 0 ? '请输入' : _props$placeholder,
      _props$value = props.value,
      value = _props$value === void 0 ? _utils.EMPTY_DESCENDANT : _props$value,
      defaultValue = props.defaultValue;

  var _useNamespace = (0, _hooks.useNamespace)('rich-text-box', props.prefixCls),
      _useNamespace2 = _slicedToArray(_useNamespace, 2),
      bem = _useNamespace2[1];

  var _React$useState = _react.default.useState(defaultValue || value),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      state = _React$useState2[0],
      setState = _React$useState2[1]; // const [count, setCount] = React.useState(0);


  var _useBoolean = (0, _ahooks.useBoolean)(),
      _useBoolean2 = _slicedToArray(_useBoolean, 2),
      hasFocus = _useBoolean2[0],
      _useBoolean2$ = _useBoolean2[1],
      handleFocus = _useBoolean2$.setTrue,
      setFalse = _useBoolean2$.setFalse;

  var renderElement = (0, _react.useCallback)(function (_ref) {
    var attributes = _ref.attributes,
        children = _ref.children,
        element = _ref.element;

    var _serializeElement = (0, _utils.serializeElement)(element),
        tag = _serializeElement.tag,
        css = _serializeElement.css;

    return /*#__PURE__*/_react.default.createElement(tag, _objectSpread(_objectSpread({}, attributes), {}, {
      style: css
    }), children);
  }, []);
  var renderLeaf = (0, _react.useCallback)(function (_ref2) {
    var attributes = _ref2.attributes,
        children = _ref2.children,
        leaf = _ref2.leaf;

    var _serializeLeaf = (0, _utils.serializeLeaf)(leaf),
        tag = _serializeLeaf.tag,
        css = _serializeLeaf.css;

    return /*#__PURE__*/_react.default.createElement(tag, _objectSpread(_objectSpread({}, attributes), {}, {
      style: css
    }), children);
  }, []);
  var editor = (0, _react.useMemo)(function () {
    return (0, _slate.withHistory)((0, _slate.withReact)((0, _slate.createEditor)()));
  }, []);
  (0, _ahooks.useUpdateEffect)(function () {
    setState(value);
  }, [value]);

  var handleKeyDown = function handleKeyDown(event) {
    for (var hotkey in HOTKEYS) {
      if ((0, _isHotkey.default)(hotkey, event)) {
        event.preventDefault();
        var mark = HOTKEYS[hotkey];

        _components.MarkButton.toggleMark(editor, mark);
      }
    }
  };

  var handleBlur = function handleBlur() {
    setTimeout(setFalse, 300);
  };

  var handleChange = function handleChange(value) {
    var _props$onChange;

    setState(value);
    (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, value); // if (maxLength > 0) {
    //   const newCount = serializeText(value).length;
    //   setCount(newCount);
    // }
  };

  return /*#__PURE__*/_react.default.createElement(_slate.Slate, {
    editor: editor,
    value: state,
    onChange: handleChange
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: bem('wrapper', {
      disabled: disabled
    })
  }, /*#__PURE__*/_react.default.createElement(_components.ToolBar, {
    disabled: disabled ? disabled : !hasFocus,
    className: bem('tool-bar'),
    buttonPrefixCls: bem('button')
  }), /*#__PURE__*/_react.default.createElement(_slate.Editable, {
    spellCheck: true,
    className: bem(),
    readOnly: disabled,
    renderLeaf: renderLeaf,
    renderElement: renderElement,
    placeholder: placeholder,
    onKeyDown: handleKeyDown,
    onFocus: handleFocus,
    onBlur: handleBlur
  })));
}

function RichTextBox(props) {
  var _props$placeholder2 = props.placeholder,
      placeholder = _props$placeholder2 === void 0 ? '请输入' : _props$placeholder2,
      defaultValue = props.defaultValue,
      richTextEditorProps = _objectWithoutProperties(props, _excluded);

  var _useControllableValue = (0, _ahooks.useControllableValue)(props),
      _useControllableValue2 = _slicedToArray(_useControllableValue, 2),
      state = _useControllableValue2[0],
      setState = _useControllableValue2[1];

  var handleChange = function handleChange(value) {
    setState((0, _utils.serializeHTML)(value));
  };

  return /*#__PURE__*/_react.default.createElement(RichTextEditor, Object.assign({}, richTextEditorProps, {
    placeholder: placeholder,
    value: (0, _utils.deserializeHTML)(state),
    onChange: handleChange
  }));
}

var _default = RichTextEditor;
exports.default = _default;