只需替换 prosemirror 中节点的内容

tyl*_*r-g 6 vue.js prose-mirror vuejs3 tiptap

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

\n
(text) => {\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我可以通过 Vue props ( ) 访问编辑器props.editor。我想用此文本替换当前节点的内容。我似乎不知道如何做到这一点。我正在使用tiptap2,它是 ProseMirror 的包装器,可以访问 ProseMirror 的所有 api。

\n

除非有必要,否则我宁愿不尝试替换整个节点,我也尝试过,在 \xe2\x80\x93 下面执行此操作,但也无法使其工作:

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

非常感谢

\n

jri*_*ief 5

这个解决方案在 Tiptap 版本 2 中适用于我。这个解决方案工作的前提是,要替换的文本被标记(突出显示)。

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


dan*_*iel 1

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

我的代码位于 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();
  };

  // ...
};
Run Code Online (Sandbox Code Playgroud)

基本上你想要:

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