admin管理员组文章数量:1405564
I want to mimic the end of line shortcut behavior in macOS. I have this:
onKeyDown (event, change, next) {
if (event.key === 'ArrowRight') {
if (event.metaKey) {
event.preventDefault();
change.moveTo(5);
return true;
}
}
return next();
}
The problem is that now the offset index is a fixed 5
on change.moveTo(5)
.
How do I find the index of the last character of the current line?
I want to mimic the end of line shortcut behavior in macOS. I have this:
onKeyDown (event, change, next) {
if (event.key === 'ArrowRight') {
if (event.metaKey) {
event.preventDefault();
change.moveTo(5);
return true;
}
}
return next();
}
The problem is that now the offset index is a fixed 5
on change.moveTo(5)
.
How do I find the index of the last character of the current line?
Share Improve this question edited Oct 16, 2018 at 19:08 Pier asked Oct 16, 2018 at 18:51 PierPier 10.8k17 gold badges72 silver badges118 bronze badges2 Answers
Reset to default 5Slate does not really know about lines and such, so the solution is to get a native range and check the coordinates of its bounding box.
I made a function that returns the index of the last possible position in a line, or the last position in the current text block which would happen if the caret is in the last line.
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;
}
This is possible with slate.js. Look at the following code.
First I'm matching the closest block. Then I'm getting the end path of the current block. Then I'm using Transform to move the cursor to the end of the line.
Look at the code example below:
import { Transforms, Editor } from 'slate';
export function moveToEnd(editor: Editor) {
const block = Editor.above(editor, {
match: n => Editor.isBlock(editor, n),
});
if(!block) return;
const [, blockPath] = block;
const endBlockPath = Editor.end(editor, blockPath);
Transforms.select(editor, endBlockPath);
}
本文标签: javascriptHow to move the cursor to the end of the current line with SlatejsStack Overflow
版权声明:本文标题:javascript - How to move the cursor to the end of the current line with Slate.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744906580a2631660.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论