merge #965: fix(editor): remember the edit scroll position across tab re-seating

This commit is contained in:
Menghuan1918 committed 2026-10-26 15:02:38 +08:00
commit ad078e4ea4
2 files changed
+108 -2

No files matched your search

+77 -2
View File
@@ -95,6 +95,28 @@ export function rememberPreviewScroll(scope: { sessionId: string }, path: string
export function previewScrollOf(scope: { sessionId: string }, path: string): number {
return previewScrollMemory.get(previewScrollKey(scope, path)) ?? 0
}
/** The edit-mode twin of {@link previewScrollMemory}: the CodeMirror scroller's
* own position, which a moved (detached + re-attached) tab body loses. Bounded
* the same way — a mounted-but-hidden tab body keeps its own scroller, so an
* unbounded map would grow with every document the session ever edited. */
const editScrollMemory = new Map<string, number>()
/** Remember one document's edit offset. See {@link rememberPreviewScroll} for
* why the write moves the key to the back of the eviction order. */
function rememberEditScroll(scope: { sessionId: string }, path: string, top: number): void {
const key = previewScrollKey(scope, path)
editScrollMemory.delete(key)
editScrollMemory.set(key, top)
for (const stale of editScrollMemory.keys()) {
if (editScrollMemory.size <= PREVIEW_SCROLL_CAP) break
editScrollMemory.delete(stale)
}
}
/** The remembered edit offset of one document (0 = none: open it at the top). */
function editScrollOf(scope: { sessionId: string }, path: string): number {
return editScrollMemory.get(previewScrollKey(scope, path)) ?? 0
}
/** Whether two spellings are the SAME document — byte-equal, or equal once
* line endings are normalized CRLF/CR → LF. Line endings are not content:
@@ -203,6 +225,11 @@ export function TextEditor(props: FileViewerProps) {
* from the module-level per-file memory so a full viewer rebuild
* (save-then-switch-to-preview reload) also keeps the position. */
const previewScrollRef = useRef(previewScrollOf(scope, path))
/** The edit surface's remembered scroll position (see {@link editScrollMemory}). */
const editScrollRef = useRef(editScrollOf(scope, path))
/** True while {@link restoreEditScroll} is writing, so the scroll event it
* causes is not mistaken for the user's own position. */
const restoringEditRef = useRef(false)
/** True while a programmatic restore is in flight; raw scroll events caused
* by the restore (or by the browser clamping a collapsed reload container
* to 0) must not overwrite the remembered position. */
@@ -269,6 +296,7 @@ export function TextEditor(props: FileViewerProps) {
// file's own entry (first open: none, so the preview starts at the top).
useEffect(() => {
previewScrollRef.current = previewScrollOf(scope, path)
editScrollRef.current = editScrollOf(scope, path)
}, [scope, path])
// Create the CodeMirror editor once the content is loaded. The view owns
@@ -374,7 +402,20 @@ export function TextEditor(props: FileViewerProps) {
})
const view = new CodeMirrorView({ state, parent: host })
viewRef.current = view
// Edit-mode scroll memory. The native sidebar re-seats a tab while it is
// being saved (the chip's dirty mark, the change gutter), and a scroller
// that is detached from the document comes back with `scrollTop` 0 — the
// one piece of view state the DOM does not carry across a move. Record the
// user's own position here; the restore paths below put it back.
const scroller = view.scrollDOM
const onScroll = (): void => {
if (restoringEditRef.current) return
editScrollRef.current = scroller.scrollTop
rememberEditScroll(scope, path, scroller.scrollTop)
}
scroller.addEventListener('scroll', onScroll, { passive: true })
return () => {
scroller.removeEventListener('scroll', onScroll)
view.destroy()
viewRef.current = null
themeCompRef.current = null
@@ -387,6 +428,36 @@ export function TextEditor(props: FileViewerProps) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [content, path])
/**
* Put the edit-mode scroll position back after the view was disturbed (a
* moved tab body, a reconfigured gutter, a collapsed container). Mirrors the
* preview's restore: a programmatic write is guarded so the scroll event it
* produces is not recorded as the user's own position, and a document that
* fits is left alone.
*/
const restoreEditScroll = (): void => {
const view = viewRef.current
if (view === null) return
const want = editScrollRef.current
if (want <= 0) return
const scroller = view.scrollDOM
if (scroller.scrollTop === want) return
if (scroller.scrollHeight <= scroller.clientHeight) return
restoringEditRef.current = true
scroller.scrollTop = want
const clear = (): void => { restoringEditRef.current = false }
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(clear)
else setTimeout(clear, 0)
}
// Save-time restore: `saving → saved` and the change-gutter refresh are the
// two edges that re-seat the tab body, and the edit surface has no reload to
// hide behind (unlike the preview, which reloads deliberately).
useLayoutEffect(() => {
if (mode !== 'edit') return
restoreEditScroll()
}, [saveState, gitKinds, mode])
// Native sidebar tabs stay mounted while another tab is active. If a file
// is opened while that host is hidden, CodeMirror can measure its viewport at
// zero and retain an empty virtualized viewport after the tab is revealed —
@@ -396,13 +467,17 @@ export function TextEditor(props: FileViewerProps) {
// and moving a node never changes its border box, so a ResizeObserver alone
// never fires for that path. An IntersectionObserver reports the reveal
// itself; the rAF follow-up covers a reveal landing in the mount's own frame,
// where CodeMirror's first measure may still have read a zero box.
// where CodeMirror's first measure may still have read a zero box. Each
// reveal also re-applies the remembered scroll position for the same reason.
useEffect(() => {
const host = hostRef.current
const view = viewRef.current
if (host === null || view === null) return
const measure = (): void => {
if (host.isConnected && host.offsetWidth > 0 && host.offsetHeight > 0) view.requestMeasure()
if (host.isConnected && host.offsetWidth > 0 && host.offsetHeight > 0) {
view.requestMeasure()
restoreEditScroll()
}
}
measure()
const frame = typeof requestAnimationFrame === 'function'
+31
View File
@@ -166,6 +166,37 @@ describe('TextEditor visibility recovery', () => {
expect(requestMeasure).not.toHaveBeenCalled()
})
it('restores the edit scroll position after the tab body is disturbed', () => {
// A save re-seats the tab body (dirty chip, change gutter) and a scroller
// that was detached comes back at scrollTop 0 — the position must survive.
const store = createSidebarStore()
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
act(() => { root!.render(createElement(TextEditor, props(store))) })
const editorHost = container.querySelector('[class*="editorCm"]') as HTMLDivElement
Object.defineProperties(editorHost, {
offsetWidth: { configurable: true, value: 480 },
offsetHeight: { configurable: true, value: 640 },
})
const scroller = container.querySelector('.cm-scroller') as HTMLElement
expect(scroller).not.toBeNull()
Object.defineProperties(scroller, {
scrollHeight: { configurable: true, value: 4000 },
clientHeight: { configurable: true, value: 640 },
})
// The user scrolls; the listener records the position.
scroller.scrollTop = 900
act(() => { scroller.dispatchEvent(new Event('scroll')) })
// The tab body is disturbed and the browser clamps the scroller to the top.
scroller.scrollTop = 0
const observer = instances.find(candidate => candidate.targets.includes(editorHost))
act(() => { observer!.trigger() })
expect(scroller.scrollTop).toBe(900)
})
it('disconnects the observer when the editor unmounts', () => {
const store = createSidebarStore()
container = document.createElement('div')