Skip to content

Instantly share code, notes, and snippets.

@fantactuka
Last active September 16, 2023 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fantactuka/2f1aaebc4c7abb616843140e7283a3ef to your computer and use it in GitHub Desktop.
Save fantactuka/2f1aaebc4c7abb616843140e7283a3ef to your computer and use it in GitHub Desktop.
Getting node and its DOM element after deletion
useEffect(() => {
const domMap: Map<NodeKey, HTMLElement | null> = new Map();
return editor.registerMutationListener(
MentionNode,
(mutations, {prevEditorState}) => {
for (const [nodeKey, mutation] of mutations) {
if (mutation === 'created' || mutation === 'updated') {
domMap.set(nodeKey, editor.getElementByKey(nodeKey));
}
if (mutation === 'destroyed') {
const prevNode = prevEditorState.read(() => $getNodeByKey(nodeKey));
const prevNodeElement = domMap.get(nodeKey);
domMap.delete(nodeKey);
console.log({
prevNode,
prevNodeElement,
});
}
}
},
);
}, [editor]);
useEffect(() => {
return editor.registerMutationListener(
MentionNode,
(mutations, {prevEditorState}) => {
for (const [nodeKey, mutation] of mutations) {
if (mutation === 'destroyed') {
// Reading prev node and its siblings keys from previous editor state
const {prevNode, nextSiblingKey, prevSiblingKey} =
prevEditorState.read(() => {
const node = $getNodeByKey(nodeKey);
return {
nextSiblingKey: node?.getNextSibling()?.getKey(),
prevNode: node,
prevSiblingKey: node?.getPreviousSibling()?.getKey(),
};
});
// Getting sibling nodes from current editor state based on its keys in the previous editor state
const {nextSibling, prevSibling} = editor
.getEditorState()
.read(() => {
return {
nextSibling: nextSiblingKey && $getNodeByKey(nextSiblingKey),
prevSibling: prevSiblingKey && $getNodeByKey(prevSiblingKey),
};
});
console.log({
nextSibling,
prevNode,
prevSibling,
});
}
}
},
);
}, [editor]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment