Skip to content

Commit 8cbc959

Browse files
Umais-Adeedclaudejuliusmarminge
authored
fix(web): files marked Viewed stay folded when a pull request's Code tab opens again (#34168)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 399df48 commit 8cbc959

4 files changed

Lines changed: 125 additions & 51 deletions

File tree

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

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,43 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
5656
};
5757
});
5858

59-
const mocks = vi.hoisted(() => ({ paged: false, diffCommits: [] as Array<string | undefined> }));
59+
const mocks = vi.hoisted(() => ({
60+
paged: false,
61+
diffCommits: [] as Array<string | undefined>,
62+
viewedPaths: null as ReadonlySet<string> | null,
63+
viewedListeners: new Set<() => void>(),
64+
}));
65+
66+
function deliverViewedPaths(paths: ReadonlySet<string> | null) {
67+
mocks.viewedPaths = paths;
68+
for (const listener of mocks.viewedListeners) listener();
69+
}
6070

6171
vi.mock(import("~/state/use-atom-command"), async (original) => ({
6272
...(await original()),
6373
useAtomCommand: (() => vi.fn()) as never,
6474
}));
75+
vi.mock(import("./usePullRequestFilesViewed"), async () => {
76+
const { useSyncExternalStore } = await import("react");
77+
const subscribe = (listener: () => void) => {
78+
mocks.viewedListeners.add(listener);
79+
return () => mocks.viewedListeners.delete(listener);
80+
};
81+
return {
82+
usePullRequestFilesViewed: () => {
83+
const viewedPaths = useSyncExternalStore(subscribe, () => mocks.viewedPaths);
84+
return {
85+
enabled: viewedPaths !== null,
86+
isViewed: (path: string) => viewedPaths?.has(path) === true,
87+
isStale: () => false,
88+
setViewed: () => {},
89+
truncated: false,
90+
error: null,
91+
refresh: () => {},
92+
};
93+
},
94+
};
95+
});
6596
vi.mock(import("~/state/pullRequests"), async (original) => {
6697
const actual = await original();
6798
return {
@@ -136,6 +167,8 @@ function setup({ paged }: { paged: boolean }) {
136167
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
137168
mocks.paged = paged;
138169
mocks.diffCommits = [];
170+
mocks.viewedPaths = null;
171+
mocks.viewedListeners.clear();
139172
}
140173

141174
const tab = (
@@ -174,6 +207,30 @@ it("keeps the diff after a refresh that brings back the same page", async () =>
174207
await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
175208
});
176209

210+
// regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it
211+
it("keeps a revealed file open when its Viewed mark loads afterwards", async () => {
212+
setup({ paged: false });
213+
__setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
214+
using _preferences = {
215+
[Symbol.dispose]() {
216+
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
217+
},
218+
};
219+
mocks.viewedPaths = new Set();
220+
const container = document.createElement("div");
221+
container.className = "flex h-[700px] w-[900px]";
222+
await using screen = await render(tab(0, { path: "a.ts", nonce: 1 }), { container });
223+
await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
224+
225+
deliverViewedPaths(new Set(["a.ts"]));
226+
await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked();
227+
228+
await expect
229+
.element(screen.getByRole("button", { name: "Collapse diff" }))
230+
.toHaveAttribute("aria-expanded", "true");
231+
await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
232+
});
233+
177234
function pagedContainer() {
178235
const container = document.createElement("div");
179236
container.className = "flex h-[500px] w-[900px]";

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

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,9 @@ import {
123123
getFileViewedRange,
124124
isFileDiffCollapsed,
125125
isLineInFileDiff,
126-
toggleFileDiffFoldForViewed,
126+
withFileDiffFold,
127127
type DiffFoldOverride,
128+
type FileDiffFoldChoices,
128129
} from "./pullRequestDiff.logic";
129130
import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";
130131
import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState";
@@ -385,7 +386,7 @@ function PullRequestCodeTab({
385386
diffLayout: settings.diffLayout,
386387
wordWrap: settings.wordWrap,
387388
}));
388-
const [toggledFiles, setToggledFiles] = useState<ReadonlySet<string>>(() => new Set());
389+
const [foldChoices, setFoldChoices] = useState<FileDiffFoldChoices>(() => new Map());
389390
const [lastViewedFileKey, setLastViewedFileKey] = useState<string | null>(null);
390391
const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);
391392
const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);
@@ -430,7 +431,7 @@ function PullRequestCodeTab({
430431
setLastViewedFileKey(null);
431432
setDraft(null);
432433
setSelectedLines(null);
433-
setToggledFiles(new Set());
434+
setFoldChoices(new Map());
434435
setFoldOverride(null);
435436
setVisibleCommitCount(COMMIT_PAGE_SIZE);
436437
setOrphansOpen(false);
@@ -740,9 +741,17 @@ function PullRequestCodeTab({
740741
</div>
741742
);
742743

744+
// A stale mark means the file changed since it was viewed; Fold all and Expand all outrank marks.
745+
const foldsAsViewed = (path: string) =>
746+
foldOverride === null && filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path);
743747
const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
744748
({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
745-
const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);
749+
const collapsed = isFileDiffCollapsed(
750+
fileKey,
751+
effectiveFoldOverride,
752+
foldChoices,
753+
foldsAsViewed(path),
754+
);
746755
const viewedMark = filesViewedEnabled
747756
? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`
748757
: "";
@@ -783,13 +792,17 @@ function PullRequestCodeTab({
783792
);
784793
};
785794

786-
const toggleFile = (fileKey: string) =>
787-
setToggledFiles((current) => {
788-
const next = new Set(current);
789-
if (next.has(fileKey)) next.delete(fileKey);
790-
else next.add(fileKey);
791-
return next;
792-
});
795+
const toggleFile = (fileKey: string) => {
796+
const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path;
797+
const viewed = path !== undefined && foldsAsViewed(path);
798+
setFoldChoices((current) =>
799+
withFileDiffFold(
800+
current,
801+
fileKey,
802+
!isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed),
803+
),
804+
);
805+
};
793806

794807
const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => {
795808
const range = getFileViewedRange(
@@ -799,12 +812,8 @@ function PullRequestCodeTab({
799812
);
800813
setLastViewedFileKey(fileKey);
801814
for (const file of range) setViewed(file.path, viewed);
802-
setToggledFiles((current) =>
803-
range.reduce(
804-
(next, file) =>
805-
toggleFileDiffFoldForViewed(file.fileKey, viewed, effectiveFoldOverride, next),
806-
current,
807-
),
815+
setFoldChoices((current) =>
816+
range.reduce((next, file) => withFileDiffFold(next, file.fileKey, viewed), current),
808817
);
809818
};
810819
const fileViewedToggle = {
@@ -817,19 +826,15 @@ function PullRequestCodeTab({
817826
const revealFile = (path: string, range?: SelectedLineRange) => {
818827
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
819828
if (item === undefined) return;
820-
// Unfold only: a second reveal before the unfold renders must not fold the file again.
821-
if (item.collapsed === true) {
822-
setToggledFiles((current) =>
823-
toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
824-
);
825-
}
829+
// Record the unfold even when already open, so a Viewed mark that loads later cannot fold it.
830+
setFoldChoices((current) => withFileDiffFold(current, item.id, false));
826831
if (range) setSelectedLines({ id: item.id, range });
827832
codeViewReveal.request(item.id, range);
828833
};
829834

830835
const toggleAllFiles = () => {
831836
setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
832-
setToggledFiles(new Set());
837+
setFoldChoices(new Map());
833838
};
834839

835840
const orderedCommits = // GitLab preserves UTC offsets, so compare instants.
@@ -971,9 +976,7 @@ function PullRequestCodeTab({
971976
onPostRender: codeViewReveal.flush,
972977
// Find may repeat requests before render; only unfold, never toggle.
973978
onRevealSearchMatch: (item: CodeViewItem<ReviewAnnotationGroup>) =>
974-
setToggledFiles((current) =>
975-
toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
976-
),
979+
setFoldChoices((current) => withFileDiffFold(current, item.id, false)),
977980
};
978981

979982
const runThreadCommand = async (

‎apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
getFileViewedRange,
66
isFileDiffCollapsed,
77
isLineInFileDiff,
8-
toggleFileDiffFoldForViewed,
8+
withFileDiffFold,
99
} from "./pullRequestDiff.logic";
1010

1111
function fileWithHunks(
@@ -43,16 +43,29 @@ describe("isLineInFileDiff", () => {
4343
describe("isFileDiffCollapsed", () => {
4444
// regression: #9174 diffs now expand by default; a reader's fold must survive new slices
4545
it("keeps a file the reader folded closed as the next slice arrives", () => {
46-
const toggled = new Set(["b.ts"]);
47-
expect(isFileDiffCollapsed("b.ts", null, toggled)).toBe(true);
48-
expect(isFileDiffCollapsed("c.ts", null, toggled)).toBe(false);
46+
const choices = new Map([["b.ts", true]]);
47+
expect(isFileDiffCollapsed("b.ts", "expanded", choices)).toBe(true);
48+
expect(isFileDiffCollapsed("c.ts", "expanded", choices)).toBe(false);
49+
});
50+
51+
it("folds a file marked Viewed when the Code tab mounts again with no fold choices", () => {
52+
expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), true)).toBe(true);
53+
expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), false)).toBe(false);
54+
});
55+
56+
it("keeps a reader's choice when the file's Viewed mark loads later", () => {
57+
const choices = new Map([["a.ts", false]]);
58+
expect(isFileDiffCollapsed("a.ts", "expanded", choices, false)).toBe(false);
59+
expect(isFileDiffCollapsed("a.ts", "expanded", choices, true)).toBe(false);
4960
});
5061
});
5162

52-
describe("toggleFileDiffFoldForViewed", () => {
53-
it("moves against whatever the toolbar last asked for", () => {
54-
expect([...toggleFileDiffFoldForViewed("a.ts", true, "expanded", new Set())]).toEqual(["a.ts"]);
55-
expect(toggleFileDiffFoldForViewed("a.ts", false, "expanded", new Set()).size).toBe(0);
63+
describe("withFileDiffFold", () => {
64+
it("records an absolute choice and keeps the same map when nothing changes", () => {
65+
const folded = withFileDiffFold(new Map(), "a.ts", true);
66+
expect(folded.get("a.ts")).toBe(true);
67+
expect(withFileDiffFold(folded, "a.ts", true)).toBe(folded);
68+
expect(withFileDiffFold(folded, "a.ts", false).get("a.ts")).toBe(false);
5669
});
5770
});
5871

‎apps/web/src/components/pullRequest/pullRequestDiff.logic.ts‎

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,28 +16,29 @@ export function isLineInFileDiff(
1616

1717
export type DiffFoldOverride = "expanded" | "folded" | null;
1818

19-
/** Keep fold choices relative to the toolbar so later pages inherit Fold all. */
19+
/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */
20+
export type FileDiffFoldChoices = ReadonlyMap<string, boolean>;
21+
22+
/**
23+
* A reader's own choice wins. Otherwise the toolbar decides, and a file still marked Viewed
24+
* starts folded. Fold all and Expand all clear the choices, so later pages follow the toolbar.
25+
*/
2026
export function isFileDiffCollapsed(
2127
fileKey: string,
2228
foldOverride: DiffFoldOverride,
23-
toggledFileKeys: ReadonlySet<string>,
29+
choices: FileDiffFoldChoices,
30+
viewed = false,
2431
): boolean {
25-
const foldedByDefault = foldOverride === "folded";
26-
return toggledFileKeys.has(fileKey) ? !foldedByDefault : foldedByDefault;
32+
return choices.get(fileKey) ?? (foldOverride === "folded" || viewed);
2733
}
2834

29-
export function toggleFileDiffFoldForViewed(
35+
export function withFileDiffFold(
36+
choices: FileDiffFoldChoices,
3037
fileKey: string,
31-
viewed: boolean,
32-
foldOverride: DiffFoldOverride,
33-
toggledFileKeys: ReadonlySet<string>,
34-
): ReadonlySet<string> {
35-
if (isFileDiffCollapsed(fileKey, foldOverride, toggledFileKeys) === viewed)
36-
return toggledFileKeys;
37-
const next = new Set(toggledFileKeys);
38-
if (next.has(fileKey)) next.delete(fileKey);
39-
else next.add(fileKey);
40-
return next;
38+
collapsed: boolean,
39+
): FileDiffFoldChoices {
40+
if (choices.get(fileKey) === collapsed) return choices;
41+
return new Map(choices).set(fileKey, collapsed);
4142
}
4243

4344
export function getFileViewedRange<T extends { readonly fileKey: string }>(

0 commit comments

Comments
 (0)