I am trying to implement track changes in lexical editor. But I am not sure how to wrap the character typed by the user.
- If the user type a character then it should be wrapped in a span tag with class name
inserted. - If the user delete a character then it should be wrapped in a span tag with class name
deleted.
I tried registerMutationListener and registerUpdateListener and tried a custom plugin which will get the diff of the previousEditorState and currentEditorState and it will wrap the selection. But it's affecting the history stack.
Not very sure how to implement.
Can anyone give some suggestions please ?
Thanks in advance
function ListenerPlugin() {
const [editor] = useLexicalComposerContext();
useLayoutEffect(() => {
return editor.registerUpdateListener(({prevEditorState, editorState}) => {
var nextText;
var prevText;
editorState.read(()=>{
nextText = $getRoot().getTextContent()
})
prevEditorState.read(()=>{
prevText = $getRoot().getTextContent()
})
editor.update(()=>{
if(nextText || prevText){
const selection = $getSelection();
const node = selection.getNodes()[0];
const key = node.__key;
const diff = diffTextContentAndApplyDelta(selection, key, prevText, nextText);
if(diff && diff.insert !== '' && diff.remove === 0) {
const isBackward = selection.isBackward();
$wrapSelectionInMarkNode(selection, isBackward)
}
}
})
});
}, [editor]);
}