@yuntijs/ui
Version:
☁️ Yunti UI - an open-source UI component library for building Cloud Native web apps
43 lines • 1.93 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { mergeRegister } from '@lexical/utils';
import { $applyNodeReplacement } from 'lexical';
import { memo, useCallback, useEffect } from 'react';
import { decoratorTransform } from "../../utils";
import { CustomTextNode } from "../custom-text/node";
import { $createMentionNode, MentionNode } from "./node";
import { MENTION_REGEX } from "./utils";
export var MentionNodePluginReplacement = /*#__PURE__*/memo(function (_ref) {
var onInsert = _ref.onInsert;
var _useLexicalComposerCo = useLexicalComposerContext(),
_useLexicalComposerCo2 = _slicedToArray(_useLexicalComposerCo, 1),
editor = _useLexicalComposerCo2[0];
useEffect(function () {
if (!editor.hasNodes([MentionNode])) throw new Error('MentionNodePlugin: MentionNode not registered on editor');
}, [editor]);
var createMentionNode = useCallback(function (textNode) {
if (onInsert) onInsert();
var nodePathString = textNode.getTextContent().slice(2, -2);
return $applyNodeReplacement($createMentionNode(nodePathString));
}, [onInsert]);
var getMatch = useCallback(function (text) {
var matchArr = MENTION_REGEX.exec(text);
if (matchArr === null) return null;
var startOffset = matchArr.index;
var endOffset = startOffset + matchArr[0].length;
return {
end: endOffset,
start: startOffset
};
}, []);
var transformListener = useCallback(function (textNode) {
MENTION_REGEX.lastIndex = 0;
return decoratorTransform(textNode, getMatch, createMentionNode);
}, [createMentionNode, getMatch]);
useEffect(function () {
MENTION_REGEX.lastIndex = 0;
return mergeRegister(editor.registerNodeTransform(CustomTextNode, transformListener));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
});