Skip to content

Instantly share code, notes, and snippets.

@stevecastaneda
Last active November 18, 2023 07:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevecastaneda/eb50aed3e5903aac2995f7cc850f71b1 to your computer and use it in GitHub Desktop.
Save stevecastaneda/eb50aed3e5903aac2995f7cc850f71b1 to your computer and use it in GitHub Desktop.
Tiptap: Check if a node has been deleted
// 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