diff --git a/src/renderer/src/components/editor/CombinedDiffViewer.tsx b/src/renderer/src/components/editor/CombinedDiffViewer.tsx index 61dc1ffec..a206fa8c8 100644 --- a/src/renderer/src/components/editor/CombinedDiffViewer.tsx +++ b/src/renderer/src/components/editor/CombinedDiffViewer.tsx @@ -4,15 +4,17 @@ restore-on-remount caching, and scroll preservation. Splitting those pieces across smaller files would make the lifecycle edges harder to reason about and more error-prone than keeping the whole viewer flow together. */ /* oxlint-disable react-doctor/no-adjust-state-on-prop-change -- Why: diff entry changes must reset virtualizer measurement and generation state in lockstep with external scroll restoration. */ -import React, { useState, useEffect, useCallback, useRef, useLayoutEffect } from 'react' -import { useVirtualizer } from '@tanstack/react-virtual' +import React, { useState, useEffect, useCallback, useRef, useLayoutEffect, useMemo } from 'react' +import { elementScroll, useVirtualizer } from '@tanstack/react-virtual' import type { editor as monacoEditor } from 'monaco-editor' import { useAppStore } from '@/store' import { useVirtualizedScrollAnchor, + VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, type VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor' import { getVirtualizedScrollAnchorForOffset } from '@/hooks/virtualized-scroll-anchor-recording' +import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' import { joinPath } from '@/lib/path' import { detectLanguage } from '@/lib/language-detect' import { setWithLRU } from '@/lib/scroll-cache' @@ -293,6 +295,11 @@ export default function CombinedDiffViewer({ combinedDiffScrollAnchorCache.get(viewStateKey) ?? null ) const directScrollInputUntilRef = useRef(0) + const [programmaticScrollMarks] = useState(createProgrammaticScrollMarks) + // Why: a scroll event pinned at a shrunken max is a browser clamp, not user + // input; bumping this asks the anchor restore to re-pin the viewport. + const [clampRestoreCount, setClampRestoreCount] = useState(0) + const lastScrollHeightRef = useRef(0) const activeScrollbarDragCleanupRef = useRef(null) const loadedIndicesRef = useRef>(new Set()) const loadingIndicesRef = useRef>(new Set()) @@ -840,6 +847,18 @@ export default function CombinedDiffViewer({ }, overscan: COMBINED_DIFF_OVERSCAN, initialOffset: () => scrollOffsetRef.current, + // Why: every scroll the virtualizer issues (scrollToIndex, measurement + // corrections) must be marked so scroll events can be attributed to the + // user only when this code didn't cause them. + scrollToFn: (offset, options, instance) => { + const target = offset + (options.adjustments ?? 0) + // Why: a write to the current position emits no scroll event; marking + // it would leave a stale mark that can claim a later user scroll. + if (instance.scrollElement?.scrollTop !== target) { + programmaticScrollMarks.mark(target) + } + elementScroll(offset, options, instance) + }, getItemKey: (index) => { const section = sections[index] if (!section) { @@ -906,7 +925,8 @@ export default function CombinedDiffViewer({ offset: Math.min( firstVisible.rect.height, Math.max(0, containerRect.top - firstVisible.rect.top) - ) + ), + scrollTop: container.scrollTop } scrollAnchorRef.current = anchor latestDomScrollAnchorRef.current = anchor @@ -930,14 +950,29 @@ export default function CombinedDiffViewer({ [recordCombinedDiffDomScrollAnchor, writeCombinedDiffScrollAnchor] ) + // Why: restore only on structural changes (rows added/removed/collapsed, + // remount, layout-mode flips, clamp recovery). Measurement churn during + // scrolling is compensated by the virtualizer itself; restoring on it wrote + // scrollTop against active wheel input whenever main-thread jank outlived + // the direct-input window. + const combinedDiffRestoreSignal = useMemo( + () => + `${generation}|${sideBySide ? 'sbs' : 'inline'}|${clampRestoreCount}|${sections + .map((section) => `${section.key}:${section.collapsed ? 'c' : 'e'}`) + .join(',')}`, + [clampRestoreCount, generation, sections, sideBySide] + ) + useVirtualizedScrollAnchor({ anchorRef: scrollAnchorRef, getItemElementKey: getCombinedDiffSectionElementKey, getRowKey: getCombinedDiffSectionKey, hasDirectScrollInput, itemElementSelector: '[data-combined-diff-section-row]', + programmaticScrollMarks, recordAnchorOnCleanup: false, recordAnchorOnScroll: false, + restoreSignal: combinedDiffRestoreSignal, rows: sections, scrollElementRef: scrollContainerRef, shouldSkipRestore: hasDirectScrollInput, @@ -1001,6 +1036,13 @@ export default function CombinedDiffViewer({ scrollAnchorRef.current = null latestDomScrollAnchorRef.current = null virtualizer.scrollToIndex(index, { align: 'start' }) + // Why: this jump is marked programmatic, so no scroll event records + // an anchor for it; snapshot the destination once layout settles. + window.requestAnimationFrame(() => { + scrollContainerRef.current?.dispatchEvent( + new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT) + ) + }) } }) if (navigatedIndex !== null) { @@ -1336,16 +1378,35 @@ export default function CombinedDiffViewer({ scrollTop }) } - const handleScroll = (): void => { - if (!hasDirectScrollInput()) { + lastScrollHeightRef.current = container.scrollHeight + const handleScroll = (event: Event): void => { + const scrollTop = container.scrollTop + const scrollHeight = container.scrollHeight + const maxScrollTop = Math.max(0, scrollHeight - container.clientHeight) + const shrank = scrollHeight < lastScrollHeightRef.current - 1 + lastScrollHeightRef.current = scrollHeight + if (programmaticScrollMarks.consume(event, scrollTop, maxScrollTop)) { updateCombinedDiffScrollbar() return } - recordCombinedDiffVirtualScrollAnchor(container.scrollTop) + if (shrank && scrollTop >= maxScrollTop - 1 && scrollOffsetRef.current > maxScrollTop + 1) { + // Why: pinned at a max that just shrank, coming from an offset the new + // range can't reach, is the browser clamping the viewport, not user + // input (a user scroll to the bottom starts from an in-range offset); + // ask the anchor restore to re-pin instead of recording the clamped + // position as intentional. + setClampRestoreCount((count) => count + 1) + updateCombinedDiffScrollbar() + return + } + // Why: any unmarked scroll is the user's (wheel, momentum, keyboard, + // scrollbar drag) — including events whose input never reached the + // wheel handler because the main thread was janked past its window. + recordCombinedDiffVirtualScrollAnchor(scrollTop) updateCachedScrollPosition({ recordDomAnchor: false, scheduleSettled: true, - scrollTop: container.scrollTop, + scrollTop, writeAnchor: true }) } @@ -1376,6 +1437,7 @@ export default function CombinedDiffViewer({ entrySignature, hasDirectScrollInput, persistCombinedDiffScrollAnchor, + programmaticScrollMarks, recordCombinedDiffVirtualScrollAnchor, sections.length, updateCombinedDiffScrollbar, diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index 34725365a..a1542323e 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -1998,6 +1998,9 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp // TanStack's default correction writes scrollTop in that path, which feels // like rubber-banding. Structural mutations still use our explicit anchor // restore after direct scroll input has settled. + // TODO(scroll-origin-migration): this wall-clock suppression misclassifies + // under main-thread jank; migrate to programmaticScrollMarks + restoreSignal + // (see CombinedDiffViewer) once that wiring is validated for the sidebar. virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => shouldAdjustWorktreeSidebarMeasuredRowScroll({ isScrolling: instance.isScrolling, diff --git a/src/renderer/src/hooks/programmatic-scroll-marks.test.ts b/src/renderer/src/hooks/programmatic-scroll-marks.test.ts new file mode 100644 index 000000000..9b386b4f4 --- /dev/null +++ b/src/renderer/src/hooks/programmatic-scroll-marks.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' +import { createProgrammaticScrollMarks } from './programmatic-scroll-marks' + +const scrollEvent = (): Event => new Event('scroll') + +describe('createProgrammaticScrollMarks', () => { + it('classifies an event matching a marked target as programmatic', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(500) + expect(marks.consume(scrollEvent(), 500, 10_000)).toBe(true) + }) + + it('matches within the epsilon for fractional scroll positions', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(500) + expect(marks.consume(scrollEvent(), 501.6, 10_000)).toBe(true) + }) + + it('classifies an unmarked scroll as user input', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(500) + expect(marks.consume(scrollEvent(), 660, 10_000)).toBe(false) + }) + + it('treats a clamped landing of an out-of-range write as programmatic', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(12_000) + expect(marks.consume(scrollEvent(), 8_000, 8_000)).toBe(true) + }) + + it('does not treat a user scroll to the bottom as a clamped write', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(4_000) + expect(marks.consume(scrollEvent(), 8_000, 8_000)).toBe(false) + }) + + it('returns the same classification for the same event across listeners', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(500) + const event = scrollEvent() + expect(marks.consume(event, 500, 10_000)).toBe(true) + // Second listener on the same event: mark already consumed, cache must answer. + expect(marks.consume(event, 500, 10_000)).toBe(true) + // A fresh event at the same offset is a new scroll and no mark remains. + expect(marks.consume(scrollEvent(), 500, 10_000)).toBe(false) + }) + + it('drops older marks whose events were coalesced away', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(300) + marks.mark(700) + expect(marks.consume(scrollEvent(), 700, 10_000)).toBe(true) + // The 300 mark predates the matched write; it must not claim a later user scroll. + expect(marks.consume(scrollEvent(), 300, 10_000)).toBe(false) + }) + + it('consumes marks independently when events arrive in write order', () => { + const marks = createProgrammaticScrollMarks() + marks.mark(300) + marks.mark(700) + expect(marks.consume(scrollEvent(), 300, 10_000)).toBe(true) + expect(marks.consume(scrollEvent(), 700, 10_000)).toBe(true) + expect(marks.consume(scrollEvent(), 700, 10_000)).toBe(false) + }) + + it('bounds the pending queue', () => { + const marks = createProgrammaticScrollMarks() + for (let i = 0; i < 40; i++) { + marks.mark(i * 1_000) + } + // Oldest marks were evicted; only the most recent 16 remain matchable. + expect(marks.consume(scrollEvent(), 0, 100_000)).toBe(false) + expect(marks.consume(scrollEvent(), 39_000, 100_000)).toBe(true) + }) +}) diff --git a/src/renderer/src/hooks/programmatic-scroll-marks.ts b/src/renderer/src/hooks/programmatic-scroll-marks.ts new file mode 100644 index 000000000..b8aed0aa0 --- /dev/null +++ b/src/renderer/src/hooks/programmatic-scroll-marks.ts @@ -0,0 +1,72 @@ +const SCROLL_MARK_MATCH_EPSILON = 2 +// Why: a bounded queue is the staleness limit. Wall-clock expiry would +// reintroduce the timing assumptions this module exists to remove. Known +// accepted window: a marked no-op write emits no scroll event, so its target +// can linger and claim a later user scroll within the epsilon; the bound and +// splice-on-match keep that window narrow. +const MAX_PENDING_SCROLL_MARKS = 16 + +export type ProgrammaticScrollMarks = { + /** Register the target offset of a scroll write this code is about to make. */ + mark: (targetOffset: number) => void + /** + * Classify a scroll event: true when it matches a registered write (or its + * browser-clamped landing spot). Idempotent per Event so multiple listeners + * on the same element agree on the classification. + */ + consume: (event: Event, scrollOffset: number, maxScrollOffset: number) => boolean +} + +/** + * Distinguishes self-initiated scrolls from user scrolls by explicit marks + * instead of wall-clock input windows. The system always knows when it writes + * scrollTop; it can never reliably know when the user scrolled — under + * main-thread jank, input events dispatch late and time-window heuristics + * misclassify exactly when it matters. + */ +export function createProgrammaticScrollMarks(): ProgrammaticScrollMarks { + const pendingTargets: number[] = [] + const classifiedEvents = new WeakMap() + + const matchesTarget = ( + targetOffset: number, + scrollOffset: number, + maxScrollOffset: number + ): boolean => { + if (Math.abs(scrollOffset - targetOffset) <= SCROLL_MARK_MATCH_EPSILON) { + return true + } + // Why: a write past the scrollable range lands at the clamped max, not at + // its target; that landing is still our scroll, not the user's. + return ( + targetOffset > maxScrollOffset + SCROLL_MARK_MATCH_EPSILON && + scrollOffset >= maxScrollOffset - SCROLL_MARK_MATCH_EPSILON + ) + } + + return { + mark: (targetOffset: number): void => { + pendingTargets.push(targetOffset) + if (pendingTargets.length > MAX_PENDING_SCROLL_MARKS) { + pendingTargets.shift() + } + }, + consume: (event: Event, scrollOffset: number, maxScrollOffset: number): boolean => { + const cached = classifiedEvents.get(event) + if (cached !== undefined) { + return cached + } + const matchedIndex = pendingTargets.findIndex((targetOffset) => + matchesTarget(targetOffset, scrollOffset, maxScrollOffset) + ) + if (matchedIndex !== -1) { + // Why: scroll events arrive in write order; older marks whose events + // were coalesced away must not linger to claim a later user scroll. + pendingTargets.splice(0, matchedIndex + 1) + } + const isProgrammatic = matchedIndex !== -1 + classifiedEvents.set(event, isProgrammatic) + return isProgrammatic + } + } +} diff --git a/src/renderer/src/hooks/useVirtualizedScrollAnchor.listener-deps.test.ts b/src/renderer/src/hooks/useVirtualizedScrollAnchor.listener-deps.test.ts index a30b3f97c..bb8755760 100644 --- a/src/renderer/src/hooks/useVirtualizedScrollAnchor.listener-deps.test.ts +++ b/src/renderer/src/hooks/useVirtualizedScrollAnchor.listener-deps.test.ts @@ -69,7 +69,8 @@ describe('useVirtualizedScrollAnchor listener effect dependencies', () => { // Why: cleanup records the current anchor. If rows are dependencies, a // delete reruns cleanup after mutation and overwrites the pre-delete anchor. - expect(initialDeps).toEqual([scrollElementRef, scrollOffsetRef]) + // Only stable refs are allowed here. + expect(initialDeps).toEqual([anchorRef, scrollElementRef, scrollOffsetRef]) expect(nextDeps).toEqual(initialDeps) }) @@ -113,7 +114,9 @@ describe('useVirtualizedScrollAnchor listener effect dependencies', () => { harness.effects[1]?.effect() expect(scrollElementRef.current.scrollTop).toBe(4116) - expect(anchorRef.current).toEqual({ key: 'row-1', offset: 3358 }) + // Why: the anchor identity is preserved through the transitional restore; + // only its source scrollTop is refreshed to the restored offset. + expect(anchorRef.current).toEqual({ key: 'row-1', offset: 3358, scrollTop: 4116 }) }) it('can ignore generic scroll anchor recording while preserving the saved anchor', async () => { diff --git a/src/renderer/src/hooks/useVirtualizedScrollAnchor.marks-restore-signal.test.ts b/src/renderer/src/hooks/useVirtualizedScrollAnchor.marks-restore-signal.test.ts new file mode 100644 index 000000000..0e7ec50cf --- /dev/null +++ b/src/renderer/src/hooks/useVirtualizedScrollAnchor.marks-restore-signal.test.ts @@ -0,0 +1,432 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createProgrammaticScrollMarks } from './programmatic-scroll-marks' + +function createReactHookHarness() { + const refs: { current: unknown }[] = [] + const effects: { + deps: readonly unknown[] | undefined + effect: () => void | (() => void) + }[] = [] + let refIndex = 0 + + return { + beginRender: () => { + refIndex = 0 + effects.length = 0 + }, + effects, + react: { + useCallback: unknown>(callback: T): T => callback, + useLayoutEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => { + effects.push({ deps, effect }) + }, + useMemo: (factory: () => T): T => factory(), + useRef: (initialValue: T): { current: T } => { + const index = refIndex + refIndex += 1 + refs[index] ??= { current: initialValue } + return refs[index] as { current: T } + } + } + } +} + +type FakeRowElement = { + getBoundingClientRect: () => { bottom: number; height: number; top: number } + isConnected: boolean + key: string +} + +function createScrollElement({ + clientHeight = 880, + rowElements = [] as FakeRowElement[], + scrollHeight = 30_000, + scrollTop = 0 +}) { + const scrollHandlers: ((event: Event) => void)[] = [] + const el = { + addEventListener: vi.fn((eventName: string, handler: (event: Event) => void) => { + if (eventName === 'scroll') { + scrollHandlers.push(handler) + } + }), + clientHeight, + getBoundingClientRect: () => ({ bottom: clientHeight, top: 0 }), + querySelectorAll: vi.fn(() => rowElements), + removeEventListener: vi.fn(), + scrollHeight, + scrollTop + } + return { + el, + emitScroll: (top: number): void => { + el.scrollTop = top + const event = new Event('scroll') + scrollHandlers.forEach((handler) => handler(event)) + } + } +} + +const anchoredRowElement = (key: string, top: number): FakeRowElement => ({ + getBoundingClientRect: () => ({ bottom: top + 4_000, height: 4_000, top }), + isConnected: true, + key +}) + +describe('useVirtualizedScrollAnchor with marks + restoreSignal', () => { + afterEach(() => { + vi.doUnmock('react') + vi.resetModules() + }) + + const loadHook = async () => { + const harness = createReactHookHarness() + vi.doMock('react', () => harness.react) + const { useVirtualizedScrollAnchor } = await import('./useVirtualizedScrollAnchor') + return { harness, useVirtualizedScrollAnchor } + } + + const virtualizerWithRow1 = () => ({ + getVirtualItems: () => [ + { index: 0, start: 0, end: 758 }, + { index: 1, start: 758, end: 4_512 } + ], + isScrolling: false, + scrollToIndex: vi.fn() + }) + + it('does not re-attempt restore on measurement churn when the signal is unchanged', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + // Row-1 already sits exactly at the anchored offset, so the first run confirms. + const { el } = createScrollElement({ + rowElements: [anchoredRowElement('row-1', -3_358)], + scrollTop: 746 + }) + const anchorRef = { current: { key: 'row-1', offset: 3_358, scrollTop: 746 } } + const virtualizer = virtualizerWithRow1() + + const render = (restoreSignal: string, totalSize: number) => { + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getItemElementKey: (element: FakeRowElement) => element.key, + getRowKey: (row: string) => row, + itemElementSelector: '[data-row]', + programmaticScrollMarks: createProgrammaticScrollMarks(), + recordAnchorOnScroll: false, + restoreSignal, + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 746 }, + totalSize, + virtualizer + } as never) + harness.effects[1]?.effect() + } + + render('signal-a', 30_000) + expect(el.querySelectorAll).toHaveBeenCalled() + const attemptsAfterConfirm = el.querySelectorAll.mock.calls.length + + // Measurement churn: totalSize changed, structural signal did not. + render('signal-a', 31_500) + expect(el.querySelectorAll.mock.calls.length).toBe(attemptsAfterConfirm) + expect(virtualizer.scrollToIndex).not.toHaveBeenCalled() + }) + + it('lets the user position win when the viewport moved after the anchor was recorded', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const { el } = createScrollElement({ + rowElements: [anchoredRowElement('row-1', -3_358)], + // The user (or compositor) scrolled beyond where the anchor was recorded. + scrollTop: 906 + }) + const anchorRef = { current: { key: 'row-1', offset: 3_358, scrollTop: 746 } } + const virtualizer = virtualizerWithRow1() + + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getItemElementKey: (element: FakeRowElement) => element.key, + getRowKey: (row: string) => row, + itemElementSelector: '[data-row]', + programmaticScrollMarks: createProgrammaticScrollMarks(), + recordAnchorOnScroll: false, + restoreSignal: 'signal-a', + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 746 }, + totalSize: 30_000, + virtualizer + } as never) + harness.effects[1]?.effect() + + expect(el.scrollTop).toBe(906) + expect(el.querySelectorAll).not.toHaveBeenCalled() + expect(virtualizer.scrollToIndex).not.toHaveBeenCalled() + }) + + it('still restores when a browser clamp explains the divergence', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + // Content above shrank: the anchor points past the new max and the browser + // clamped the viewport to the bottom. + const { el } = createScrollElement({ + rowElements: [], + scrollHeight: 2_000, + scrollTop: 1_120 + }) + const anchorRef = { current: { key: 'row-1', offset: 3_358, scrollTop: 5_000 } } + const virtualizer = virtualizerWithRow1() + + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getItemElementKey: (element: FakeRowElement) => element.key, + getRowKey: (row: string) => row, + itemElementSelector: '[data-row]', + programmaticScrollMarks: createProgrammaticScrollMarks(), + recordAnchorOnScroll: false, + restoreSignal: 'signal-a', + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 5_000 }, + totalSize: 2_000, + virtualizer + } as never) + harness.effects[1]?.effect() + + expect(el.querySelectorAll).toHaveBeenCalled() + }) + + it('yields the mount restore to an unmarked user scroll instead of rewriting it', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const { el, emitScroll } = createScrollElement({ scrollTop: 0 }) + const anchorRef = { current: null } + + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getRowKey: (row: string) => row, + programmaticScrollMarks: createProgrammaticScrollMarks(), + recordAnchorOnScroll: false, + restoreSignal: 'signal-a', + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 4_000 }, + totalSize: 30_000, + virtualizer: virtualizerWithRow1() + } as never) + harness.effects[0]?.effect() + // The mount write landed and was marked. + expect(el.scrollTop).toBe(4_000) + + // An unmarked scroll means the user took over — even without any wheel + // event reaching a direct-input tracker (the jank case). + emitScroll(4_200) + expect(el.scrollTop).toBe(4_200) + }) + + it('keeps structural restores alive after its own marked writes move the viewport', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const marks = createProgrammaticScrollMarks() + const rowElement = anchoredRowElement('row-1', -3_358) + const { el, emitScroll } = createScrollElement({ + rowElements: [rowElement], + scrollTop: 746 + }) + const anchorRef = { current: { key: 'row-1', offset: 3_358, scrollTop: 746 } } + const scrollOffsetRef = { current: 746 } + const virtualizer = virtualizerWithRow1() + + const render = (restoreSignal: string) => { + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getItemElementKey: (element: FakeRowElement) => element.key, + getRowKey: (row: string) => row, + itemElementSelector: '[data-row]', + programmaticScrollMarks: marks, + recordAnchorOnScroll: false, + restoreSignal, + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef, + totalSize: 30_000, + virtualizer + } as never) + harness.effects[0]?.effect() + harness.effects[1]?.effect() + } + + render('signal-a') + // A virtualizer size-adjustment correction (marked) moves the viewport. + marks.mark(946) + emitScroll(946) + // Bookkeeping followed the marked write, so the divergence gate must not + // read it as user input. + expect(anchorRef.current.scrollTop).toBe(946) + expect(scrollOffsetRef.current).toBe(946) + + // A structural change now still restores instead of being dropped. + const attemptsBefore = el.querySelectorAll.mock.calls.length + render('signal-b') + expect(el.querySelectorAll.mock.calls.length).toBeGreaterThan(attemptsBefore) + }) + + it('retries a signal-change restore that was skipped during direct input', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const { el } = createScrollElement({ + rowElements: [anchoredRowElement('row-1', -3_358)], + scrollTop: 746 + }) + const anchorRef = { current: { key: 'row-1', offset: 3_358, scrollTop: 746 } } + const virtualizer = virtualizerWithRow1() + let directInput = true + + const render = (restoreSignal: string, totalSize: number) => { + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getItemElementKey: (element: FakeRowElement) => element.key, + getRowKey: (row: string) => row, + itemElementSelector: '[data-row]', + programmaticScrollMarks: createProgrammaticScrollMarks(), + recordAnchorOnScroll: false, + restoreSignal, + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 746 }, + shouldSkipRestore: () => directInput, + totalSize, + virtualizer + } as never) + harness.effects[1]?.effect() + } + + // Signal changes while wheel input is active: restore is skipped. + render('signal-a', 30_000) + expect(el.querySelectorAll).not.toHaveBeenCalled() + + // Input settled; a later measurement tick must still run the owed restore + // even though the signal did not change again. + directInput = false + render('signal-a', 31_000) + expect(el.querySelectorAll).toHaveBeenCalled() + }) + + it('does not stay armed when the anchor row and all fallbacks are gone', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const { el } = createScrollElement({ + rowElements: [anchoredRowElement('row-1', -3_358)], + scrollTop: 746 + }) + const anchorRef = { current: { key: 'row-gone', offset: 3_358, scrollTop: 746 } } + const virtualizer = virtualizerWithRow1() + + const render = (rows: readonly string[], totalSize: number) => { + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getItemElementKey: (element: FakeRowElement) => element.key, + getRowKey: (row: string) => row, + itemElementSelector: '[data-row]', + programmaticScrollMarks: createProgrammaticScrollMarks(), + recordAnchorOnScroll: false, + restoreSignal: 'signal-a', + rows, + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 746 }, + totalSize, + virtualizer + } as never) + harness.effects[1]?.effect() + } + + // Signal change arms a restore, but the anchor resolves to no row. + render(['row-0', 'row-2'], 30_000) + expect(el.querySelectorAll).not.toHaveBeenCalled() + + // The arm must not leak: a later measurement tick with an unchanged + // signal stays out of restore even though the anchor is now resolvable + // (in production, resolvability changes always change the signal too). + render(['row-0', 'row-gone'], 31_000) + expect(el.querySelectorAll).not.toHaveBeenCalled() + expect(virtualizer.scrollToIndex).not.toHaveBeenCalled() + }) + + it('does not treat a browser clamp during the mount restore as user takeover', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const marks = createProgrammaticScrollMarks() + const { el, emitScroll } = createScrollElement({ scrollHeight: 3_000, scrollTop: 0 }) + const anchorRef = { current: null } + const scrollOffsetRef = { current: 4_000 } + + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getRowKey: (row: string) => row, + programmaticScrollMarks: marks, + recordAnchorOnScroll: false, + restoreSignal: 'signal-a', + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef, + totalSize: 3_000, + virtualizer: virtualizerWithRow1() + } as never) + harness.effects[0]?.effect() + + // The mount write's own clamped landing is classified programmatic. + emitScroll(2_120) + // Content above shrank further: the browser clamps again with no mark. + el.scrollHeight = 2_000 + emitScroll(1_120) + // Not a takeover: no anchor was recorded for the clamped position. + expect(anchorRef.current).toBeNull() + + // Content finished loading; a marked correction wakes the restore and the + // persisted offset is finally reachable. + el.scrollHeight = 30_000 + marks.mark(1_500) + emitScroll(1_500) + expect(el.scrollTop).toBe(4_000) + expect(scrollOffsetRef.current).toBe(4_000) + }) + + it('keeps rewriting toward the target while its own marked writes settle', async () => { + const { harness, useVirtualizedScrollAnchor } = await loadHook() + const marks = createProgrammaticScrollMarks() + const { el, emitScroll } = createScrollElement({ scrollTop: 0 }) + const anchorRef = { current: null } + + harness.beginRender() + // oxlint-disable-next-line react-hooks/rules-of-hooks -- test harness mocks React's hook dispatcher directly. + useVirtualizedScrollAnchor({ + anchorRef, + getRowKey: (row: string) => row, + programmaticScrollMarks: marks, + recordAnchorOnScroll: false, + restoreSignal: 'signal-a', + rows: ['row-0', 'row-1'], + scrollElementRef: { current: el }, + scrollOffsetRef: { current: 4_000 }, + totalSize: 30_000, + virtualizer: virtualizerWithRow1() + } as never) + harness.effects[0]?.effect() + + // A marked write (e.g. a virtualizer correction) landed elsewhere while + // restoring; the restore should push back toward its target. + marks.mark(3_500) + emitScroll(3_500) + expect(el.scrollTop).toBe(4_000) + }) +}) diff --git a/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts b/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts index 7dd9764e7..4ffcdf7ba 100644 --- a/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts +++ b/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts @@ -7,16 +7,22 @@ import { type RefObject } from 'react' import type { Virtualizer } from '@tanstack/react-virtual' -import { shouldCancelVirtualizedScrollOffsetRestore } from './virtualizedScrollOffsetRestore' import { findVirtualizedDomScrollAnchor, getVirtualizedScrollAnchorForOffset } from './virtualized-scroll-anchor-recording' +import { createVirtualizedScrollAnchorListener } from './virtualized-scroll-anchor-listener' +import { runVirtualizedScrollAnchorRestore } from './virtualized-scroll-anchor-restore' +import type { ProgrammaticScrollMarks } from './programmatic-scroll-marks' export type VirtualizedScrollAnchor = { fallbackKeys?: readonly string[] key: string offset: number + // Why: the scroll offset this anchor was derived from lets restore detect + // that the viewport moved (user scroll or clamp) after the anchor was + // recorded. Optional: anchors persisted before this field existed lack it. + scrollTop?: number } | null export const VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT = 'orca-record-virtualized-scroll-anchor' const RECORD_ANCHOR_SCROLL_IDLE_DELAY_MS = 150 @@ -31,10 +37,20 @@ type UseVirtualizedScrollAnchorOptions< getRowKey: (row: TRow) => string hasDirectScrollInput?: () => boolean itemElementSelector?: string + // Why: marks classify scroll events by origin (self-initiated vs user) + // instead of wall-clock input windows, which misclassify under main-thread + // jank. Callers opting in must route every programmatic scroll they issue + // through marks (including the virtualizer's scrollToFn). + programmaticScrollMarks?: ProgrammaticScrollMarks recordAnchorOnCleanup?: boolean // Why: some callers record user scroll anchors outside this hook; passive // programmatic scroll events during remount must not teach them a transient row. recordAnchorOnScroll?: boolean + // Why: when provided, anchor restore runs only when this value changes + // (structural row changes) or while a prior restore is still converging — + // not on every totalSize/isScrolling tick. Measurement-driven shifts are the + // virtualizer's own scroll-adjustment job. + restoreSignal?: string rows: readonly TRow[] scrollElementRef: RefObject scrollOffsetRef: MutableRefObject @@ -61,8 +77,10 @@ export function useVirtualizedScrollAnchor< getRowKey, hasDirectScrollInput, itemElementSelector, + programmaticScrollMarks, recordAnchorOnCleanup = true, recordAnchorOnScroll = true, + restoreSignal, rows, scrollElementRef, scrollOffsetRef, @@ -137,6 +155,13 @@ export function useVirtualizedScrollAnchor< recordAnchorOnCleanupRef.current = recordAnchorOnCleanup const recordAnchorOnScrollRef = useRef(recordAnchorOnScroll) recordAnchorOnScrollRef.current = recordAnchorOnScroll + const programmaticScrollMarksRef = useRef(programmaticScrollMarks) + programmaticScrollMarksRef.current = programmaticScrollMarks + const prevRestoreSignalRef = useRef(undefined) + // Why: true while a restore has written toward the anchor but the anchored + // row's position is not yet confirmed; re-arms the restore effect across + // totalSize ticks until it converges or the user scrolls. + const pendingRestoreRef = useRef(false) useLayoutEffect(() => { const el = scrollElementRef.current @@ -144,12 +169,6 @@ export function useVirtualizedScrollAnchor< return } - const targetOffset = scrollOffsetRef.current - let restoring = targetOffset > 0 - if (restoring) { - el.scrollTop = targetOffset - } - let frameId: number | null = null let idleTimerId: number | null = null const cancelScheduledRecord = (): void => { @@ -179,53 +198,31 @@ export function useVirtualizedScrollAnchor< scrollOffsetRef.current = el.scrollTop recordScrollAnchorRef.current(el.scrollTop) } - const onScroll = (): void => { - if ( - shouldCancelVirtualizedScrollOffsetRestore({ - hasDirectScrollInput: hasDirectScrollInputRef.current, - restoring - }) - ) { - // Why: direct wheel/touch input means the user has taken control of the - // viewport. Treat the current offset as intentional instead of snapping - // back to a stale persisted offset while restoration is still pending. - restoring = false - recordCurrentAnchor() - return - } - if (restoring) { - // Why: during a fresh virtualizer mount, total height may still be - // estimate-based. Avoid persisting a browser-clamped offset as the - // user's real position until the intended offset is reachable. - if (el.scrollTop === targetOffset) { - restoring = false - if (recordAnchorOnScrollRef.current) { - recordCurrentAnchor() - } else { - scrollOffsetRef.current = el.scrollTop - } - return + const onScroll = createVirtualizedScrollAnchorListener({ + el, + getHasDirectScrollInput: () => hasDirectScrollInputRef.current, + getMarks: () => programmaticScrollMarksRef.current, + getRecordAnchorOnScroll: () => recordAnchorOnScrollRef.current, + onProgrammaticScroll: (scrollTop) => { + // Why: our own settled writes must keep the divergence bookkeeping in + // sync, or the restore gate reads them as user scrolling and drops + // the next structural restore. + scrollOffsetRef.current = scrollTop + const anchor = anchorRef.current + if (anchor && anchor.scrollTop !== undefined) { + anchor.scrollTop = scrollTop } - if (el.scrollHeight - el.clientHeight >= targetOffset) { - el.scrollTop = targetOffset - if (el.scrollTop === targetOffset) { - restoring = false - if (recordAnchorOnScrollRef.current) { - recordCurrentAnchor() - } else { - scrollOffsetRef.current = el.scrollTop - } - } - } - return - } - if (!recordAnchorOnScrollRef.current) { - return - } - scrollOffsetRef.current = el.scrollTop - recordVirtualScrollAnchorRef.current(el.scrollTop) - scheduleRecordAnchor() - } + }, + pendingRestoreRef, + recordCurrentAnchor, + recordUserScroll: (scrollTop) => { + scrollOffsetRef.current = scrollTop + recordVirtualScrollAnchorRef.current(scrollTop) + scheduleRecordAnchor() + }, + targetOffset: scrollOffsetRef.current, + scrollOffsetRef + }) el.addEventListener('scroll', onScroll, { passive: true }) el.addEventListener(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, recordCurrentAnchor) @@ -238,7 +235,9 @@ export function useVirtualizedScrollAnchor< el.removeEventListener(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, recordCurrentAnchor) el.removeEventListener('scroll', onScroll) } - }, [scrollElementRef, scrollOffsetRef]) + // Why: only stable refs may appear here; row-derived values would rerun + // cleanup after a delete and overwrite the pre-delete anchor. + }, [anchorRef, scrollElementRef, scrollOffsetRef]) useLayoutEffect(() => { const anchor = anchorRef.current @@ -246,6 +245,33 @@ export function useVirtualizedScrollAnchor< if (!anchor || !el) { return } + if (restoreSignal !== undefined) { + const signalChanged = prevRestoreSignalRef.current !== restoreSignal + prevRestoreSignalRef.current = restoreSignal + if (!signalChanged && !pendingRestoreRef.current) { + // Why: no structural row change and no restore mid-convergence. Pure + // measurement churn is compensated by the virtualizer's own scroll + // adjustment; restoring here would fight concurrent user scrolling. + return + } + if (anchor.scrollTop !== undefined) { + const maxScrollTop = Math.max(0, el.scrollHeight - el.clientHeight) + const clampExplained = + anchor.scrollTop > maxScrollTop + 1 && el.scrollTop >= maxScrollTop - 2 + if (Math.abs(el.scrollTop - anchor.scrollTop) > 1 && !clampExplained) { + // Why: the viewport moved after this anchor was recorded and no + // browser clamp explains it — the user scrolled. Their position + // wins; restoring would undo their input. + pendingRestoreRef.current = false + return + } + } + // Why: armed before the skip guards below, so a restore owed to a + // signal change survives being skipped during active input and retries + // on the next tick instead of being silently consumed. User scrolls + // disarm it via the scroll listener. + pendingRestoreRef.current = true + } if (virtualizer.isScrolling && hasDirectScrollInputRef.current?.() === true) { // Why: remeasurement during wheel scrolling can change totalSize. Restoring // the anchor in that window writes scrollTop and fights the user's wheel. @@ -256,89 +282,24 @@ export function useVirtualizedScrollAnchor< return } - const resolvedKey = rowIndexByKey.has(anchor.key) - ? anchor.key - : anchor.fallbackKeys?.find((key) => rowIndexByKey.has(key)) - if (!resolvedKey) { - return - } - const index = rowIndexByKey.get(resolvedKey) - if (index === undefined) { - return - } - const offset = resolvedKey === anchor.key ? anchor.offset : 0 - - const restoreFromDomElement = (): boolean => { - if (!itemElementSelector || !getItemElementKey) { - return false - } - const element = - Array.from(el.querySelectorAll(itemElementSelector)).find( - (candidate) => getItemElementKey(candidate) === resolvedKey && candidate.isConnected - ) ?? null - if (!element) { - return false - } - const scrollRect = el.getBoundingClientRect() - const rect = element.getBoundingClientRect() - const desiredTop = scrollRect.top - offset - const delta = rect.top - desiredTop - if (Math.abs(delta) > 1) { - // Why: this scroll write is still part of restore; keep the target - // anchor until a later layout confirms the intended row is in place. - el.scrollTop += delta - scrollOffsetRef.current = el.scrollTop - return true - } - scrollOffsetRef.current = el.scrollTop - recordScrollAnchor(el.scrollTop) - return true - } - - const restoreFromMeasuredItem = (): boolean => { - const item = virtualizer.getVirtualItems().find((candidate) => candidate.index === index) - if (!item) { - return false - } - const maxScrollTop = Math.max(0, el.scrollHeight - el.clientHeight) - const nextScrollTop = Math.min(maxScrollTop, Math.max(0, item.start + offset)) - if (Math.abs(el.scrollTop - nextScrollTop) > 1) { - el.scrollTop = nextScrollTop - } - // Why: measured fallback can run while TanStack's virtual window is - // transitional, so recording here can replace the target with a wrong row. - scrollOffsetRef.current = el.scrollTop - return true - } - - if (restoreFromDomElement()) { - return - } - - // Why: right after a delete the virtualizer can briefly render the wrong - // window, so the anchor row's DOM node isn't mounted yet even though the - // virtualizer still has its measured slot. Pin from that measured start - // (preserving the within-row offset) before falling back to scrollToIndex, - // whose align:'start' snaps the row to the viewport top and visibly jumps. - if (restoreFromMeasuredItem()) { - return - } - - // Why: the anchored row is outside the virtualizer's current window — no - // DOM node and no measured slot. Bring it in, then apply the within-row - // offset once TanStack Virtual has mounted and measured that row. - virtualizer.scrollToIndex(index, { align: 'start' }) - const frameId = window.requestAnimationFrame(() => { - if (!restoreFromDomElement()) { - restoreFromMeasuredItem() - } + return runVirtualizedScrollAnchorRestore({ + anchor, + el, + getItemElementKey, + itemElementSelector, + pendingRestoreRef, + programmaticScrollMarks: programmaticScrollMarksRef.current, + recordScrollAnchor, + rowIndexByKey, + scrollOffsetRef, + virtualizer }) - return () => window.cancelAnimationFrame(frameId) }, [ anchorRef, getItemElementKey, itemElementSelector, recordScrollAnchor, + restoreSignal, rowIndexByKey, scrollElementRef, scrollOffsetRef, diff --git a/src/renderer/src/hooks/virtualized-scroll-anchor-listener.ts b/src/renderer/src/hooks/virtualized-scroll-anchor-listener.ts new file mode 100644 index 000000000..b787e75eb --- /dev/null +++ b/src/renderer/src/hooks/virtualized-scroll-anchor-listener.ts @@ -0,0 +1,140 @@ +import type { MutableRefObject } from 'react' +import { shouldCancelVirtualizedScrollOffsetRestore } from './virtualizedScrollOffsetRestore' +import type { ProgrammaticScrollMarks } from './programmatic-scroll-marks' + +type CreateVirtualizedScrollAnchorListenerArgs = { + el: TScrollElement + getHasDirectScrollInput: () => (() => boolean) | undefined + getMarks: () => ProgrammaticScrollMarks | undefined + getRecordAnchorOnScroll: () => boolean + // Why: our own writes (virtualizer size adjustments, restore nudges) move + // the viewport; the owner must sync its bookkeeping (scrollOffset, anchor + // scrollTop) or a later divergence check reads the moved offset as user + // input and drops a due restore. + onProgrammaticScroll: (scrollTop: number) => void + pendingRestoreRef: MutableRefObject + recordCurrentAnchor: () => void + recordUserScroll: (scrollTop: number) => void + targetOffset: number + scrollOffsetRef: MutableRefObject +} + +/** + * Owns the mount-time offset restore and classifies subsequent scroll events. + * With marks, classification is state-owned: a scroll is the user's exactly + * when no registered programmatic write (or its clamped landing) explains it. + * Without marks, falls back to the legacy direct-input time window. + * Writes the initial offset on creation when one is persisted. + */ +export function createVirtualizedScrollAnchorListener({ + el, + getHasDirectScrollInput, + getMarks, + getRecordAnchorOnScroll, + onProgrammaticScroll, + pendingRestoreRef, + recordCurrentAnchor, + recordUserScroll, + targetOffset, + scrollOffsetRef +}: CreateVirtualizedScrollAnchorListenerArgs): (event: Event) => void { + // Why: a write to the current position emits no scroll event, so an armed + // restore would never complete and would snap later marked writes back to + // this stale target. Nothing to restore — don't arm. + let restoring = targetOffset > 0 && el.scrollTop !== targetOffset + if (restoring) { + getMarks()?.mark(targetOffset) + el.scrollTop = targetOffset + } + + const completeRestore = (): void => { + restoring = false + if (getRecordAnchorOnScroll()) { + recordCurrentAnchor() + } else { + scrollOffsetRef.current = el.scrollTop + } + } + + return (event: Event): void => { + const marks = getMarks() + if (marks) { + const isProgrammatic = marks.consume(event, el.scrollTop, el.scrollHeight - el.clientHeight) + if (restoring) { + if (el.scrollTop === targetOffset) { + completeRestore() + return + } + if (!isProgrammatic) { + const maxScrollOffset = el.scrollHeight - el.clientHeight + // Why: an unmarked landing pinned at a max the target can't reach + // is the browser clamping after content shrank, not user input; + // keep waiting for the range to catch up instead of persisting the + // clamped position. Direct input still takes over immediately. + const clampExplainsLanding = + targetOffset > maxScrollOffset && el.scrollTop >= maxScrollOffset - 2 + if (!clampExplainsLanding || getHasDirectScrollInput()?.() === true) { + // Why: an unmarked scroll no clamp explains is the user taking + // control of the viewport (marks classify our writes and their + // clamped landings); their position wins over the persisted offset. + restoring = false + pendingRestoreRef.current = false + recordCurrentAnchor() + return + } + } + if (el.scrollHeight - el.clientHeight >= targetOffset) { + marks.mark(targetOffset) + el.scrollTop = targetOffset + if (el.scrollTop === targetOffset) { + completeRestore() + } + } + return + } + if (isProgrammatic) { + onProgrammaticScroll(el.scrollTop) + return + } + pendingRestoreRef.current = false + if (!getRecordAnchorOnScroll()) { + return + } + recordUserScroll(el.scrollTop) + return + } + if ( + shouldCancelVirtualizedScrollOffsetRestore({ + hasDirectScrollInput: getHasDirectScrollInput(), + restoring + }) + ) { + // Why: direct wheel/touch input means the user has taken control of the + // viewport. Treat the current offset as intentional instead of snapping + // back to a stale persisted offset while restoration is still pending. + restoring = false + recordCurrentAnchor() + return + } + if (restoring) { + // Why: during a fresh virtualizer mount, total height may still be + // estimate-based. Avoid persisting a browser-clamped offset as the + // user's real position until the intended offset is reachable. + if (el.scrollTop === targetOffset) { + completeRestore() + return + } + if (el.scrollHeight - el.clientHeight >= targetOffset) { + el.scrollTop = targetOffset + if (el.scrollTop === targetOffset) { + completeRestore() + } + } + return + } + if (!getRecordAnchorOnScroll()) { + return + } + recordUserScroll(el.scrollTop) + } +} diff --git a/src/renderer/src/hooks/virtualized-scroll-anchor-recording.ts b/src/renderer/src/hooks/virtualized-scroll-anchor-recording.ts index bf77d2426..43855b50f 100644 --- a/src/renderer/src/hooks/virtualized-scroll-anchor-recording.ts +++ b/src/renderer/src/hooks/virtualized-scroll-anchor-recording.ts @@ -42,7 +42,8 @@ export function findVirtualizedDomScrollAnchor({ return { fallbackKeys: visibleItems.slice(1).map((item) => item.key), key: firstVisible.key, - offset: Math.min(firstVisible.rect.height, Math.max(0, scrollRect.top - firstVisible.rect.top)) + offset: Math.min(firstVisible.rect.height, Math.max(0, scrollRect.top - firstVisible.rect.top)), + scrollTop: scrollElement.scrollTop } } @@ -70,6 +71,7 @@ export function getVirtualizedScrollAnchorForOffset({ .filter((row): row is TRow => row != null) .map(getRowKey), key: getRowKey(row), - offset: Math.max(0, scrollTop - firstVisible.start) + offset: Math.max(0, scrollTop - firstVisible.start), + scrollTop } } diff --git a/src/renderer/src/hooks/virtualized-scroll-anchor-restore.ts b/src/renderer/src/hooks/virtualized-scroll-anchor-restore.ts new file mode 100644 index 000000000..083e95acb --- /dev/null +++ b/src/renderer/src/hooks/virtualized-scroll-anchor-restore.ts @@ -0,0 +1,148 @@ +import type { MutableRefObject } from 'react' +import type { Virtualizer } from '@tanstack/react-virtual' +import type { ProgrammaticScrollMarks } from './programmatic-scroll-marks' +import type { VirtualizedScrollAnchor } from './useVirtualizedScrollAnchor' + +type RunVirtualizedScrollAnchorRestoreArgs< + TScrollElement extends Element, + TItemElement extends Element +> = { + anchor: NonNullable + el: TScrollElement + getItemElementKey?: (element: TItemElement) => string | null + itemElementSelector?: string + // Why: true while a restore has written toward the anchor but the anchored + // row's position is not yet confirmed; the caller re-runs the restore across + // measurement ticks until it converges or the user scrolls. + pendingRestoreRef: MutableRefObject + programmaticScrollMarks?: ProgrammaticScrollMarks + recordScrollAnchor: (scrollTop: number) => void + rowIndexByKey: ReadonlyMap + scrollOffsetRef: MutableRefObject + virtualizer: Virtualizer +} + +/** + * One restore attempt: pin the anchored row back to its recorded viewport + * offset. Prefers the row's live DOM position, then its measured virtual slot, + * then scrollToIndex to bring it into the window. Every scroll write is + * registered with the marks so scroll listeners attribute it to this code, + * not the user. Returns a cleanup for the scrollToIndex follow-up frame. + */ +export function runVirtualizedScrollAnchorRestore< + TScrollElement extends Element, + TItemElement extends Element +>({ + anchor, + el, + getItemElementKey, + itemElementSelector, + pendingRestoreRef, + programmaticScrollMarks, + recordScrollAnchor, + rowIndexByKey, + scrollOffsetRef, + virtualizer +}: RunVirtualizedScrollAnchorRestoreArgs): (() => void) | undefined { + const resolvedKey = rowIndexByKey.has(anchor.key) + ? anchor.key + : anchor.fallbackKeys?.find((key) => rowIndexByKey.has(key)) + if (!resolvedKey) { + // Why: an unresolvable anchor has nothing to converge; rows that make it + // resolvable again always arrive via a signal change, so leaving the arm + // set would re-run restore on every measurement tick. + pendingRestoreRef.current = false + return + } + const index = rowIndexByKey.get(resolvedKey) + if (index === undefined) { + pendingRestoreRef.current = false + return + } + const offset = resolvedKey === anchor.key ? anchor.offset : 0 + const canConfirmFromDom = Boolean(itemElementSelector && getItemElementKey) + + const restoreFromDomElement = (): boolean => { + if (!itemElementSelector || !getItemElementKey) { + return false + } + const element = + Array.from(el.querySelectorAll(itemElementSelector)).find( + (candidate) => getItemElementKey(candidate) === resolvedKey && candidate.isConnected + ) ?? null + if (!element) { + return false + } + const scrollRect = el.getBoundingClientRect() + const rect = element.getBoundingClientRect() + const desiredTop = scrollRect.top - offset + const delta = rect.top - desiredTop + if (Math.abs(delta) > 1) { + // Why: this scroll write is still part of restore; keep the target + // anchor until a later layout confirms the intended row is in place. + programmaticScrollMarks?.mark(el.scrollTop + delta) + el.scrollTop += delta + scrollOffsetRef.current = el.scrollTop + anchor.scrollTop = el.scrollTop + pendingRestoreRef.current = true + return true + } + scrollOffsetRef.current = el.scrollTop + pendingRestoreRef.current = false + recordScrollAnchor(el.scrollTop) + return true + } + + const restoreFromMeasuredItem = (): boolean => { + const item = virtualizer.getVirtualItems().find((candidate) => candidate.index === index) + if (!item) { + return false + } + const maxScrollTop = Math.max(0, el.scrollHeight - el.clientHeight) + const nextScrollTop = Math.min(maxScrollTop, Math.max(0, item.start + offset)) + if (Math.abs(el.scrollTop - nextScrollTop) > 1) { + programmaticScrollMarks?.mark(nextScrollTop) + el.scrollTop = nextScrollTop + } + // Why: measured fallback can run while TanStack's virtual window is + // transitional, so recording here can replace the target with a wrong row. + scrollOffsetRef.current = el.scrollTop + anchor.scrollTop = el.scrollTop + // Why: without a DOM selector there is no later confirmation step; the + // measured landing is final, so don't re-arm restore ticks forever. + pendingRestoreRef.current = canConfirmFromDom + return true + } + + if (restoreFromDomElement()) { + return + } + + // Why: right after a delete the virtualizer can briefly render the wrong + // window, so the anchor row's DOM node isn't mounted yet even though the + // virtualizer still has its measured slot. Pin from that measured start + // (preserving the within-row offset) before falling back to scrollToIndex, + // whose align:'start' snaps the row to the viewport top and visibly jumps. + if (restoreFromMeasuredItem()) { + return + } + + // Why: the anchored row is outside the virtualizer's current window — no + // DOM node and no measured slot. Bring it in, then apply the within-row + // offset once TanStack Virtual has mounted and measured that row. + // scrollToIndex marks its write via the caller-supplied scrollToFn. + pendingRestoreRef.current = true + virtualizer.scrollToIndex(index, { align: 'start' }) + anchor.scrollTop = el.scrollTop + const frameId = window.requestAnimationFrame(() => { + if (!pendingRestoreRef.current) { + // Why: an unmarked (user) scroll disarmed the restore between the + // effect and this frame; writing now would fight their input. + return + } + if (!restoreFromDomElement()) { + restoreFromMeasuredItem() + } + }) + return () => window.cancelAnimationFrame(frameId) +}