tiptap - 在当前节点的下方/末尾插入节点 当前的解决方案之前的编辑

问题描述

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

Add block below current demo

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

src/components/blocks/Paragraph.js

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

所以在这一点上,它起作用了。但是,当我尝试在此位置插入新的 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

所以,为了让你看到这个错误的细节,我在 codeandBox.io 上做了一个沙箱。要重现错误,您只需关注编辑器,随机编写一些内容,然后单击 + 按钮。您应该会看到错误

Error when adding a new block

Edit react-passing-local-state-to-parent-component

预先感谢您的帮助!

解决方法

当前的解决方案


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

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

之前的编辑


好吧,我终于让它起作用了。通过使用 editor.chain() 链接命令,它似乎有效。所以如果有人遇到同样的问题,这里是我做的:

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

现在它起作用了!

编辑:但我仍然有一个问题:使用selectNodeForward()后没有显示光标/插入符号...

enter image description here