繁体   English   中英

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

[英]simply replace a node's content in prosemirror

我在接收字符串作为输入的 function 中:

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

非常感谢

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

我的代码在 React NodeView 的上下文中,所以我得到了一个 getPos() 道具,它给出了 Prosemirror 文档中 React 节点的 position(我相信这个数字或多或少意味着有多少个字符在 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. 用新节点替换您的选择。

此解决方案在 Tiptap 版本 2 中适用于我。此解决方案的先决条件是,要替换的文本被标记(突出显示)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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