0

运行命令({ 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()
4

1 回答 1

2

这就是您使用 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
})
于 2020-12-09T23:21:44.757 回答