maintain caret at current line when position is on newline part

This commit is contained in:
Bruno Windels 2019-05-24 18:54:29 +02:00
parent 9d6a818591
commit b2592583c4

View file

@ -20,13 +20,23 @@ export function setCaretPosition(editor, model, caretPosition) {
sel.removeAllRanges();
const range = document.createRange();
const {parts} = model;
const {index} = caretPosition;
let {offset} = caretPosition;
let lineIndex = 0;
let nodeIndex = -1;
for (let i = 0; i <= caretPosition.index; ++i) {
for (let i = 0; i <= index; ++i) {
const part = parts[i];
if (part && part.type === "newline") {
lineIndex += 1;
nodeIndex = -1;
if (i < index) {
lineIndex += 1;
nodeIndex = -1;
} else {
// if index points at a newline part,
// put the caret at the end of the previous part
// so it stays on the same line
const prevPart = parts[i - 1];
offset = prevPart ? prevPart.text.length : 0;
}
} else {
nodeIndex += 1;
}
@ -34,7 +44,7 @@ export function setCaretPosition(editor, model, caretPosition) {
let focusNode;
const lineNode = editor.childNodes[lineIndex];
if (lineNode) {
if (lineNode.childNodes.length === 0 && caretPosition.offset === 0) {
if (lineNode.childNodes.length === 0 && offset === 0) {
focusNode = lineNode;
} else {
focusNode = lineNode.childNodes[nodeIndex];
@ -50,7 +60,7 @@ export function setCaretPosition(editor, model, caretPosition) {
range.collapse(false);
} else {
// make sure we have a text node
range.setStart(focusNode, caretPosition.offset);
range.setStart(focusNode, offset);
range.collapse(true);
}
sel.addRange(range);