【问题标题】:ProseMirror - Set caret position to end of selected nodeProseMirror - 将插入符号位置设置为所选节点的末尾
【发布时间】:2020-07-25 00:13:34
【问题描述】:

运行命令({ href: url }) 后,我想取消选择当前选择并将插入符号位置设置为所选节点的末尾。注意:我正在使用 TipTap

setLinkUrl(command, url) {
command({ href: url })
this.hideLinkMenu()

// Set cursor position after highlighted link
var tag = document.getElementById("editor")

var setpos = document.createRange()

var set = window.getSelection()

const state = this.editor.state

let sel = state.selection
// TODO: Check if sel range > 0
let resolvedPos = state.doc.resolve(sel.from)
let node = resolvedPos.node(resolvedPos.depth)

// This is where I want to set the caret position to the end of the currently selected node
// Currently, I'm using hardcoded indices as proof of concept while the editor contains three paragraph nodes
setpos.setStart(document.getElementById("editor").childNodes[0].childNodes[1], 1)
setpos.setEnd(document.getElementById("editor").childNodes[0].childNodes[1], 1)

setpos.collapse(true)

set.removeAllRanges()

set.addRange(setpos)

tag.focus()

【问题讨论】:

    标签: javascript text-editor rich-text-editor prose-mirror tiptap


    【解决方案1】:

    这就是你使用 ProseMirror 的方式,我想它也应该转换为 TipTap。

    一个选择可以跨越多个节点,所以我们要将插入符号移动到最后一个选定节点的末尾。

    选择结束的解析位置在selection.$to。这是 ProseMirror 中的约定,解析位置以 $ 开头。

    要在已解析位置的当前节点末尾找到下一个“剪切”,您可以使用after() 方法。这将在节点结束后返回一个位置,因此我们需要从中减去一个。

    最后,我们需要创建一个新的选择并通过使用setSelection() 方法分派一个文档转换来应用它。请记住,TextSelection 需要一个解析的位置来实例化,而不是位置编号。

    如果我们把它们放在一起,我们可以创建一个命令来执行此操作:

    import {TextSelection} from "prosemirror-state";
    
    function moveToEnd (state, dispatch, view) {
        // Don't dispatch this command if the selection is empty
        if (state.selection.empty) return false;
    
        // Subtract one so that it falls within the current node
        const endPos = state.selection.$to.after() - 1;
        const selection = new TextSelection(state.doc.resolve(endPos));
        let transaction = state.tr.setSelection(selection);
    
        if (dispatch) dispatch(transaction.scrollIntoView());
    
        return true;
    }
    

    您可以在实例化编辑器时将此命令与keymap 模块一起使用:

    keymap({
        'Mod-Shift-j': moveToEnd
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多