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

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

import React, { useCallback, useMemo } from 'react';
import isHotkey from 'is-hotkey';
import { useControllableValue, useUpdateEffect, useBoolean } from 'ahooks';
import { useNamespace } from '@parallel-line/common/es/hooks';
import { serializeElement, serializeText, serializeHTML, deserializeHTML, EMPTY_DESCENDANT, serializeLeaf } from './utils';
import { MarkButton, ToolBar } from './components';
import { withHistory, Editable, withReact, Slate, createEditor } from './slate';
var HOTKEYS = {
  'mod+b': 'bold',
  'mod+i': 'italic',
  'mod+u': 'underline'
};
export 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 ? EMPTY_DESCENDANT : _props$value,
      defaultValue = props.defaultValue;

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

  var _React$useState = React.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 = useBoolean(),
      _useBoolean2 = _slicedToArray(_useBoolean, 2),
      hasFocus = _useBoolean2[0],
      _useBoolean2$ = _useBoolean2[1],
      handleFocus = _useBoolean2$.setTrue,
      setFalse = _useBoolean2$.setFalse;

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

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

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

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

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

  var handleKeyDown = function handleKeyDown(event) {
    for (var hotkey in HOTKEYS) {
      if (isHotkey(hotkey, event)) {
        event.preventDefault();
        var mark = HOTKEYS[hotkey];
        MarkButton.toggleMark(editor, mark);
      }
    }
  };

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

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

    if (serializeText(value).length) {
      var _props$onChange;

      setState(value);
      (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, value);
      return;
    }

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

  return /*#__PURE__*/React.createElement(Slate, {
    editor: editor,
    value: state,
    onChange: handleChange
  }, /*#__PURE__*/React.createElement("div", {
    className: bem('wrapper', {
      disabled: disabled
    })
  }, /*#__PURE__*/React.createElement(ToolBar, {
    disabled: disabled ? disabled : !hasFocus,
    className: bem('tool-bar'),
    buttonPrefixCls: bem('button')
  }), /*#__PURE__*/React.createElement(Editable, {
    spellCheck: true,
    className: bem(),
    readOnly: disabled,
    renderLeaf: renderLeaf,
    renderElement: renderElement,
    placeholder: placeholder,
    onKeyDown: handleKeyDown,
    onFocus: handleFocus,
    onBlur: handleBlur
  })));
}
export function RichTextBox(props) {
  var _props$placeholder2 = props.placeholder,
      placeholder = _props$placeholder2 === void 0 ? '请输入' : _props$placeholder2,
      defaultValue = props.defaultValue,
      richTextEditorProps = _objectWithoutProperties(props, _excluded);

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

  var handleChange = function handleChange(value) {
    setState(serializeHTML(value));
  };

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