From efd991c1b69f2ef5fe99dfb1d822fe1de06fab35 Mon Sep 17 00:00:00 2001 From: Lucas Vieira Date: Wed, 11 Sep 2024 09:07:21 -0300 Subject: [PATCH] fix: Unnecessary scrolling after code block insert When a code block is inserted, the editor switches to insert mode, which previously caused the scroll view to adjust slightly to ensure the current line was always visible. Now, we've changed the behavior to only scroll if the current line is actually off-screen. This prevents unnecessary scrolling after inserting blocks since the view already adjusts when the block is inserted. --- apps/web/src/components/v2Editor/index.tsx | 12 ++++++++--- apps/web/src/hooks/useV2CodeEditor.ts | 23 ++++++++++++++++------ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/v2Editor/index.tsx b/apps/web/src/components/v2Editor/index.tsx index 619a0b22..73aed989 100644 --- a/apps/web/src/components/v2Editor/index.tsx +++ b/apps/web/src/components/v2Editor/index.tsx @@ -890,7 +890,6 @@ file` }, [blocks, layout, tabRefs, environmentStartedAt]) const runBelowBlock = useCallback(() => { - debugger const currentBlockGroupIndex = layout.value.toArray().findIndex((bg) => { return bg.getAttribute('id') === props.id }) @@ -1247,9 +1246,16 @@ const V2Editor = (props: V2EditorProps) => { behavior: 'smooth', }) } else { - el.scrollIntoView({ + // scroll el so that it's center is at the center of the scroll view + const top = + elRect.top - + scrollRect.top - + scrollRect.height / 2 + + elRect.height / 2 + + scrollViewRef.current.scrollBy({ + top, behavior: 'smooth', - block: 'center', }) } diff --git a/apps/web/src/hooks/useV2CodeEditor.ts b/apps/web/src/hooks/useV2CodeEditor.ts index dda9b65e..88feb9d8 100644 --- a/apps/web/src/hooks/useV2CodeEditor.ts +++ b/apps/web/src/hooks/useV2CodeEditor.ts @@ -113,19 +113,30 @@ function useCodeEditor( !interactionState.scrollIntoView ) { const scrollView = document.getElementById('editor-scrollview') + const editorRect = editor.getDomNode()?.getBoundingClientRect() editor.focus() setIsEditorFocused(true) - if (!scrollView) { + if (!scrollView || !editorRect) { return } const currentLine = editor.getPosition()?.lineNumber ?? 0 - const top = editor.getTopForLineNumber(currentLine) - scrollView.scrollBy({ - top: top - scrollView.getBoundingClientRect().top - 80, - behavior: 'smooth', - }) + const scrollViewRect = scrollView.getBoundingClientRect() + const top = editorRect.top + editor.getTopForLineNumber(currentLine) + + // scroll to make sure we can see cursor in screen + if (top < scrollViewRect.top) { + scrollView.scrollBy({ + top: top - scrollViewRect.top - 80, + behavior: 'smooth', + }) + } else if (top + 20 > scrollViewRect.bottom) { + scrollView.scrollBy({ + top: top - scrollViewRect.bottom + 80, + behavior: 'smooth', + }) + } } }, [interactionState, blockId, editor])