简体   繁体   English

如何使用 Slate.js 将 cursor 移动到当前行的末尾?

[英]How to move the cursor to the end of the current line with Slate.js?

I want to mimic the end of line shortcut behavior in macOS.我想模仿 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) .问题是现在偏移索引在change.moveTo(5)上固定为5

How do I find the index of the last character of the current line?如何找到当前行最后一个字符的索引?

Slate 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. Slate 并不真正了解线条等,因此解决方案是获取原生范围并检查其边界框的坐标。

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.这可以通过 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.然后我使用 Transform 将 cursor 移动到行尾。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM