con*_*sen 1 javascript text-editor rich-text-editor prose-mirror tiptap
运行命令({ 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()
Run Code Online (Sandbox Code Playgroud)
这就是你使用 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;
}
Run Code Online (Sandbox Code Playgroud)
实例化编辑器时,您可以将此命令与键盘映射模块一起使用:
keymap({
'Mod-Shift-j': moveToEnd
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4736 次 |
| 最近记录: |