Last active
September 16, 2023 16:47
-
-
Save fantactuka/2f1aaebc4c7abb616843140e7283a3ef to your computer and use it in GitHub Desktop.
Getting node and its DOM element after deletion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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