diff --git a/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts b/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts index ec503dff2c83c..538359c843b84 100644 --- a/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts +++ b/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts @@ -68,6 +68,38 @@ describe("createCodeViewScrollRestore", () => { expect(shrunk.scrolls).toEqual([{ type: "position", position: 1500 }]); }); + it("lets a reader who scrolls while more files load keep their own position", () => { + const first = viewer(10_000); + mount("thread-e", first).onScroll(4000, first.instance); + + const loading = viewer(700); + const restore = mount("thread-e", loading, false, () => {}); + restore.cancel(); + restore.onScroll(150, loading.instance); + loading.instance.scrollHeight = 10_000; + restore.update("thread-e", true, null); + restore.flush(); + expect(loading.scrolls).toEqual([]); + + const again = viewer(10_000); + mount("thread-e", again); + expect(again.scrolls).toEqual([{ type: "position", position: 182 }]); + }); + + it("moves a viewer kept across a scope change to that scope's position, not the old one", () => { + const commitA = viewer(10_000); + mount("commit-a", commitA).onScroll(3000, commitA.instance); + const commitB = viewer(10_000); + mount("commit-b", commitB).onScroll(800, commitB.instance); + + const kept = viewer(700); + const restore = mount("commit-a", kept, false, () => {}); + restore.update("commit-b", true, null); + kept.instance.scrollHeight = 10_000; + restore.flush(); + expect(kept.scrolls).toEqual([{ type: "position", position: 832 }]); + }); + it("forgets a position that a reveal or collapsing every file replaced", () => { const first = viewer(10_000); const restore = mount("thread-d", first); diff --git a/apps/web/src/components/diffs/useCodeViewScrollRestore.ts b/apps/web/src/components/diffs/useCodeViewScrollRestore.ts index 464df7a498361..f13cb7b87e905 100644 --- a/apps/web/src/components/diffs/useCodeViewScrollRestore.ts +++ b/apps/web/src/components/diffs/useCodeViewScrollRestore.ts @@ -40,6 +40,10 @@ export function createCodeViewScrollRestore() { }; return { update(nextScopeKey: string | null, nextSettled: boolean, nextLoadMore: (() => void) | null) { + // A viewer kept across a scope change takes the new scope's position, never the old one's. + if (viewer && nextScopeKey !== scopeKey) { + pending = nextScopeKey === null ? null : (scrollTopByScopeKey.get(nextScopeKey) ?? null); + } scopeKey = nextScopeKey; settled = nextSettled; loadMore = nextLoadMore; @@ -57,6 +61,10 @@ export function createCodeViewScrollRestore() { if (source !== viewer || pending !== null || scopeKey === null) return; scrollTopByScopeKey.set(scopeKey, scrollTop); }, + /** The reader scrolled before the saved position was reached; their scroll wins. */ + cancel() { + pending = null; + }, /** Something else positions the viewer, such as a file reveal or collapsing every file. */ discard() { pending = null; diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 4d305c4da66ed..faee99620af8e 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -59,6 +59,8 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { }); const mocks = vi.hoisted(() => ({ + // Folds and scroll persist per pull request for the session, so each test gets its own scope. + session: 0, paged: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, @@ -172,6 +174,7 @@ const detail: PullRequestDetailView = { function setup({ paged }: { paged: boolean }) { window.localStorage.removeItem("t3code.diffHideTestFiles"); __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + mocks.session += 1; mocks.paged = paged; mocks.diffCommits = []; mocks.viewedPaths = null; @@ -186,7 +189,7 @@ const tab = ( ) => ( {}} - environmentId={EnvironmentId.make("environment")} + environmentId={EnvironmentId.make(`environment-${mocks.session}`)} reference={detail} detail={detail} selectedCommitOid={null} @@ -253,11 +256,23 @@ it("restores saved Viewed folds, follows cleared marks, and allows explicit expa await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + // Switching right-panel tabs remounts the Code tab; Expand all holds for the session. await screen.rerender(
); await screen.rerender(tab(1)); - await expect - .element(screen.getByRole("button", { name: "Expand diff", exact: true })) - .toHaveAttribute("aria-expanded", "false"); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); +}); + +it("keeps a file opened by hand when the tab remounts", async () => { + setup({ paged: false }); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render(tab(0), { container }); + await screen.getByRole("button", { name: "Expand diff", exact: true }).click(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + + await screen.rerender(
); + await screen.rerender(tab(0)); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); }); // regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it @@ -349,7 +364,7 @@ it("never requests the diff of a selected commit the pull request no longer has" await using screen = await render( {}} - environmentId={EnvironmentId.make("environment")} + environmentId={EnvironmentId.make(`environment-${mocks.session}`)} reference={detail} detail={{ ...detail, @@ -389,7 +404,7 @@ it("answers a commit's diff link only once that commit's diff is shown", async ( const scoped = (selectedCommitOid: string | null, revealUrl?: string) => ( {}} - environmentId={EnvironmentId.make("environment")} + environmentId={EnvironmentId.make(`environment-${mocks.session}`)} reference={detail} detail={withCommit} selectedCommitOid={selectedCommitOid} @@ -428,7 +443,7 @@ it("hides a resolved conversation behind avatars on its line until they are clic const withThread = (isResolved: boolean, oldSideToo = false) => ( {}} - environmentId={EnvironmentId.make("environment")} + environmentId={EnvironmentId.make(`environment-${mocks.session}`)} reference={detail} detail={{ ...detail, @@ -517,7 +532,7 @@ it("keeps an unsent reply when the appearance switches between light and dark", await using screen = await render( {}} - environmentId={EnvironmentId.make("environment")} + environmentId={EnvironmentId.make(`environment-${mocks.session}`)} reference={detail} detail={{ ...detail, diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f29d002c2bf81..a63fd8fa1f161 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -17,7 +17,7 @@ import type { FileDiffMetadata, SelectedLineRange, } from "@pierre/diffs"; -import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react"; +import type { CodeViewAnnotationArgs, CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react"; import type { EnvironmentId, PullRequestDetailView, @@ -67,6 +67,7 @@ import { observeIntersection } from "~/lib/observeIntersection"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; import { useRenderedAppearance } from "~/hooks/useTheme"; +import { useStableCallback } from "~/hooks/useStableCallback"; import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse"; import { pullRequestFindingKey, @@ -112,6 +113,7 @@ import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { DiffFileTree } from "../diffs/DiffFileTree"; import { FileExplorerPane } from "../files/FileExplorerPane"; import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal"; +import { useCodeViewScrollRestore } from "../diffs/useCodeViewScrollRestore"; import { useHideTestFiles } from "../diffs/useHideTestFiles"; import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic"; import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView"; @@ -187,6 +189,12 @@ type ReviewAnnotation = DiffLineAnnotation; const COMMIT_PAGE_SIZE = 10; +// Session-only, like the thread diff's folds: switching right-panel tabs remounts this tab. +const foldsByScopeKey = new Map< + string, + { readonly choices: FileDiffFoldChoices; readonly override: DiffFoldOverride } +>(); + const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen"; interface DiffSlice { @@ -451,11 +459,8 @@ function PullRequestCodeTab({ diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, })); - const [foldChoices, setFoldChoices] = useState(() => new Map()); const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); - const [foldOverride, setFoldOverride] = useState(null); - const effectiveFoldOverride = foldOverride ?? (settings.diffFilesCollapsed ? "folded" : null); const diffLayout = settings.diffLayout; const [wordWrapOverride, setWordWrapOverride] = useState(null); const wordWrap = wordWrapOverride ?? settings.wordWrap; @@ -488,6 +493,17 @@ function PullRequestCodeTab({ ? selectedCommitOid : null; const scopeKey = JSON.stringify([environmentId, referenceKey, commit]); + const [foldChoices, setFoldChoices] = useState( + () => foldsByScopeKey.get(scopeKey)?.choices ?? new Map(), + ); + const [foldOverride, setFoldOverride] = useState( + () => foldsByScopeKey.get(scopeKey)?.override ?? null, + ); + const effectiveFoldOverride = foldOverride ?? (settings.diffFilesCollapsed ? "folded" : null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- saves folds to the session map so a remount restores them + useEffect(() => { + foldsByScopeKey.set(scopeKey, { choices: foldChoices, override: foldOverride }); + }, [scopeKey, foldChoices, foldOverride]); // The panel keeps this mounted across pull requests, so an open composer would otherwise // survive the switch and attach its comment to whichever one is on screen when it is sent. const [stateScopeKey, setStateScopeKey] = useState(scopeKey); @@ -496,8 +512,8 @@ function PullRequestCodeTab({ setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); - setFoldChoices(new Map()); - setFoldOverride(null); + setFoldChoices(foldsByScopeKey.get(scopeKey)?.choices ?? new Map()); + setFoldOverride(foldsByScopeKey.get(scopeKey)?.override ?? null); setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); @@ -983,6 +999,25 @@ function PullRequestCodeTab({ if (nextCursor === null) return; setSliceState((previous) => ({ ...previous, cursor: nextCursor })); }; + const codeViewScroll = useCodeViewScrollRestore( + `pull-request:${scopeKey}`, + loadedSlices.length > 0 && nextCursor === null, + canLoadNextSlice ? loadNextSlice : null, + ); + // The viewer moves scrollTop itself while it measures restored rows; saving those moves would + // drift the offset further on every remount, so only a reader's own scroll is saved. + const scrolledByReader = useRef(false); + const followReader = () => { + scrolledByReader.current = true; + codeViewScroll.cancel(); + codeViewReveal.cancel(); + }; + const attachCodeView = useStableCallback( + (handle: CodeViewHandle | null) => { + codeViewScroll.attach(handle); + codeViewReveal.attach(handle); + }, + ); const sentinelRef = (node: HTMLDivElement | null) => { if (node === null || !canLoadNextSlice) return; return observeIntersection( @@ -1035,6 +1070,8 @@ function PullRequestCodeTab({ const revealFile = (path: string, range?: SelectedLineRange) => { const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; + codeViewScroll.discard(); + scrolledByReader.current = true; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. setFoldChoices((current) => withFileDiffFold(current, item.id, false)); if (range) setSelectedLines({ id: item.id, range }); @@ -1192,6 +1229,7 @@ function PullRequestCodeTab({ onGutterUtilityClick: beginComment, onLineSelectionEnd: beginComment, onPostRender: (fileContainer: HTMLElement, instance: object) => { + codeViewScroll.flush(); codeViewReveal.flush(); // Containers are reused across files, so the flag is set or cleared on every render. fileContainer.toggleAttribute( @@ -1914,10 +1952,10 @@ function PullRequestCodeTab({
{ const composedPath = event.nativeEvent.composedPath?.() ?? []; @@ -1944,7 +1982,10 @@ function PullRequestCodeTab({ className="@container h-full overflow-auto [scrollbar-gutter:stable]" containerRef={scrollerRef} - viewerRef={codeViewReveal.attach} + viewerRef={attachCodeView} + onScroll={(scrollTop, viewer) => { + if (scrolledByReader.current) codeViewScroll.onScroll(scrollTop, viewer); + }} items={items} selectedLines={selectedLines} onSelectedLinesChange={setSelectedLines} diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index d0ad2e02f8e12..56a90ce2756c1 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -271,6 +271,10 @@ const TABS: ReadonlyArray<{ value: PullRequestDetailTab; label: string }> = [ const loadCodeTab = () => import("./PullRequestCodeTab"); const PullRequestCodeTab = lazy(loadCodeTab); +// The Code tab restores its scroll on remount; a header left expanded would condense over the +// restored position and shift it up. +const codeCondensedByScopeKey = new Map(); + function reportCheckoutCommandError(error: Error) { toastManager.add({ type: "error", @@ -539,7 +543,7 @@ export function PullRequestDetailPanel({ // Each tab restores the condensed state its own scrolling left behind. const [condensedByTab, setCondensedByTab] = useState< Partial> - >({}); + >(() => ({ code: codeCondensedByScopeKey.get(tabScopeKey) ?? false })); const condensed = condensedByTab[tab] ?? false; const scrollerByTab = useRef>>({}); // Fresh ref callbacks would detach and reattach every scroller on each render. @@ -2042,7 +2046,9 @@ export function PullRequestDetailPanel({ compensationRef.current = { tab, scroller, target: top - chromeDelta }; next = true; } - if (next !== previous) setCondensedByTab({ ...condensedByTab, [tab]: next }); + if (next === previous) return; + if (tab === "code") codeCondensedByScopeKey.set(tabScopeKey, next); + setCondensedByTab({ ...condensedByTab, [tab]: next }); }} > {detailQuery.error && !detail ? (