From 1170502c68de84442e23c2c87b0388796299e727 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Ska=C5=82ka?= <39538890+Skalakid@users.noreply.github.com> Date: Tue, 15 Oct 2024 03:30:39 -0700 Subject: [PATCH] Fix scrolling lines into view (#514) --- src/web/utils/cursorUtils.ts | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/src/web/utils/cursorUtils.ts b/src/web/utils/cursorUtils.ts index 6b86707f..adc0a1b9 100644 --- a/src/web/utils/cursorUtils.ts +++ b/src/web/utils/cursorUtils.ts @@ -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) {