diff --git a/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts b/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts index ec503dff2c83c..8b26e785cd25a 100644 --- a/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts +++ b/apps/web/src/components/diffs/useCodeViewScrollRestore.test.ts @@ -1,17 +1,38 @@ import type { CodeViewScrollTarget } from "@pierre/diffs"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } 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 LINE_HEIGHT = 20; + +// Files stacked from the given tops, each a 32px header followed by 20px lines. +function viewer(tops: Record, collapsed: readonly string[] = []) { + const items = new Map(Object.entries(tops)); + const instance = { + scrollTop: 0, + rendered: null as string[] | null, + getHeight: () => 500, + getScrollTop: () => instance.scrollTop, + getTopForItem: (id: string) => items.get(id), + getRenderedItems: () => + (instance.rendered ?? [...items.keys()]).map((id) => ({ + id, + instance: { + getNumericScrollAnchor: (localTop: number) => { + if (collapsed.includes(id)) return undefined; + const lineNumber = Math.ceil((localTop - 32) / LINE_HEIGHT) + 1; + return { lineNumber, top: 32 + (lineNumber - 1) * LINE_HEIGHT }; + }, + }, + })), + }; const scrolls: CodeViewScrollTarget[] = []; return { instance, + items, scrolls, getInstance: () => instance, + getItem: (id: string) => (items.has(id) ? { collapsed: collapsed.includes(id) } : undefined), scrollTo: (target: CodeViewScrollTarget) => scrolls.push(target), }; } @@ -28,53 +49,104 @@ function mount( return restore; } +function setup() { + const frames: FrameRequestCallback[] = []; + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => frames.push(callback)); + const runFrame = () => { + for (const callback of frames.splice(0)) callback(0); + }; + const runFrames = () => { + while (frames.length > 0) runFrame(); + }; + const scroll = ( + restore: ReturnType, + view: ReturnType, + top: number, + ) => { + view.instance.scrollTop = top; + restore.onScroll(top, view.instance); + runFrames(); + }; + return { runFrame, runFrames, scroll }; +} + 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); + it("puts a remounted viewer back on its scope's file and line, not its pixel offset", () => { + const { scroll } = setup(); + const first = viewer({ a: 0, b: 4000, c: 9000 }); + // 104px into file b: line 7 is the first under the sticky header, 16px below its edge. + scroll(mount("thread-a", first), first, 4104); + const other = viewer({ a: 0, b: 4000 }); + scroll(mount("thread-b", other), other, 1200); - const again = viewer(10_000); + // The remounted viewer estimates file a shorter, so file b starts elsewhere. + const again = viewer({ a: 0, b: 2500, c: 6000 }); mount("thread-a", again); - // Pierre subtracts the 32px sticky header from an unclamped position target. - expect(again.scrolls).toEqual([{ type: "position", position: 4032 }]); + expect(again.scrolls).toEqual([ + { type: "line", id: "b", align: "start", lineNumber: 7, offset: 16 }, + ]); + }); + + it("reads the anchor from the viewport Pierre renders after the scroll, not the one before", () => { + const { runFrame, runFrames } = setup(); + const first = viewer({ a: 0, b: 4000, c: 8000 }); + first.instance.rendered = ["a"]; + const restore = mount("thread-e", first); + first.instance.scrollTop = 104; + restore.onScroll(104, first.instance); + runFrame(); + // The drag goes on to file c between the frames and notifies before the viewer renders it. + first.instance.scrollTop = 8104; + restore.onScroll(8104, first.instance); + runFrame(); + first.instance.rendered = ["c"]; + runFrames(); + + const again = viewer({ a: 0, b: 2500, c: 6000 }); + mount("thread-e", again); + expect(again.scrolls).toEqual([ + { type: "line", id: "c", align: "start", lineNumber: 7, offset: 16 }, + ]); }); - 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); + it("loads more files until the anchored file has loaded, then falls back to the file", () => { + const { scroll } = setup(); + const first = viewer({ a: 0, b: 4000 }); + scroll(mount("thread-c", first), first, 4104); - const loading = viewer(700); + const loading = viewer({ a: 0 }); let batches = 0; const restore = mount("thread-c", loading, false, () => { batches += 1; }); - restore.onScroll(0, loading.instance); + scroll(restore, loading, 0); restore.flush(); expect(loading.scrolls).toEqual([]); expect(batches).toBe(2); - loading.instance.scrollHeight = 10_000; + loading.items.set("b", 700); restore.flush(); restore.flush(); - expect(loading.scrolls).toEqual([{ type: "position", position: 4032 }]); + expect(loading.scrolls).toEqual([ + { type: "line", id: "b", align: "start", lineNumber: 7, offset: 16 }, + ]); - const shrunk = viewer(2000); - const settling = mount("thread-c", shrunk, false); + const pending = viewer({ a: 0, b: 700 }, ["b"]); + const settling = mount("thread-c", pending, false); settling.flush(); - expect(shrunk.scrolls).toEqual([]); + expect(pending.scrolls).toEqual([]); settling.update("thread-c", true, null); settling.flush(); - expect(shrunk.scrolls).toEqual([{ type: "position", position: 1500 }]); + expect(pending.scrolls).toEqual([{ type: "item", id: "b", align: "start", offset: -104 }]); }); it("forgets a position that a reveal or collapsing every file replaced", () => { - const first = viewer(10_000); + const { scroll } = setup(); + const first = viewer({ a: 0, b: 4000 }); const restore = mount("thread-d", first); - restore.onScroll(4000, first.instance); + scroll(restore, first, 4104); restore.discard(); - const again = viewer(10_000); + const again = viewer({ a: 0, b: 4000 }); 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 index 464df7a498361..aa45c78ee6e4e 100644 --- a/apps/web/src/components/diffs/useCodeViewScrollRestore.ts +++ b/apps/web/src/components/diffs/useCodeViewScrollRestore.ts @@ -1,23 +1,69 @@ -import type { CodeViewScrollTarget } from "@pierre/diffs"; +import type { CodeViewScrollTarget, SelectionSide } from "@pierre/diffs"; import { useEffect, useState } from "react"; interface Viewer { getHeight(): number; - getScrollHeight(): number; + getScrollTop(): number; + getRenderedItems(): readonly { + id: string; + instance: { + getNumericScrollAnchor( + localViewportTop: number, + ): { lineNumber: number; top: number; side?: SelectionSide } | undefined; + }; + }[]; + getTopForItem(id: string): number | undefined; } interface ScrollRestoreHandle { getInstance(): Viewer | undefined; + getItem(id: string): { collapsed?: boolean } | undefined; scrollTo(target: CodeViewScrollTarget): void; } +// A remounted viewer estimates the height of files it has not measured, so a pixel offset lands +// in other content; the anchor is a file and line plus where it sat in the viewport. +interface ScrollAnchor { + id: string; + offset: number; + line?: { lineNumber: number; side?: SelectionSide; offset: number }; +} + +// The panel's sticky file header, which Pierre keeps a line target below. +const STICKY_HEADER_HEIGHT = 32; + // Session-only, like the panel's folds. -const scrollTopByScopeKey = new Map(); +const anchorByScopeKey = new Map(); + +function anchorAt(viewer: Viewer, scrollTop: number): ScrollAnchor | null { + if (scrollTop <= 0) return null; + const items = viewer.getRenderedItems().flatMap((item) => { + const top = viewer.getTopForItem(item.id); + return top === undefined ? [] : [{ item, top }]; + }); + const anchor = items.findLast(({ top }) => top <= scrollTop) ?? items[0]; + if (anchor === undefined) return null; + const { item, top } = anchor; + const line = item.instance.getNumericScrollAnchor(scrollTop + STICKY_HEADER_HEIGHT - top); + return { + id: item.id, + offset: top - scrollTop, + ...(line + ? { + line: { + lineNumber: line.lineNumber, + ...(line.side ? { side: line.side } : {}), + offset: top + line.top - STICKY_HEADER_HEIGHT - scrollTop, + }, + } + : {}), + }; +} /** - * 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. + * Puts a remounted code view back on the file and line its scope was last scrolled to. `attach` + * is the viewer's ref and `flush` its post-render handler; the anchor waits until its file is + * loaded, loading more files while any remain, and falls back to the file once none are left. */ export function createCodeViewScrollRestore() { let scopeKey: string | null = null; @@ -25,18 +71,31 @@ export function createCodeViewScrollRestore() { let loadMore: (() => void) | null = null; let viewer: Viewer | undefined; let handle: ScrollRestoreHandle | null = null; - let pending: number | null = null; + let pending: ScrollAnchor | null = null; + let captureRequest = 0; + const capture = (source: object) => { + if (!handle || source !== viewer || pending !== null || scopeKey === null) return; + const scrollTop = viewer.getScrollTop(); + const anchor = anchorAt(viewer, scrollTop); + if (anchor) anchorByScopeKey.set(scopeKey, anchor); + else if (scrollTop <= 0) anchorByScopeKey.delete(scopeKey); + }; const flush = () => { if (pending === null || !viewer || !handle || viewer.getHeight() === 0) return; - const maxScrollTop = viewer.getScrollHeight() - viewer.getHeight(); - if (maxScrollTop < pending && !settled) { + const item = handle.getItem(pending.id); + const loaded = item !== undefined && (pending.line === undefined || item.collapsed !== true); + if (!loaded && !settled) { loadMore?.(); return; } - // Pierre lands an unclamped position target one sticky header (32px) above it. - const position = pending + 32 <= maxScrollTop ? pending + 32 : maxScrollTop; + const { id, offset, line } = pending; pending = null; - if (position > 0) handle.scrollTo({ type: "position", position }); + if (item === undefined) return; + handle.scrollTo( + line && loaded + ? { type: "line", id, align: "start", ...line } + : { type: "item", id, align: "start", offset }, + ); }; return { update(nextScopeKey: string | null, nextSettled: boolean, nextLoadMore: (() => void) | null) { @@ -49,18 +108,25 @@ export function createCodeViewScrollRestore() { const instance = next?.getInstance(); if (instance && instance !== viewer) { viewer = instance; - pending = scopeKey === null ? null : (scrollTopByScopeKey.get(scopeKey) ?? null); + pending = scopeKey === null ? null : (anchorByScopeKey.get(scopeKey) ?? null); } flush(); }, - onScroll(scrollTop: number, source: object) { - if (source !== viewer || pending !== null || scopeKey === null) return; - scrollTopByScopeKey.set(scopeKey, scrollTop); + onScroll(_scrollTop: number, source: object) { + if (source !== viewer || pending !== null) return; + // Pierre notifies before it renders the new viewport in the next frame, so the rendered + // items are read in the frame after the last scroll's render. + const request = ++captureRequest; + requestAnimationFrame(() => + requestAnimationFrame(() => { + if (request === captureRequest) capture(source); + }), + ); }, /** Something else positions the viewer, such as a file reveal or collapsing every file. */ discard() { pending = null; - if (scopeKey !== null) scrollTopByScopeKey.delete(scopeKey); + if (scopeKey !== null) anchorByScopeKey.delete(scopeKey); }, flush, }; @@ -73,7 +139,7 @@ export function useCodeViewScrollRestore( ) { 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 + // 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 anchor useEffect(() => restore.flush()); return restore; }