只需在 Prosemirror 中替换节点的内容



我在一个接收字符串作为输入的函数中:

(text) => {
}

我可以通过Vue道具(props.editor(访问编辑器。我想用此文本替换当前节点的内容。我似乎不知道该怎么做。我使用的是tiptap2,它是ProseMirror的包装器,可以访问ProseMirror所有的api。

除非必要,否则我宁愿不尝试替换整个节点,我也尝试过,如下所述——但也无法实现:

(text) => {
props.editor
.chain()
.focus()
.command(({ tr }) => {
const node = props.editor.state.schema.nodes.paragraph.create(
{ content: text}
);
tr.replaceSelectionWith(node);
return true;
})
.run();
}

非常感谢

此解决方案适用于Tiptap版本2。这样做的一个先决条件是,要替换的文本被标记(突出显示(。

const selection = editor.view.state.selection;
editor.chain().focus().insertContentAt({
from: selection.from,
to: selection.to
}, "replacement text").run();

我参加聚会迟到了,但这是我在为自己寻找解决方案时遇到的最重要的结果。

我的代码是在React NodeView的上下文中,所以我得到了一个getPos((道具,它给出了React节点在Prosemirror文档中的位置(我相信这个数字或多或少意味着React NodeView节点前面有多少个字符(。有了它,我就可以使用这个命令链来替换内容:

import { Node as ProsemirrorNode } from "prosemirror-model";
import { JSONContent, NodeViewProps } from "@tiptap/react";
const NodeViewComponent = (props: NodeViewProps) => 
// ...
/**
* Replace the current node with one containing newContent.
*/
const setContent = (newContent: JSONContent[]) => {
const thisPos = props.getPos();
props.editor
.chain()
.setNodeSelection(thisPos)
.command(({ tr }) => {
const newNode = ProsemirrorNode.fromJSON(props.editor.schema, {
type: props.node.type.name,
attrs: { ...props.attrs },
content: newContent,
});
tr.replaceSelectionWith(newNode);
return true;
})
.run();
};
// ...
};

基本上你想:

  1. 将当前选择设置为要替换的内容的节点
  2. 创建并更新作为当前节点副本的新节点
  3. 用新节点替换您的选择

最新更新