diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 9767972d73d05..4231b669aa76b 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -24,6 +24,7 @@ import { import * as Schema from "effect/Schema"; import { type MouseEvent, useEffect, useRef, useState } from "react"; import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal"; +import { useCodeViewScrollRestore } from "./diffs/useCodeViewScrollRestore"; import { useFilesystemReadAccess } from "~/state/filesystem"; import { useOpenInPreferredEditor } from "../editorPreferences"; import { useFileContextMenuHandler } from "../fileContextMenu"; @@ -67,7 +68,7 @@ import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampForma import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { DiffStatLabel } from "./chat/DiffStatLabel"; -import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView"; +import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView"; import { DiffFileTree } from "./diffs/DiffFileTree"; import { FileExplorerPane } from "./files/FileExplorerPane"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; @@ -693,12 +694,27 @@ export default function DiffPanel({ const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles); const fileTreeEntries = diffFileTreeEntries(renderableFiles.filter(isFileShown)); const codeViewReveal = useCodeViewFileReveal(); + // Lazy files that sat above the saved position load again only when asked for. + const codeViewScroll = useCodeViewScrollRestore( + collapseScopeKey, + !isRefreshingDiff && remainingFileCount === 0, + remainingFileCount > 0 ? loadNextFiles : null, + ); + const attachCodeView = useStableCallback((handle: AnnotatableCodeViewHandle | null) => { + codeViewScroll.attach(handle); + codeViewReveal.attach(handle); + }); + const flushCodeView = useStableCallback(() => { + codeViewScroll.flush(); + codeViewReveal.flush(); + }); const revealDiffFile = (filePath: string) => { const index = renderableFileEntries.findIndex( (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, ); const file = renderableFileEntries[index]; if (!file) return false; + codeViewScroll.discard(); updateCollapsedDiffFiles((current) => { const next = new Set(current); next.delete(file.fileKey); @@ -775,6 +791,7 @@ export default function DiffPanel({ }); const toggleDiffFileCollapse = () => { + codeViewScroll.discard(); setCodeViewRevision((current) => current + 1); updateCollapsedDiffFiles((current) => toggleAllDiffFiles(shownFileKeys, current)); }; @@ -1431,7 +1448,8 @@ export default function DiffPanel({ key={collapseScopeKey ?? reviewSectionId} environmentId={activeThread?.environmentId} projectId={activeThread?.projectId} - viewerRef={codeViewReveal.attach} + viewerRef={attachCodeView} + onScroll={codeViewScroll.onScroll} codeViewKey={codeViewMountKey} className="h-full min-h-0 overflow-auto" files={codeViewFiles} @@ -1493,7 +1511,7 @@ export default function DiffPanel({ preferredHighlighter: PREFERRED_HIGHLIGHTER, themeType: resolvedTheme as DiffThemeType, stickyHeaders: true, - onPostRender: codeViewReveal.flush, + onPostRender: flushCodeView, ...(currentLoadDiffFiles ? { loadDiffFiles } : {}), }} /> diff --git a/apps/web/src/components/diffs/AnnotatableCodeView.tsx b/apps/web/src/components/diffs/AnnotatableCodeView.tsx index b7965428478fb..f5a0da4b1a903 100644 --- a/apps/web/src/components/diffs/AnnotatableCodeView.tsx +++ b/apps/web/src/components/diffs/AnnotatableCodeView.tsx @@ -6,7 +6,7 @@ import type { FileDiffMetadata, SelectedLineRange, } from "@pierre/diffs"; -import type { CodeViewHandle } from "@pierre/diffs/react"; +import type { CodeViewHandle, CodeViewProps } from "@pierre/diffs/react"; import type { EnvironmentId, ProjectId, ScopedThreadRef } from "@t3tools/contracts"; import { useState, type ReactNode, type Ref } from "react"; @@ -88,6 +88,7 @@ interface AnnotatableCodeViewProps { composerDraftTarget: ScopedThreadRef | DraftId; options: StyledDiffCodeViewOptions; viewerRef?: Ref; + onScroll?: CodeViewProps["onScroll"]; className?: string; renderCodeViewFooter?: () => ReactNode; unsafeCSSExtra?: string; @@ -116,6 +117,7 @@ export function AnnotatableCodeView({ composerDraftTarget, options, viewerRef, + onScroll, className, renderCodeViewFooter, unsafeCSSExtra, @@ -260,6 +262,7 @@ export function AnnotatableCodeView({ key={codeViewKey} {...(viewerRef ? { viewerRef } : {})} + {...(onScroll ? { onScroll } : {})} {...(className ? { className } : {})} {...(unsafeCSSExtra ? { unsafeCSSExtra } : {})} {...(renderHeaderMetadata diff --git a/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts b/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts new file mode 100644 index 0000000000000..ec503dff2c83c --- /dev/null +++ b/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts @@ -0,0 +1,81 @@ +import type { CodeViewScrollTarget } from "@pierre/diffs"; +import { describe, expect, it } from "vite-plus/test"; + +import { createCodeViewScrollRestore } from "./useCodeViewScrollRestore"; + +function viewer(scrollHeight: number, height = 500) { + const instance = { scrollHeight, height, getHeight: () => 0, getScrollHeight: () => 0 }; + instance.getHeight = () => instance.height; + instance.getScrollHeight = () => instance.scrollHeight; + const scrolls: CodeViewScrollTarget[] = []; + return { + instance, + scrolls, + getInstance: () => instance, + scrollTo: (target: CodeViewScrollTarget) => scrolls.push(target), + }; +} + +function mount( + scopeKey: string, + view: ReturnType, + settled = true, + loadMore: (() => void) | null = null, +) { + const restore = createCodeViewScrollRestore(); + restore.update(scopeKey, settled, loadMore); + restore.attach(view); + return restore; +} + +describe("createCodeViewScrollRestore", () => { + it("puts a remounted viewer back at its scope's position, not another scope's", () => { + const first = viewer(10_000); + mount("thread-a", first).onScroll(4000, first.instance); + const other = viewer(10_000); + mount("thread-b", other).onScroll(1200, other.instance); + + const again = viewer(10_000); + mount("thread-a", again); + // Pierre subtracts the 32px sticky header from an unclamped position target. + expect(again.scrolls).toEqual([{ type: "position", position: 4032 }]); + }); + + it("loads more files until the position is reachable, then gives up once none remain", () => { + const first = viewer(10_000); + mount("thread-c", first).onScroll(4000, first.instance); + + const loading = viewer(700); + let batches = 0; + const restore = mount("thread-c", loading, false, () => { + batches += 1; + }); + restore.onScroll(0, loading.instance); + restore.flush(); + expect(loading.scrolls).toEqual([]); + expect(batches).toBe(2); + loading.instance.scrollHeight = 10_000; + restore.flush(); + restore.flush(); + expect(loading.scrolls).toEqual([{ type: "position", position: 4032 }]); + + const shrunk = viewer(2000); + const settling = mount("thread-c", shrunk, false); + settling.flush(); + expect(shrunk.scrolls).toEqual([]); + settling.update("thread-c", true, null); + settling.flush(); + expect(shrunk.scrolls).toEqual([{ type: "position", position: 1500 }]); + }); + + it("forgets a position that a reveal or collapsing every file replaced", () => { + const first = viewer(10_000); + const restore = mount("thread-d", first); + restore.onScroll(4000, first.instance); + restore.discard(); + + const again = viewer(10_000); + mount("thread-d", again); + expect(again.scrolls).toEqual([]); + }); +}); diff --git a/apps/web/src/components/diffs/useCodeViewScrollRestore.ts b/apps/web/src/components/diffs/useCodeViewScrollRestore.ts new file mode 100644 index 0000000000000..464df7a498361 --- /dev/null +++ b/apps/web/src/components/diffs/useCodeViewScrollRestore.ts @@ -0,0 +1,79 @@ +import type { CodeViewScrollTarget } from "@pierre/diffs"; +import { useEffect, useState } from "react"; + +interface Viewer { + getHeight(): number; + getScrollHeight(): number; +} + +interface ScrollRestoreHandle { + getInstance(): Viewer | undefined; + scrollTo(target: CodeViewScrollTarget): void; +} + +// Session-only, like the panel's folds. +const scrollTopByScopeKey = new Map(); + +/** + * Puts a remounted code view back where its scope was last scrolled. `attach` is the viewer's + * ref and `flush` its post-render handler; the position waits until the content can reach it, + * loading more files while any remain, and clamps once nothing is left to load. + */ +export function createCodeViewScrollRestore() { + let scopeKey: string | null = null; + let settled = true; + let loadMore: (() => void) | null = null; + let viewer: Viewer | undefined; + let handle: ScrollRestoreHandle | null = null; + let pending: number | null = null; + const flush = () => { + if (pending === null || !viewer || !handle || viewer.getHeight() === 0) return; + const maxScrollTop = viewer.getScrollHeight() - viewer.getHeight(); + if (maxScrollTop < pending && !settled) { + loadMore?.(); + return; + } + // Pierre lands an unclamped position target one sticky header (32px) above it. + const position = pending + 32 <= maxScrollTop ? pending + 32 : maxScrollTop; + pending = null; + if (position > 0) handle.scrollTo({ type: "position", position }); + }; + return { + update(nextScopeKey: string | null, nextSettled: boolean, nextLoadMore: (() => void) | null) { + scopeKey = nextScopeKey; + settled = nextSettled; + loadMore = nextLoadMore; + }, + attach(next: ScrollRestoreHandle | null) { + handle = next; + const instance = next?.getInstance(); + if (instance && instance !== viewer) { + viewer = instance; + pending = scopeKey === null ? null : (scrollTopByScopeKey.get(scopeKey) ?? null); + } + flush(); + }, + onScroll(scrollTop: number, source: object) { + if (source !== viewer || pending !== null || scopeKey === null) return; + scrollTopByScopeKey.set(scopeKey, scrollTop); + }, + /** Something else positions the viewer, such as a file reveal or collapsing every file. */ + discard() { + pending = null; + if (scopeKey !== null) scrollTopByScopeKey.delete(scopeKey); + }, + flush, + }; +} + +export function useCodeViewScrollRestore( + scopeKey: string | null, + settled: boolean, + loadMore: (() => void) | null, +) { + const [restore] = useState(createCodeViewScrollRestore); + restore.update(scopeKey, settled, loadMore); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a loaded batch can leave the viewer's rendered items alone, so no ref or post-render call re-checks the pending position + useEffect(() => restore.flush()); + return restore; +}