improve deletion recognition logic

This commit is contained in:
Dominik Biedebach 2024-10-11 09:53:36 +02:00
parent 48890f2df6
commit f5504ed9d8
2 changed files with 23 additions and 15 deletions

View File

@ -442,23 +442,17 @@ export class Editor extends EventEmitter<EditorEvents> {
transaction,
})
const hasReplaceSteps = transaction.steps.some(step => step.constructor.name === 'ReplaceStep')
const removedNodes = findRemovedNodesOnTransaction(transaction)
// We only want to do this if there are replace steps to avoid
// unnecessary work when there was no replaced content
if (hasReplaceSteps) {
const removedNodes = findRemovedNodesOnTransaction(transaction)
if (removedNodes.length) {
removedNodes.forEach(({ node, range }) => {
this.emit('nodeRemoved', {
editor: this,
transaction,
node,
range,
})
if (removedNodes) {
removedNodes.forEach(({ node, range }) => {
this.emit('nodeRemoved', {
editor: this,
transaction,
node,
range,
})
}
})
}
if (selectionHasChanged) {

View File

@ -1,5 +1,6 @@
import { Node } from '@tiptap/pm/model'
import { Transaction } from '@tiptap/pm/state'
import { ReplaceStep } from '@tiptap/pm/transform'
/**
* Finds removed nodes on a transaction including text nodes
@ -8,6 +9,19 @@ import { Transaction } from '@tiptap/pm/state'
* @returns An array of objects containing the removed node and the range of the node
*/
export const findRemovedNodesOnTransaction = (tr: Transaction) => {
if (!tr.steps.some(step => step instanceof ReplaceStep)) {
return null
}
const hasDeleteStep = tr.steps.some(step => {
return (step as ReplaceStep).slice.size === 0
})
// we don't want to run the following logic if this was not a delete step
if (!hasDeleteStep) {
return null
}
const removedNodes: Array<{ node: Node, range: { from: number, to: number } }> = []
const oldDoc = tr.before