Skip to content

Commit b4ce8e0

Browse files
fix(web): reveals asked before the code view mounts still land
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2dff20f commit b4ce8e0

5 files changed

Lines changed: 136 additions & 58 deletions

File tree

‎apps/web/src/components/DiffPanel.tsx‎

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
2121
import * as Schema from "effect/Schema";
2222
import { useEffect, useRef, useState } from "react";
23-
import { createCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
23+
import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
2424
import { useFilesystemReadAccess } from "~/state/filesystem";
2525
import { useOpenInPreferredEditor } from "../editorPreferences";
2626
import { useFileContextMenuHandler } from "../fileContextMenu";
@@ -55,7 +55,7 @@ import { formatShortTimestamp } from "../timestampFormat";
5555
import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
5656
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
5757
import { DiffStatLabel } from "./chat/DiffStatLabel";
58-
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
58+
import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView";
5959
import { DiffFileTree } from "./diffs/DiffFileTree";
6060
import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";
6161
import { Button } from "./ui/button";
@@ -216,7 +216,6 @@ export default function DiffPanel({
216216
);
217217
const [baseRefQuery, setBaseRefQuery] = useState("");
218218
const [codeViewRevision, setCodeViewRevision] = useState(0);
219-
const [codeView, setCodeView] = useState<AnnotatableCodeViewHandle | null>(null);
220219

221220
const routeThreadRef = useThreadRouteRef();
222221
const activeThreadId = routeThreadRef?.threadId ?? null;
@@ -534,8 +533,7 @@ export default function DiffPanel({
534533
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
535534
const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
536535
const fileTreeEntries = diffFileTreeEntries(renderableFiles);
537-
const [codeViewReveal] = useState(createCodeViewFileReveal);
538-
const requestTreeReveal = (fileKey: string) => codeViewReveal.request(codeView, fileKey);
536+
const codeViewReveal = useCodeViewFileReveal();
539537
const revealDiffFile = (filePath: string) => {
540538
const index = renderableFileEntries.findIndex(
541539
(candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
@@ -550,14 +548,10 @@ export default function DiffPanel({
550548
if (lazySource && index >= settledFileCount) {
551549
requestFile(index);
552550
}
553-
requestTreeReveal(file.fileKey);
551+
codeViewReveal.request(file.fileKey);
554552
return true;
555553
};
556554

557-
// The code view keeps the post-render handler it was given; a file it did not hold yet when
558-
// asked is positioned once it renders it.
559-
const flushCodeViewReveal = useStableCallback(() => codeViewReveal.flush(codeView));
560-
561555
// A file another view asked to reveal (a chat diff link): retried as the diff loads until it
562556
// holds the file, then not again until a new request, so it does not undo what the user did since.
563557
const externalRevealRef = useRef<string | null>(null);
@@ -1086,7 +1080,7 @@ export default function DiffPanel({
10861080
>
10871081
<AnnotatableCodeView
10881082
key={collapseScopeKey ?? reviewSectionId}
1089-
viewerRef={setCodeView}
1083+
viewerRef={codeViewReveal.attach}
10901084
codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
10911085
className="h-full min-h-0 overflow-auto"
10921086
files={codeViewFiles}
@@ -1145,7 +1139,7 @@ export default function DiffPanel({
11451139
preferredHighlighter: PREFERRED_HIGHLIGHTER,
11461140
themeType: resolvedTheme as DiffThemeType,
11471141
stickyHeaders: true,
1148-
onPostRender: flushCodeViewReveal,
1142+
onPostRender: codeViewReveal.flush,
11491143
...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
11501144
}}
11511145
/>

‎apps/web/src/components/diffs/useCodeViewFileReveal.test.ts‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,34 +19,54 @@ describe("createCodeViewFileReveal", () => {
1919
it("scrolls at once to a file the viewer holds", () => {
2020
const reveal = createCodeViewFileReveal();
2121
const view = viewer(["a"]);
22+
reveal.attach(view);
2223

23-
reveal.request(view, "a");
24+
reveal.request("a");
2425

2526
expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
2627
});
2728

2829
it("keeps a missing file pending until a flush finds it, then drops it", () => {
2930
const reveal = createCodeViewFileReveal();
3031
const view = viewer([]);
32+
reveal.attach(view);
3133

32-
reveal.request(view, "a");
33-
reveal.flush(view);
34+
reveal.request("a");
35+
reveal.flush();
3436
expect(view.scrolls).toEqual([]);
3537

3638
view.items.add("a");
37-
reveal.flush(view);
38-
reveal.flush(view);
39+
reveal.flush();
40+
reveal.flush();
3941
expect(view.scrolls).toHaveLength(1);
4042
});
4143

42-
it("drops a pending reveal when another viewer replaces the one it was asked of", () => {
44+
it("applies a reveal asked before the viewer mounted once it holds the file", () => {
45+
const reveal = createCodeViewFileReveal();
46+
const view = viewer([]);
47+
48+
reveal.request("a");
49+
reveal.attach(view);
50+
expect(view.scrolls).toEqual([]);
51+
52+
view.items.add("a");
53+
reveal.flush();
54+
expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
55+
});
56+
57+
it("drops a pending reveal when its viewer detaches, and positions the next viewer on request", () => {
4358
const reveal = createCodeViewFileReveal();
4459
const first = viewer([]);
4560
const second = viewer(["a"]);
61+
reveal.attach(first);
4662

47-
reveal.request(first, "a");
48-
reveal.flush(second);
49-
63+
reveal.request("a");
64+
reveal.attach(null);
65+
reveal.attach(second);
66+
reveal.flush();
5067
expect(second.scrolls).toEqual([]);
68+
69+
reveal.request("a");
70+
expect(second.scrolls).toHaveLength(1);
5171
});
5272
});

‎apps/web/src/components/diffs/useCodeViewFileReveal.ts‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,35 @@ interface FileRevealHandle {
88
}
99

1010
/**
11-
* Scrolls a code view to a file. A file the viewer does not hold yet stays
12-
* pending until `flush` (from the viewer's post-render) finds it. A pending
13-
* reveal belongs to the viewer it was asked of, so a remounted viewer, such as
14-
* one for another diff scope, drops it.
11+
* Scrolls a code view to a file. `attach` is the viewer's ref and `flush` its post-render
12+
* handler, so a reveal asked before the viewer mounts, or for a file it does not hold yet, is
13+
* positioned once it does. A reveal belongs to the diff it was asked of, so detaching the viewer,
14+
* such as remounting it for another diff scope, drops it.
1515
*/
1616
export function createCodeViewFileReveal() {
17-
let pending: { readonly viewer: FileRevealHandle; readonly fileKey: string } | null = null;
18-
const apply = (viewer: FileRevealHandle, fileKey: string) => {
19-
if (!viewer.getInstance() || viewer.getItem(fileKey) === undefined) return false;
20-
viewer.scrollTo({ type: "item", id: fileKey, align: "start" });
21-
return true;
17+
let viewer: FileRevealHandle | null = null;
18+
let pending: string | null = null;
19+
const flush = () => {
20+
if (pending === null || viewer === null) return;
21+
if (!viewer.getInstance() || viewer.getItem(pending) === undefined) return;
22+
viewer.scrollTo({ type: "item", id: pending, align: "start" });
23+
pending = null;
2224
};
2325
return {
24-
/** Whether the viewer was positioned now, rather than left pending or dropped. */
25-
request(viewer: FileRevealHandle | null, fileKey: string): boolean {
26-
const applied = viewer !== null && apply(viewer, fileKey);
27-
pending = viewer === null || applied ? null : { viewer, fileKey };
28-
return applied;
26+
attach(next: FileRevealHandle | null) {
27+
if (viewer !== null && next !== viewer) pending = null;
28+
viewer = next;
29+
flush();
2930
},
30-
flush(viewer: FileRevealHandle | null) {
31-
if (pending === null || pending.viewer !== viewer) return;
32-
if (apply(pending.viewer, pending.fileKey)) pending = null;
31+
request(fileKey: string) {
32+
pending = fileKey;
33+
flush();
3334
},
35+
flush,
3436
};
3537
}
3638

37-
export function useCodeViewFileReveal(viewer: FileRevealHandle | null) {
39+
export function useCodeViewFileReveal() {
3840
const [reveal] = useState(createCodeViewFileReveal);
39-
return (fileKey: string) => reveal.request(viewer, fileKey);
41+
return reveal;
4042
}

‎apps/web/src/components/pullRequest/PullRequestCodeTab.tsx‎

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
sourceControlClients,
44
} from "@t3tools/client-runtime/source-control-clients";
55
import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
6-
import type { CodeViewAnnotationArgs, CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
6+
import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react";
77
import type {
88
EnvironmentId,
99
PullRequestDetailView,
@@ -36,7 +36,6 @@ import {
3636
use,
3737
useEffect,
3838
useEffectEvent,
39-
useLayoutEffect,
4039
useRef,
4140
useState,
4241
type ReactNode,
@@ -313,9 +312,6 @@ function PullRequestCodeTab({
313312
readonly cursor: string | null;
314313
readonly slices: ReadonlyArray<DiffSlice>;
315314
}>({ key: "", cursor: null, slices: NO_SLICES });
316-
const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup, undefined> | null>(
317-
null,
318-
);
319315

320316
const referenceKey = pullRequestReviewKey(reference);
321317
const commit = selectedCommitOid;
@@ -454,7 +450,7 @@ function PullRequestCodeTab({
454450
refreshFilesViewed();
455451
}, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]);
456452

457-
const requestTreeReveal = useCodeViewFileReveal(viewer);
453+
const codeViewReveal = useCodeViewFileReveal();
458454
const answeredRevealNonce = useRef<number | null>(null);
459455

460456
const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
@@ -701,14 +697,14 @@ function PullRequestCodeTab({
701697

702698
const revealFile = (path: string) => {
703699
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
704-
if (item === undefined) return false;
705-
// Unfold only: a reveal retried before the unfold renders must not fold the file again.
700+
if (item === undefined) return;
701+
// Unfold only: a second reveal before the unfold renders must not fold the file again.
706702
if (item.collapsed === true) {
707703
setToggledFiles((current) =>
708704
toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
709705
);
710706
}
711-
return requestTreeReveal(item.id);
707+
codeViewReveal.request(item.id);
712708
};
713709

714710
const toggleAllFiles = () => {
@@ -848,6 +844,7 @@ function PullRequestCodeTab({
848844
enableLineSelection: canSelectLines && draft === null,
849845
onGutterUtilityClick: beginComment,
850846
onLineSelectionEnd: beginComment,
847+
onPostRender: codeViewReveal.flush,
851848
};
852849

853850
const runThreadCommand = async (
@@ -1284,22 +1281,22 @@ function PullRequestCodeTab({
12841281
</div>
12851282
</div>
12861283
);
1287-
// The viewer takes new items in its own layout effect and attaches after the first commit, so
1288-
// a reveal can only position after commit. It stays unanswered until it does, and a file not
1289-
// loaded yet pages forward each time a slice arrives.
1284+
// A file not loaded yet pages forward each time a slice arrives; once loaded, the viewer
1285+
// positions it when it renders it.
12901286
const answerReveal = useEffectEvent(() => {
12911287
if (revealRequest === null || answeredRevealNonce.current === revealRequest.nonce) return;
12921288
if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
12931289
if (canLoadNextSlice) loadNextSlice();
12941290
return;
12951291
}
1296-
if (revealFile(revealRequest.path)) answeredRevealNonce.current = revealRequest.nonce;
1292+
answeredRevealNonce.current = revealRequest.nonce;
1293+
revealFile(revealRequest.path);
12971294
});
1298-
useLayoutEffect(() => {
1299-
// oxlint-disable-next-line react/set-state-in-effect -- Positioning the viewer is the external sync; paging forward and unfolding set state only on the way there.
1295+
useEffect(() => {
1296+
// oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
13001297
answerReveal();
1301-
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load and the viewer attaches until the requested file is positioned.
1302-
}, [canLoadNextSlice, items, revealRequest, viewer]);
1298+
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
1299+
}, [canLoadNextSlice, items, revealRequest]);
13031300
useEffect(() => {
13041301
if (commit !== null && selectedCommit === undefined) {
13051302
onSelectedCommitChange(null);
@@ -1435,7 +1432,7 @@ function PullRequestCodeTab({
14351432
<StyledDiffCodeView<ReviewAnnotationGroup>
14361433
className="@container h-full overflow-auto [scrollbar-gutter:stable]"
14371434
containerRef={scrollerRef}
1438-
viewerRef={setViewer}
1435+
viewerRef={codeViewReveal.attach}
14391436
items={items}
14401437
selectedLines={selectedLines}
14411438
onSelectedLinesChange={setSelectedLines}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { act, fakeTimers, render } from "../../test/render";
4+
import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "./useLiveRefresh";
5+
6+
function Probe(props: {
7+
readonly refresh: () => void;
8+
readonly viewKey: string;
9+
readonly enabled?: boolean;
10+
readonly intervalMs?: number | null;
11+
readonly refreshOnShow?: boolean;
12+
}) {
13+
useLiveRefresh(props.refresh, {
14+
key: props.viewKey,
15+
enabled: props.enabled ?? true,
16+
...(props.intervalMs !== undefined ? { intervalMs: props.intervalMs } : {}),
17+
...(props.refreshOnShow !== undefined ? { refreshOnShow: props.refreshOnShow } : {}),
18+
});
19+
return null;
20+
}
21+
22+
describe("useLiveRefresh", () => {
23+
it("with refreshOnShow, reads on every show unless it read within the floor", async () => {
24+
const refresh = vi.fn();
25+
// The first enable reads the clock.
26+
using _timers = fakeTimers({ now: 1_000_000 });
27+
const probe = (enabled: boolean) => (
28+
<Probe refresh={refresh} viewKey="show" enabled={enabled} refreshOnShow intervalMs={null} />
29+
);
30+
// A bare hook probe; nothing here navigates.
31+
await using screen = await render(probe(true), { router: false });
32+
expect(refresh).toHaveBeenCalledTimes(1);
33+
34+
await screen.rerender(probe(false));
35+
await act(() => vi.advanceTimersByTime(LIVE_REFRESH_MIN_INTERVAL_MS - 1));
36+
await screen.rerender(probe(true));
37+
expect(refresh).toHaveBeenCalledTimes(1);
38+
39+
await screen.rerender(probe(false));
40+
await act(() => vi.advanceTimersByTime(1));
41+
await screen.rerender(probe(true));
42+
expect(refresh).toHaveBeenCalledTimes(2);
43+
});
44+
45+
it("with intervalMs null, never refreshes on a timer", async () => {
46+
const periodic = vi.fn();
47+
const untimed = vi.fn();
48+
// The interaction clock starts when the first view mounts.
49+
using _timers = fakeTimers({ now: 1_000_000 });
50+
await using _screen = await render(
51+
<>
52+
<Probe refresh={periodic} viewKey="periodic" intervalMs={60_000} />
53+
<Probe refresh={untimed} viewKey="untimed" intervalMs={null} />
54+
</>,
55+
// A bare hook probe; nothing here navigates.
56+
{ router: false },
57+
);
58+
59+
// Past the default 5 minute interval, but inside the 6 minute idle cutoff.
60+
await act(() => vi.advanceTimersByTime(5.5 * 60_000));
61+
62+
expect(periodic).toHaveBeenCalledTimes(5);
63+
expect(untimed).not.toHaveBeenCalled();
64+
});
65+
});

0 commit comments

Comments
 (0)