简体   繁体   中英

tiptap - Insert node below / at the end of the current one

I'm trying to create a text editor with tiptap using reactjs. I would like to create a button next to each "block" of the editor ( paragraph block, blockquote block, codeblock block, ...) that allows the user to add a new empty block just before the selected block. It would look like this (Notion editor) :

在当前演示下方添加块

So the way I tried to do this is to set the cursor's position at the end of the current node :

src/components/blocks/Paragraph.js

const Paragraph = (props) => {
    // ...

    

    return {
        // ...
        <button onMouseDown={() => {
            // ...

            // props.getPos() gives the position at the beginning of the block
            // props.node.nodeSize gives the "length" of the node
            const endPos = props.getPos() + props.node.nodeSize;
            props.editor.commands.focus(endPos);

            // ...
        }}>
             Add block below
        </button>
    }
}

So at this point, it works. But then, when I try to insert a new node at this position...

// It will insert a paragraph node containing text "New block added"
props.editor.commands.insertContent({
    "type":"paragraph",
    "content":[
        {
            "type":"text",
            "text":"New block added"
        }
    ]
})

... I get an error : TypeError: Cannot read property 'nodeType' of null

So, to let you see this error in details, I've made a sandbox on codesandbox.io. To reproduce the error, you just have to focus on the editor, write something random and then click on + button. You should see the error.

添加新块时出错

编辑 react-passing-local-state-to-parent-component

Thanks in advance for your help !

Current solution


Currently the best solution I've found :

const endPos = props.getPos() + props.node.nodeSize

// I focus the start of the editor because
// when the cursor is at the end of the node below which 
// we want to add a block, it doesn't focus the next block
props.editor.commands.focus('start')

props.editor
    .chain()
    .insertContentAt(endPos, {type: "paragraph"})
    .focus(endPos)
    .run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM