gpt4 book ai didi

javascript - 如何使用 Slate.js 将光标移动到当前行的末尾?

转载 作者:行者123 更新时间:2023-11-29 23:15:48 28 4
gpt4 key购买 nike

我想模仿 macOS 中的行尾快捷方式行为。我有这个:

onKeyDown (event, change, next) {

if (event.key === 'ArrowRight') {
if (event.metaKey) {
event.preventDefault();
change.moveTo(5);
return true;
}
}

return next();
}

问题是现在偏移索引在 change.moveTo(5) 上固定为 5

如何找到当前行最后一个字符的索引?

最佳答案

Slate 并不真正了解线条等,因此解决方案是获取原生范围并检查其边界框的坐标。

我创建了一个函数,返回一行中最后一个可能位置的索引,或者返回当前文本 block 中最后一个位置的索引,如果插入符号位于最后一行,则会发生这种情况。

getIndexLastCharOfLine () {
const selection = window.getSelection()
const range = selection.getRangeAt(0);
const caretIndex = range.startOffset;
const rect = range.getBoundingClientRect();
const container = range.startContainer;
const lastIndex = container.length;

for (let i = caretIndex; i < lastIndex; i++) {
const rangeTest = document.createRange();
rangeTest.setStart(container, i);
const rectTest = rangeTest.getBoundingClientRect();
// if the y is different it means the test range is in a different line
if (rectTest.y !== rect.y) return i - 1;
}

return lastIndex;
}

关于javascript - 如何使用 Slate.js 将光标移动到当前行的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52842172/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com