@yuntijs/ui
Version:
☁️ Yunti UI - an open-source UI component library for building Cloud Native web apps
63 lines • 2.67 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { CAN_USE_BEFORE_INPUT, IS_APPLE_WEBKIT, IS_IOS, IS_SAFARI } from '@lexical/utils';
import { $getRoot, $getSelection, $isRangeSelection, COMMAND_PRIORITY_LOW, INSERT_PARAGRAPH_COMMAND, KEY_ENTER_COMMAND } from 'lexical';
import { useEffect, useRef } from 'react';
export var ShiftEnterKeyPlugin = function ShiftEnterKeyPlugin(_ref) {
var onPressEnter = _ref.onPressEnter;
var _useLexicalComposerCo = useLexicalComposerContext(),
_useLexicalComposerCo2 = _slicedToArray(_useLexicalComposerCo, 1),
editor = _useLexicalComposerCo2[0];
var onPressEnterRef = useRef(onPressEnter);
useEffect(function () {
onPressEnterRef.current = onPressEnter;
}, [onPressEnter]);
useEffect(function () {
// https://github.com/facebook/lexical/discussions/4464#discussioncomment-5833227
editor.registerCommand(KEY_ENTER_COMMAND, function (event) {
var selection = $getSelection();
if (!$isRangeSelection(selection)) {
return false;
}
if (event !== null) {
// If we have beforeinput, then we can avoid blocking
// the default behavior. This ensures that the iOS can
// intercept that we're actually inserting a paragraph,
// and autocomplete, autocapitalize etc work as intended.
// This can also cause a strange performance issue in
// Safari, where there is a noticeable pause due to
// preventing the key down of enter.
if ((IS_IOS || IS_SAFARI || IS_APPLE_WEBKIT) && CAN_USE_BEFORE_INPUT) {
return false;
}
event.preventDefault();
if (event.shiftKey) {
return editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, void 0);
}
}
event === null || event === void 0 || event.preventDefault();
var text = editor.read(function () {
return $getRoot().getTextContent();
});
var value = text.replaceAll('\n\n', '\n');
// 这里把 onPressEnter 放在下一次事件循环中触发,是为了避免跟 Lexical 还未结束的输入等事务发生冲突
if (window.queueMicrotask === undefined) {
setTimeout(function () {
onPressEnterRef.current(value, {
event: event
});
}, 0);
} else {
queueMicrotask(function () {
onPressEnterRef.current(value, {
event: event
});
});
}
return true;
},
// 优先级要低于 MentionPickerPlugin
COMMAND_PRIORITY_LOW);
}, [editor]);
return null;
};