Skip to content

Commit 987fcca

Browse files
committed
fix(editor): prevent editor from scrolling on focus
Capture scroll position before focus and restore it via requestAnimationFrame to undo CodeMirror's automatic scrollIntoView.
1 parent 5a5ffc9 commit 987fcca

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

packages/shared/src/editor/themes.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,29 @@ import { EditorView } from '@codemirror/view'
22
import { vsCodeDark } from '@fsegurai/codemirror-theme-vscode-dark'
33
import { vsCodeLight } from '@fsegurai/codemirror-theme-vscode-light'
44

5+
// Prevent CodeMirror's scrollIntoView on focus by restoring scroll position
6+
// after CodeMirror performs its automatic scroll.
7+
const noScrollOnFocus = EditorView.domEventHandlers({
8+
focus(_event, _view) {
9+
const scrollDOM = _view.scrollDOM
10+
const { scrollTop, scrollLeft } = scrollDOM
11+
requestAnimationFrame(() => {
12+
scrollDOM.scrollTop = scrollTop
13+
scrollDOM.scrollLeft = scrollLeft
14+
})
15+
return false
16+
},
17+
})
18+
519
const customStyles = EditorView.theme({
20+
// 移除聚焦时的蓝色边框
21+
'&.cm-focused': {
22+
outline: `none`,
23+
},
24+
// 防止滚动链接效应
25+
'.cm-scroller': {
26+
overscrollBehavior: `contain`,
27+
},
628
// 装订线:垂直居中、无背景无边框无内边距
729
'.cm-gutterElement': {
830
display: `flex`,
@@ -37,11 +59,11 @@ const customStyles = EditorView.theme({
3759
})
3860

3961
export function lightTheme() {
40-
return [vsCodeLight, customStyles]
62+
return [vsCodeLight, customStyles, noScrollOnFocus]
4163
}
4264

4365
export function darkTheme() {
44-
return [vsCodeDark, customStyles]
66+
return [vsCodeDark, customStyles, noScrollOnFocus]
4567
}
4668

4769
// 根据主题模式获取主题扩展

0 commit comments

Comments
 (0)