Prevent deletion

Hello,

I was wondering what is the best way to prevent deletion of specific node types …? Currently I’m using a filterTransaction plugin with something like:

    addProseMirrorPlugins() {
        return [
            new Plugin({
                filterTransaction(transaction, state) {
                    let return_value = true
                    transaction.steps.forEach((step, index) => {
                        state.doc.nodesBetween(
                            step.from, step.to, (node, pos) => { 
                                if (step.from < pos && step.to > pos) {
                                    if (node.type.name == 'flexItem') {
                                        return_value = false
                                        return false
                                    }
                                }
                            }
                        )
                    })
                    return return_value
                }
            })
        ];
    },

is there any better way of doing it ..?

Thanks !

A transaction filter is probably the best way to do something like this. But your code assumes all steps have from and to properties, which isn’t the case. You’ll probably want to iterate over the changed ranges in the step maps in Transaction.mapping instead.

Got it, thank you for your help! :slight_smile:

I ended with the following:


    addProseMirrorPlugins() {
        return [
            new Plugin({
                filterTransaction(transaction, state) {
                    let return_value = true
                    transaction.mapping.maps.forEach((map) => {
                        
                        /*
                         * A map describing the deletions and insertions made 
                         * by a step.
                         */

                        map.forEach((oldStart, oldEnd, newStart, newEnd) => {
                            console.debug('OLD START: ', oldStart)
                            console.debug('OLD END: ', oldEnd)
                            console.debug('NEW START: ', newStart)
                            console.debug('NEW END: ', newEnd)
                            
                            state.doc.nodesBetween(oldStart, oldEnd, (node, pos, parent) => {
                                if (pos >= oldStart && pos <= oldEnd) {
                                    if (node.type.name == 'flexItem') {
                                        return_value = false
                                    }
                                }
                            })

                        })
                    })

                    return return_value
                }
            })
        ];
    },

does it look OK ?