Slate 并不真正了解线条等,因此解决方案是获取原生范围并检查其边界框的坐标。
我创建了一个函数,它返回一行中最后一个可能位置的索引,或者返回当前文本块中的最后一个位置,如果插入符号在最后一行,则会发生这种情况。
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;
}