tiptap - 在当前节点下方/末尾插入节点

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

我正在尝试使用 tiptap 使用 reactjs 创建一个文本编辑器。我想在编辑器的每个“块”旁边创建一个按钮(paragraph 块,blockquote 块,codeblock 块,...),允许用户添加一个新的所选块之前的空块。它看起来像这样(概念编辑器):

所以我尝试这样做的方法是将光标的位置设置在当前节点的末尾:

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>
    }
}

所以在这一点上,它起作用了。但是,当我尝试在这个位置插入一个新的 node 时...

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

...我得到一个错误:TypeError: Cannot read property 'nodeType' of null

因此,为了让您详细了解此错误,我在 codesandbox.io 上制作了一个沙盒。要重现错误,您只需要专注于编辑器,随意写一些东西,然后单击 + 按钮。您应该会看到错误。

在此先感谢您的帮助!

当前解决方案


目前我找到的最佳解决方案:

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()