How to implement empty doc by backspace?


#1

Current behavior is that when I have data in a doc and for example the first block is a header and I clean everything, the header could end up in the empty doc as:

<div class="ProseMirror">
   <h3></h3>
</div>

What I want to accomplish is that when I empty everything even with backspace that it becomes:

<div class="ProseMirror">
   <p></p>
</div>

I need to write a plugin for this, but what could be a good implementation.


#2

The idea would be to write a command that notices this situation (document empty, single top-level tag not a regular paragraph) and changes that tag to a paragraph, and bind backspace to it.


#3

For the ones who also need this functionality, I used the following code.

export function emptyContent(state, dispatch) {
    const { tr } = state;
    let doc = state.doc;

    if (doc.childCount === 1 && doc.firstChild.isTextblock && doc.firstChild.content.size === 0 && doc.firstChild.type !== state.schema.nodes.paragraph) {
        tr.setBlockType(1, 1, state.schema.nodes.paragraph);
        if (dispatch) {
            dispatch(tr);
        }
        return true;
    }
    return false;
}