Skip to content

Commit

Permalink
Fix scrolling lines into view (#514)
Browse files Browse the repository at this point in the history
  • Loading branch information
Skalakid authored Oct 15, 2024
1 parent b97a0a6 commit 1170502
Showing 1 changed file with 14 additions and 21 deletions.
35 changes: 14 additions & 21 deletions src/web/utils/cursorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,28 +54,21 @@ function setCursorPosition(target: MarkdownTextInputElement, startIndex: number,

function scrollIntoView(target: MarkdownTextInputElement, node: TreeNode) {
const targetElement = target;
if (node.type === 'br' && node.parentNode?.parentNode?.type === 'line') {
// If the node is a line break, scroll to the parent paragraph, because Safari doesn't support scrollIntoView on br elements
node.parentNode.parentNode.element.scrollIntoView({
block: 'nearest',
});
} else {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const caretRect = range.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();

// In case the caret is below the visible input area, scroll to the end of the node
if (caretRect.top + caretRect.height > targetRect.top + targetRect.height) {
targetElement.scrollTop = caretRect.top + caretRect.height - targetRect.top - targetRect.height + target.scrollTop;
}
}

node.element.scrollIntoView({
block: 'nearest',
});
const orderIndex = Number(node.orderIndex.split(',')[0]);
const currentLine = target.tree.childNodes[orderIndex]?.element;
const scrollTargetElement = currentLine || node.element;

const caretRect = scrollTargetElement.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
// In case the caret is below the visible input area, scroll to the end of the node
if (caretRect.top + caretRect.height > targetRect.top + targetRect.height) {
targetElement.scrollTop = caretRect.top - targetRect.top + target.scrollTop - targetRect.height + caretRect.height + 4;
return;
}

scrollTargetElement.scrollIntoView({
block: 'nearest',
});
}

function moveCursorToEnd(target: HTMLElement) {
Expand Down

0 comments on commit 1170502

Please sign in to comment.