How to filter pasted content by node type?

Hello, I would like to prevent pasting a specific node type. The following code works for children at the root of the pasted slice’s content:

handlePaste(view, event, slice) {
    let filteredContent = []
    slice.content.forEach((node) => {
        if (node.type.name !== "node_type") {
            filteredContent.push(node)
        }
    })
    
    // and then...
    view.dispatch(
        view.state.tr.replaceSelection(
            new Slice(
                Fragment.fromArray(filteredContent),
                slice.openStart,
                slice.openEnd
            )
        )
    )
}

But this doesn’t work if this node is nested inside another node (e.g. a blockquote or a bullet list). I guess I should make a recursive function, but I believe I cannot directly edit a Node 's content?

Thanks in advance for your help!

Calling descendants on each of the slice’s children might help with this.

Thanks for your answer. Node.descendants gives me each child node, but I still don’t know how to filter them.

I think I may not have given enough details in my question: I don’t want to prevent pasting the whole node if it contains a node that shouldn’t be pasted, this node should be pasted anyway but only with the children that can be pasted.

I’m nearly positive this will work for you model.ParseRule.ignore. In short, you’ll need to develop a ParseRule and mark this ignore flag as true to skip that DOM node.

Would appreciate confirmation @marijn

1 Like

Thank you @bZichett! I added the ignore flag to the parse rule and it works perfectly!

1 Like