Fix caret jump when backspacing into empty line at beginning of editor (#11128)

Fixes: vector-im/element-web#22335
pull/28217/head
Johannes Marbach 2023-06-23 17:24:05 +02:00 committed by GitHub
parent 36c81f6416
commit ab98268901
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 4 deletions

View File

@ -104,10 +104,10 @@ export function getLineAndNodePosition(
} {
const { parts } = model;
const partIndex = caretPosition.index;
const lineResult = findNodeInLineForPart(parts, partIndex);
let { offset } = caretPosition;
const lineResult = findNodeInLineForPart(parts, partIndex, offset);
const { lineIndex } = lineResult;
let { nodeIndex } = lineResult;
let { offset } = caretPosition;
// we're at an empty line between a newline part
// and another newline part or end/start of parts.
// set offset to 0 so it gets set to the <br> inside the line container
@ -120,7 +120,11 @@ export function getLineAndNodePosition(
return { lineIndex, nodeIndex, offset };
}
function findNodeInLineForPart(parts: Part[], partIndex: number): { lineIndex: number; nodeIndex: number } {
function findNodeInLineForPart(
parts: Part[],
partIndex: number,
offset: number,
): { lineIndex: number; nodeIndex: number } {
let lineIndex = 0;
let nodeIndex = -1;
@ -130,6 +134,10 @@ function findNodeInLineForPart(parts: Part[], partIndex: number): { lineIndex: n
for (let i = 0; i <= partIndex; ++i) {
const part = parts[i];
if (part.type === Type.Newline) {
// don't jump over the linebreak if the offset is before it
if (i == partIndex && offset === 0) {
continue;
}
lineIndex += 1;
nodeIndex = -1;
prevPart = undefined;

View File

@ -46,6 +46,14 @@ describe("editor/caret: DOM position for caret", function () {
});
});
describe("handling line breaks", function () {
it("at start of first line which is empty", function () {
const pc = createPartCreator();
const model = new EditorModel([pc.newline(), pc.plain("hello world")], pc);
const { offset, lineIndex, nodeIndex } = getLineAndNodePosition(model, { index: 0, offset: 0 });
expect(lineIndex).toBe(0);
expect(nodeIndex).toBe(-1);
expect(offset).toBe(0);
});
it("at end of last line", function () {
const pc = createPartCreator();
const model = new EditorModel([pc.plain("hello"), pc.newline(), pc.plain("world")], pc);
@ -62,6 +70,14 @@ describe("editor/caret: DOM position for caret", function () {
expect(nodeIndex).toBe(0);
expect(offset).toBe(0);
});
it("before empty line", function () {
const pc = createPartCreator();
const model = new EditorModel([pc.plain("hello"), pc.newline(), pc.newline(), pc.plain("world")], pc);
const { offset, lineIndex, nodeIndex } = getLineAndNodePosition(model, { index: 0, offset: 5 });
expect(lineIndex).toBe(0);
expect(nodeIndex).toBe(0);
expect(offset).toBe(5);
});
it("in empty line", function () {
const pc = createPartCreator();
const model = new EditorModel([pc.plain("hello"), pc.newline(), pc.newline(), pc.plain("world")], pc);