Last active
August 17, 2024 11:58
-
-
Save stevecastaneda/eb50aed3e5903aac2995f7cc850f71b1 to your computer and use it in GitHub Desktop.
Tiptap: Check if a node has been deleted
This file contains 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
// From Github issue | |
// https://github.com/ueberdosis/tiptap/issues/3700 | |
// Requires that the node have an ID | |
// See: https://tiptap.dev/api/extensions/unique-id | |
import { Node } from "@tiptap/pm/model"; | |
import { Editor as CoreEditor } from "@tiptap/core"; | |
// Remember the rpevious state, so we can diff edits and detect deleted nodes | |
const previousState = useRef<EditorState>(); | |
// Fires when a deletion is detected | |
const onNodeDeleted = useCallback( | |
(node: Node) => { | |
// Do stuff... | |
}, | |
[], | |
); | |
// Runs on every editor update to check for deletions | |
const checkForNodeDeletions = useCallback( | |
({ editor }: { editor: CoreEditor }) => { | |
// Compare previous/current nodes to detect deleted ones | |
const prevNodesById: Record<string, Node> = {}; | |
previousState.current?.doc.forEach((node) => { | |
if (node.attrs.id) { | |
prevNodesById[node.attrs.id] = node; | |
} | |
}); | |
const nodesById: Record<string, Node> = {}; | |
editor.state.doc.forEach((node) => { | |
if (node.attrs.id) { | |
nodesById[node.attrs.id] = node; | |
} | |
}); | |
previousState.current = editor.state; | |
for (const [id, node] of Object.entries(prevNodesById)) { | |
if (nodesById[id] === undefined) { | |
onNodeDeleted(node); | |
} | |
} | |
}, | |
[onNodeDeleted], | |
); | |
const editor = useEditor ( | |
{ | |
onUpdate: (e) => { | |
checkForNodeDeletions(e) | |
} | |
... | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment