From c9b99ac0480663e1eb607f97fd2658ca7f1e7ec9 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:14:24 +0100 Subject: [PATCH 01/13] test: expanding or collapsing all diffs keeps hidden test files' folds Co-authored-by: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 23 +++++++++ apps/web/src/lib/diffCollapse.test.ts | 15 ++++++ ...ble-diffs-keeps-hidden-tests-folded.e2e.ts | 50 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 apps/web/src/lib/diffCollapse.test.ts create mode 100644 scripts/scenarios/expanding-visible-diffs-keeps-hidden-tests-folded.e2e.ts diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 4d305c4da66ed..3b2b3f2abe565 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -341,6 +341,29 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it await expectFileHeaderShown(screen, container, "late.test.ts"); }); +it("keeps a hidden test file folded when all shown files expand", async () => { + setup({ paged: true }); + using _hidden = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + }, + }; + await using screen = await render(tab(0), { container: pagedContainer() }); + // Files keep their order, so the second header is early-1.test.ts while tests are shown. + const testFileToggle = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1); + await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); + const filter = screen.getByRole("button", { name: "Hide test files" }); + await filter.click(); + await expect.element(filter).toHaveAttribute("aria-pressed", "true"); + + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "true"); + await filter.click(); + + await expect.element(filter).toHaveAttribute("aria-pressed", "false"); + await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); +}); + it("never requests the diff of a selected commit the pull request no longer has", async () => { setup({ paged: false }); const container = document.createElement("div"); diff --git a/apps/web/src/lib/diffCollapse.test.ts b/apps/web/src/lib/diffCollapse.test.ts new file mode 100644 index 0000000000000..038a8898aa628 --- /dev/null +++ b/apps/web/src/lib/diffCollapse.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { toggleAllDiffFiles } from "./diffCollapse"; + +describe("toggleAllDiffFiles", () => { + it.each([ + { action: "expanding", collapsed: ["a", "b", "hidden"], expected: ["hidden"] }, + { action: "collapsing", collapsed: ["a", "hidden"], expected: ["a", "b", "hidden"] }, + ])( + "keeps a folded file outside the given ones folded when $action", + ({ collapsed, expected }) => { + expect([...toggleAllDiffFiles(["a", "b"], new Set(collapsed))].toSorted()).toEqual(expected); + }, + ); +}); diff --git a/scripts/scenarios/expanding-visible-diffs-keeps-hidden-tests-folded.e2e.ts b/scripts/scenarios/expanding-visible-diffs-keeps-hidden-tests-folded.e2e.ts new file mode 100644 index 0000000000000..06f596f0d2445 --- /dev/null +++ b/scripts/scenarios/expanding-visible-diffs-keeps-hidden-tests-folded.e2e.ts @@ -0,0 +1,50 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Expanding visible diffs keeps a hidden test file folded", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo", { + "notes.txt": "Old implementation notes\n", + "notes.test.ts": "const expected = 1;\n", + }); + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(`${project}/notes.txt`, "New implementation notes\n"); + yield* fs.writeFileString(`${project}/notes.test.ts`, "const expected = 2;\n"); + }), + ); + const thread = await t3.thread({ project, title: "Diff folds", messages: ["first"] }); + + await t3.open(thread); + await screen.getByText("first fixture turn complete", { exact: false }).waitFor(); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByText("Diff").tap(); + + const fileToggle = (path: string, expanded: boolean) => + screen.getByRole("button", `${expanded ? "Collapse" : "Expand"} ${path}`, { exact: true }); + for (const path of ["notes.test.ts", "notes.txt"]) { + // Open each file once to load its patch before testing the saved folds. + await fileToggle(path, false).tap(); + await fileToggle(path, true).tap(); + await fileToggle(path, false).waitFor(); + } + + const filter = screen.getByRole("button", "Hide test files", { exact: true }); + await filter.tap(); + await fileToggle("notes.test.ts", false).waitFor({ state: "hidden" }); + await screen.getByRole("button", "Expand all files", { exact: true }).tap(); + await fileToggle("notes.txt", true).waitFor(); + await filter.tap(); + + const testFile = screen.getByRole("button", /^(Collapse|Expand) notes\.test\.ts$/); + await testFile.waitFor(); + await app.screenshot("test-file-shown-again"); + await expect(testFile).toHaveAttribute("aria-expanded", "false"); + }, +); From e9da7648e8d617f889ff65cc77cec5cea2a1358f Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:18:41 +0100 Subject: [PATCH 02/13] test: pull request Code tab keeps a hidden test file open through collapse all Co-authored-by: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 3b2b3f2abe565..f7403f99c3ee5 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -341,27 +341,31 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it await expectFileHeaderShown(screen, container, "late.test.ts"); }); -it("keeps a hidden test file folded when all shown files expand", async () => { +it("keeps a hidden test file open when all shown files collapse", async () => { setup({ paged: true }); - using _hidden = { + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + using _preferences = { [Symbol.dispose]() { window.localStorage.removeItem("t3code.diffHideTestFiles"); + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); }, }; await using screen = await render(tab(0), { container: pagedContainer() }); - // Files keep their order, so the second header is early-1.test.ts while tests are shown. - const testFileToggle = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1); - await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); const filter = screen.getByRole("button", { name: "Hide test files" }); await filter.click(); await expect.element(filter).toHaveAttribute("aria-pressed", "true"); - await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "true"); + await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); + await expect + .element(screen.getByRole("button", { name: "Expand all files", exact: true })) + .toBeVisible(); await filter.click(); await expect.element(filter).toHaveAttribute("aria-pressed", "false"); - await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); + // Files keep their order, so the second header is early-1.test.ts's. + await expect + .element(screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1)) + .toHaveAttribute("aria-expanded", "true"); }); it("never requests the diff of a selected commit the pull request no longer has", async () => { From dec2f647eaec63b65a5ed438e400635065db237c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:24:13 +0100 Subject: [PATCH 03/13] test: pin the Code tab collapse-all case to a two-file diff whose test file renders Co-authored-by: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index f7403f99c3ee5..10fe39d80a6e5 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -15,7 +15,7 @@ import { __setClientSettingsForTests } from "../../hooks/useSettings"; import { setAppearanceMode } from "../../hooks/useTheme"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; -const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { +const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () => { const { AsyncResult, Atom } = await import("effect/reactivity"); const filePatch = (path: string) => [ @@ -52,6 +52,13 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { // An environment query whose refetch returns equal content hands back the previous value // itself, so a refresh publishes a new result around the very same page. diffAtom: Atom.make(() => AsyncResult.success(firstPage)), + testFileDiffAtom: Atom.make(() => + AsyncResult.success({ + patch: filePatch("a.ts") + filePatch("a.test.ts"), + truncated: false, + nextCursor: null, + }), + ), pagedDiffAtom: Atom.family((cursor: string) => Atom.make(() => AsyncResult.success(pages[cursor]!)), ), @@ -60,6 +67,7 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { const mocks = vi.hoisted(() => ({ paged: false, + withTestFile: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -108,7 +116,8 @@ vi.mock(import("~/state/pullRequests"), async (original) => { ...actual.pullRequestEnvironment, diff: (({ input }: { input: { cursor?: string; commit?: string } }) => { mocks.diffCommits.push(input.commit); - return mocks.paged ? pagedDiffAtom(input.cursor ?? "first") : diffAtom; + if (mocks.paged) return pagedDiffAtom(input.cursor ?? "first"); + return mocks.withTestFile ? testFileDiffAtom : diffAtom; }) as never, }, }; @@ -173,6 +182,7 @@ function setup({ paged }: { paged: boolean }) { window.localStorage.removeItem("t3code.diffHideTestFiles"); __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); mocks.paged = paged; + mocks.withTestFile = false; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -342,7 +352,8 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it }); it("keeps a hidden test file open when all shown files collapse", async () => { - setup({ paged: true }); + setup({ paged: false }); + mocks.withTestFile = true; __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); using _preferences = { [Symbol.dispose]() { @@ -350,7 +361,9 @@ it("keeps a hidden test file open when all shown files collapse", async () => { __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); }, }; - await using screen = await render(tab(0), { container: pagedContainer() }); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render(tab(0), { container }); const filter = screen.getByRole("button", { name: "Hide test files" }); await filter.click(); await expect.element(filter).toHaveAttribute("aria-pressed", "true"); @@ -361,8 +374,8 @@ it("keeps a hidden test file open when all shown files collapse", async () => { .toBeVisible(); await filter.click(); - await expect.element(filter).toHaveAttribute("aria-pressed", "false"); - // Files keep their order, so the second header is early-1.test.ts's. + await expect.element(screen.getByText("a.test.ts", { exact: true }).first()).toBeVisible(); + // Test files sort after the others, so the second header is a.test.ts's. await expect .element(screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1)) .toHaveAttribute("aria-expanded", "true"); From d7420d4e25153604ecbe7e1003b2e338ee8b9b1f Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:25:19 +0100 Subject: [PATCH 04/13] fix(web): expand and collapse all leave hidden test files' folds alone The diff panel's toggle now changes only the shown files' folds, and the pull request Code tab records the current fold of each file the test filter hides before it switches the override. Co-authored-by: Claude Opus 5.5 --- .../pullRequest/PullRequestCodeTab.tsx | 21 ++++++++++++++++++- apps/web/src/lib/diffCollapse.ts | 9 +++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f29d002c2bf81..5aa3d2d4cfb02 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1043,7 +1043,26 @@ function PullRequestCodeTab({ const toggleAllFiles = () => { setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); - setFoldChoices(new Map()); + // A file the test filter hides keeps the fold it has now. + const shownFiles = new Set(files); + setFoldChoices( + (current) => + new Map( + loadedFiles + .filter((file) => !shownFiles.has(file)) + .map((file) => { + const fileKey = buildFileDiffRenderKey(file); + const viewed = foldsAsViewed(resolveFileDiffPath(file)); + const collapsed = isFileDiffCollapsed( + fileKey, + effectiveFoldOverride, + current, + viewed, + ); + return [fileKey, collapsed] as const; + }), + ), + ); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. diff --git a/apps/web/src/lib/diffCollapse.ts b/apps/web/src/lib/diffCollapse.ts index 51bdcaf94ac8a..2c582757bd8e2 100644 --- a/apps/web/src/lib/diffCollapse.ts +++ b/apps/web/src/lib/diffCollapse.ts @@ -5,9 +5,16 @@ export function areAllDiffFilesCollapsed( return fileKeys.length > 0 && fileKeys.every((fileKey) => collapsedFileKeys.has(fileKey)); } +/** Expands or collapses all of `fileKeys`; every other file, such as a hidden one, keeps its fold. */ export function toggleAllDiffFiles( fileKeys: ReadonlyArray, collapsedFileKeys: ReadonlySet, ): ReadonlySet { - return areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? new Set() : new Set(fileKeys); + const collapse = !areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys); + const next = new Set(collapsedFileKeys); + for (const fileKey of fileKeys) { + if (collapse) next.add(fileKey); + else next.delete(fileKey); + } + return next; } From 6915fa329a905a7d99dc746357aa79966fae60b9 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:54:44 +0100 Subject: [PATCH 05/13] test: restore the Code tab expand-all case on a diff whose second header is the test file Co-authored-by: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 10fe39d80a6e5..30c777538f663 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -54,7 +54,10 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () diffAtom: Atom.make(() => AsyncResult.success(firstPage)), testFileDiffAtom: Atom.make(() => AsyncResult.success({ - patch: filePatch("a.ts") + filePatch("a.test.ts"), + patch: + filePatch("early-0.ts") + + filePatch("early-1.test.ts") + + filePatch("early-2.generated.ts"), truncated: false, nextCursor: null, }), @@ -351,6 +354,34 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it await expectFileHeaderShown(screen, container, "late.test.ts"); }); +it("keeps a hidden test file folded when all shown files expand", async () => { + setup({ paged: true }); + // Test files sort after source files, so this diff puts its only test file second. + mocks.paged = false; + mocks.withTestFile = true; + using _hidden = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + }, + }; + await using screen = await render(tab(0), { container: pagedContainer() }); + // Every expanded file stays rendered, so the toggles below keep their positions. + screen.container.className = "flex h-[1000px] w-[900px]"; + // Files keep their order, so the second header is early-1.test.ts while tests are shown. + const testFileToggle = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1); + await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); + const filter = screen.getByRole("button", { name: "Hide test files" }); + await filter.click(); + await expect.element(filter).toHaveAttribute("aria-pressed", "true"); + + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "true"); + await filter.click(); + + await expect.element(filter).toHaveAttribute("aria-pressed", "false"); + await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); +}); + it("keeps a hidden test file open when all shown files collapse", async () => { setup({ paged: false }); mocks.withTestFile = true; @@ -374,8 +405,7 @@ it("keeps a hidden test file open when all shown files collapse", async () => { .toBeVisible(); await filter.click(); - await expect.element(screen.getByText("a.test.ts", { exact: true }).first()).toBeVisible(); - // Test files sort after the others, so the second header is a.test.ts's. + await expect.element(screen.getByText("early-1.test.ts", { exact: true }).first()).toBeVisible(); await expect .element(screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1)) .toHaveAttribute("aria-expanded", "true"); From dbbec2c403d3e6782361924fc1df7ba1cb2cff02 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:15:29 +0100 Subject: [PATCH 06/13] fix(web): retain hidden diff folds when pull request pages refresh Co-authored-by: GPT 6.2 Sol --- .../PullRequestCodeTab.browser.test.tsx | 30 ++++++- .../pullRequest/PullRequestCodeTab.tsx | 90 +++++++++---------- .../src/pullRequestDiffFold.test.ts | 32 ++++++- .../client-runtime/src/pullRequestDiffFold.ts | 11 +++ 4 files changed, 113 insertions(+), 50 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 30c777538f663..e19faa1d3f7e6 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -55,7 +55,7 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () testFileDiffAtom: Atom.make(() => AsyncResult.success({ patch: - filePatch("early-0.ts") + + filePatch(mocks.renameSourceOnRefresh ? "early-0-renamed.ts" : "early-0.ts") + filePatch("early-1.test.ts") + filePatch("early-2.generated.ts"), truncated: false, @@ -71,6 +71,7 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () const mocks = vi.hoisted(() => ({ paged: false, withTestFile: false, + renameSourceOnRefresh: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -186,6 +187,7 @@ function setup({ paged }: { paged: boolean }) { __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); mocks.paged = paged; mocks.withTestFile = false; + mocks.renameSourceOnRefresh = false; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -411,6 +413,32 @@ it("keeps a hidden test file open when all shown files collapse", async () => { .toHaveAttribute("aria-expanded", "true"); }); +it("keeps a hidden test file folded when a refresh renames another file after expand all", async () => { + setup({ paged: false }); + mocks.withTestFile = true; + using _hidden = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + }, + }; + const container = document.createElement("div"); + container.className = "flex h-[1000px] w-[900px]"; + await using screen = await render(tab(0), { container }); + const filter = screen.getByRole("button", { name: "Hide test files" }); + await filter.click(); + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + + mocks.renameSourceOnRefresh = true; + await screen.rerender(tab(1)); + await expect.element(screen.getByText("early-0-renamed.ts", { exact: true })).toBeVisible(); + await filter.click(); + + await expect.element(screen.getByText("early-1.test.ts", { exact: true })).toBeVisible(); + const toggles = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }); + await expect.element(toggles.nth(0)).toHaveAttribute("aria-expanded", "true"); + await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "false"); +}); + it("never requests the diff of a selected commit the pull request no longer has", async () => { setup({ paged: false }); const container = document.createElement("div"); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 5aa3d2d4cfb02..6186c6a2399b9 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,5 +1,6 @@ import { isFileDiffCollapsed, + preserveFileDiffFolds, withFileDiffFold, type DiffFoldOverride, type FileDiffFoldChoices, @@ -82,6 +83,7 @@ import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import { orderDiffFiles } from "./pullRequestFileOrder.logic"; import { + buildFileDiffIdentityKey, buildFileDiffRenderKey, fnv1a32, getDiffLineStat, @@ -451,6 +453,7 @@ function PullRequestCodeTab({ diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, })); + // Render keys change when any file on a page changes; fold choices follow file identity. const [foldChoices, setFoldChoices] = useState(() => new Map()); const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); @@ -607,9 +610,8 @@ function PullRequestCodeTab({ const [withheldLoads, setWithheldLoads] = useState<{ readonly scope: string; readonly paths: ReadonlyArray; - /** The render key each loaded file was last shown under; a changed patch gets a new one. */ - readonly shownKeys: ReadonlyMap; - }>({ scope: "", paths: NO_PATHS, shownKeys: new Map() }); + readonly shownPaths: ReadonlySet; + }>({ scope: "", paths: NO_PATHS, shownPaths: new Set() }); const withheldPaths = withheldLoads.scope === scopeKey ? withheldLoads.paths : NO_PATHS; const withheldInput = { ...reference, ...(commit === null ? {} : { commit }) }; const atomRegistry = useContext(RegistryContext); @@ -707,23 +709,18 @@ function PullRequestCodeTab({ if (hasCutLines(data.patch)) cutFiles.add(file); } else withheldStatuses.set(path, "empty"); }); - // Fold choices follow render keys, so a loaded or refetched patch would otherwise fold again - // when marked Viewed: it opens on first load and keeps its earlier key's choice after. - const rekeyed = [...withheldFiles].flatMap(([path, file]) => { - const key = buildFileDiffRenderKey(file); - return withheldLoads.shownKeys.get(path) === key ? [] : [[path, key] as const]; - }); - if (withheldLoads.scope === scopeKey && rekeyed.length > 0) { + // Open a withheld patch on first load. Refreshes keep the choice for that file. + const newlyShown = [...withheldFiles].filter(([path]) => !withheldLoads.shownPaths.has(path)); + if (newlyShown.length > 0) { setWithheldLoads({ ...withheldLoads, - shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]), + shownPaths: new Set([...withheldLoads.shownPaths, ...newlyShown.map(([path]) => path)]), }); setFoldChoices((current) => - rekeyed.reduce((next, [path, key]) => { - const shown = withheldLoads.shownKeys.get(path); - const collapsed = shown === undefined ? false : current.get(shown); - return collapsed === undefined ? next : withFileDiffFold(next, key, collapsed); - }, current), + newlyShown.reduce( + (next, [, file]) => withFileDiffFold(next, buildFileDiffIdentityKey(file), false), + current, + ), ); } const loadedFiles = @@ -740,7 +737,7 @@ function PullRequestCodeTab({ setWithheldLoads({ scope: scopeKey, paths: [...withheldPaths, path], - shownKeys: withheldLoads.scope === scopeKey ? withheldLoads.shownKeys : new Map(), + shownPaths: withheldLoads.scope === scopeKey ? withheldLoads.shownPaths : new Set(), }); }; const linkAnchor = parsePullRequestAnchor(revealUrl); @@ -949,7 +946,7 @@ function PullRequestCodeTab({ const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { const collapsed = isFileDiffCollapsed( - fileKey, + buildFileDiffIdentityKey(fileDiff), effectiveFoldOverride, foldChoices, foldsAsViewed(path), @@ -995,13 +992,15 @@ function PullRequestCodeTab({ }; const toggleFile = (fileKey: string) => { - const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path; - const viewed = path !== undefined && foldsAsViewed(path); + const file = annotatedFiles.find((file) => file.fileKey === fileKey); + if (file === undefined) return; + const foldKey = buildFileDiffIdentityKey(file.fileDiff); + const viewed = foldsAsViewed(file.path); setFoldChoices((current) => withFileDiffFold( current, - fileKey, - !isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed), + foldKey, + !isFileDiffCollapsed(foldKey, effectiveFoldOverride, current, viewed), ), ); }; @@ -1020,7 +1019,11 @@ function PullRequestCodeTab({ setFoldChoices((current) => range.reduce( (next, file) => - withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), + withFileDiffFold( + next, + buildFileDiffIdentityKey(file.fileDiff), + effectiveFoldOverride === null ? undefined : viewed, + ), current, ), ); @@ -1036,33 +1039,23 @@ function PullRequestCodeTab({ const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. - setFoldChoices((current) => withFileDiffFold(current, item.id, false)); + setFoldChoices((current) => + withFileDiffFold(current, buildFileDiffIdentityKey(item.fileDiff), false), + ); if (range) setSelectedLines({ id: item.id, range }); codeViewReveal.request(item.id, range); }; const toggleAllFiles = () => { - setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); - // A file the test filter hides keeps the fold it has now. + setFoldOverride(allFilesCollapsed ? "expanded" : "folded"); const shownFiles = new Set(files); - setFoldChoices( - (current) => - new Map( - loadedFiles - .filter((file) => !shownFiles.has(file)) - .map((file) => { - const fileKey = buildFileDiffRenderKey(file); - const viewed = foldsAsViewed(resolveFileDiffPath(file)); - const collapsed = isFileDiffCollapsed( - fileKey, - effectiveFoldOverride, - current, - viewed, - ); - return [fileKey, collapsed] as const; - }), - ), - ); + const hiddenFiles = loadedFiles + .filter((file) => !shownFiles.has(file)) + .map((file) => ({ + key: buildFileDiffIdentityKey(file), + viewed: foldsAsViewed(resolveFileDiffPath(file)), + })); + setFoldChoices((current) => preserveFileDiffFolds(current, effectiveFoldOverride, hiddenFiles)); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. @@ -1222,10 +1215,11 @@ function PullRequestCodeTab({ onItemCollapsedChange: ( _item: CodeViewItem, nextItem: CodeViewItem, - ) => - setFoldChoices((current) => - withFileDiffFold(current, nextItem.id, nextItem.collapsed === true), - ), + ) => { + if (nextItem.type !== "diff") return; + const foldKey = buildFileDiffIdentityKey(nextItem.fileDiff); + setFoldChoices((current) => withFileDiffFold(current, foldKey, nextItem.collapsed === true)); + }, }; const runThreadCommand = async ( diff --git a/packages/client-runtime/src/pullRequestDiffFold.test.ts b/packages/client-runtime/src/pullRequestDiffFold.test.ts index 34269c2212a05..9b262fdf53bea 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.test.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { isFileDiffCollapsed, withFileDiffFold } from "./pullRequestDiffFold.ts"; +import { + isFileDiffCollapsed, + preserveFileDiffFolds, + withFileDiffFold, +} from "./pullRequestDiffFold.ts"; describe("isFileDiffCollapsed", () => { it("collapses saved viewed files on reopening and when a later read marks them viewed", () => { @@ -39,3 +43,29 @@ describe("withFileDiffFold", () => { expect(withFileDiffFold(folded, "a.ts", undefined).has("a.ts")).toBe(false); }); }); + +describe("preserveFileDiffFolds", () => { + it.each([ + { before: null, after: "expanded", hiddenFold: true }, + { before: "expanded", after: "folded", hiddenFold: false }, + ] as const)( + "keeps hidden folds when switching from $before to $after", + ({ before, after, hiddenFold }) => { + const kept = preserveFileDiffFolds( + new Map([ + ["hidden-explicit", !hiddenFold], + ["shown", after === "expanded"], + ]), + before, + [ + { key: "hidden-viewed", viewed: true }, + { key: "hidden-explicit", viewed: true }, + ], + ); + expect(isFileDiffCollapsed("hidden-viewed", after, kept, false)).toBe(hiddenFold); + expect(isFileDiffCollapsed("hidden-explicit", after, kept, false)).toBe(!hiddenFold); + expect(isFileDiffCollapsed("shown", after, kept)).toBe(after === "folded"); + expect(isFileDiffCollapsed("later-page", after, kept)).toBe(after === "folded"); + }, + ); +}); diff --git a/packages/client-runtime/src/pullRequestDiffFold.ts b/packages/client-runtime/src/pullRequestDiffFold.ts index 8083c93c25b09..b26169b70672d 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.ts @@ -23,3 +23,14 @@ export function withFileDiffFold( else next.set(fileKey, collapsed); return next; } + +/** Keep the effective fold of files excluded from a bulk fold change. */ +export function preserveFileDiffFolds( + choices: FileDiffFoldChoices, + foldOverride: DiffFoldOverride, + files: ReadonlyArray<{ readonly key: string; readonly viewed: boolean }>, +): FileDiffFoldChoices { + return new Map( + files.map(({ key, viewed }) => [key, isFileDiffCollapsed(key, foldOverride, choices, viewed)]), + ); +} From 41cc305f880b31edaaf018ac85df5d071003e7be Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:34:38 +0100 Subject: [PATCH 07/13] fix(web): scope pull request bulk folds to the test filter Keep saved folds through unrelated patch refreshes and expire them when the file's own patch changes. Apply the bulk choice to eligible files on later pages. Co-authored-by: GPT 6.2 Sol --- .../PullRequestCodeTab.browser.test.tsx | 92 ++++++++++++++++-- .../pullRequest/PullRequestCodeTab.tsx | 94 ++++++++++++------- .../src/pullRequestDiffFold.test.ts | 52 +++++++--- .../client-runtime/src/pullRequestDiffFold.ts | 45 +++++++-- 4 files changed, 220 insertions(+), 63 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index e19faa1d3f7e6..33951c12ef52c 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -8,7 +8,7 @@ import { type PullRequestDiffResult, } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { __setClientSettingsForTests } from "../../hooks/useSettings"; @@ -17,15 +17,15 @@ import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () => { const { AsyncResult, Atom } = await import("effect/reactivity"); - const filePatch = (path: string) => + const filePatch = (path: string, changed = false) => [ `diff --git a/${path} b/${path}`, - "index 1111111..2222222 100644", + `index 1111111..${changed ? "3333333" : "2222222"} 100644`, `--- a/${path}`, `+++ b/${path}`, "@@ -1,6 +1,6 @@", "-before()", - "+after()", + changed ? "+updated()" : "+after()", " one()", " two()", " three()", @@ -46,7 +46,13 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () truncated: true, nextCursor: "page-2", }, - "page-2": { patch: filePatch("late.test.ts"), truncated: false, nextCursor: null }, + get "page-2"() { + return { + patch: (mocks.withLateSourceFile ? filePatch("late.ts") : "") + filePatch("late.test.ts"), + truncated: false, + nextCursor: null, + }; + }, }; return { // An environment query whose refetch returns equal content hands back the previous value @@ -56,7 +62,7 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () AsyncResult.success({ patch: filePatch(mocks.renameSourceOnRefresh ? "early-0-renamed.ts" : "early-0.ts") + - filePatch("early-1.test.ts") + + filePatch("early-1.test.ts", mocks.changeTestOnRefresh) + filePatch("early-2.generated.ts"), truncated: false, nextCursor: null, @@ -70,8 +76,10 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () const mocks = vi.hoisted(() => ({ paged: false, + withLateSourceFile: false, withTestFile: false, renameSourceOnRefresh: false, + changeTestOnRefresh: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -98,7 +106,7 @@ vi.mock(import("./usePullRequestFilesViewed"), async () => { return { enabled: viewedPaths !== null, isViewed: (path: string) => viewedPaths?.has(path) === true, - isStale: () => false, + isStale: (path: string) => mocks.changeTestOnRefresh && path === "early-1.test.ts", setViewed: (path: string, viewed: boolean) => { const next = new Set(mocks.viewedPaths); if (viewed) next.add(path); @@ -186,8 +194,10 @@ function setup({ paged }: { paged: boolean }) { window.localStorage.removeItem("t3code.diffHideTestFiles"); __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); mocks.paged = paged; + mocks.withLateSourceFile = false; mocks.withTestFile = false; mocks.renameSourceOnRefresh = false; + mocks.changeTestOnRefresh = false; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -439,6 +449,74 @@ it("keeps a hidden test file folded when a refresh renames another file after ex await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "false"); }); +it("opens a hidden test file when a refresh changes its patch and makes its Viewed mark stale", async () => { + setup({ paged: false }); + mocks.withTestFile = true; + mocks.viewedPaths = new Set(["early-1.test.ts"]); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + using _preferences = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }, + }; + const container = document.createElement("div"); + container.className = "flex h-[1000px] w-[900px]"; + await using screen = await render(tab(0), { container }); + const toggles = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }); + await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "false"); + const filter = screen.getByRole("button", { name: "Hide test files" }); + await filter.click(); + await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + + mocks.changeTestOnRefresh = true; + await screen.rerender(tab(1)); + await filter.click(); + + await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "true"); + await expect.element(screen.getByText("updated()", { exact: true })).toBeVisible(); +}); + +it("expands later source files while keeping a later hidden test file folded", async () => { + setup({ paged: true }); + mocks.withLateSourceFile = true; + using _hidden = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + window.localStorage.removeItem("t3code.pullRequestFileTreeOpen"); + }, + }; + const container = pagedContainer(); + await using screen = await render(tab(0), { container }); + const filter = screen.getByRole("button", { name: "Hide test files" }); + await filter.click(); + await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible(); + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + + await screen.getByRole("button", { name: "Show file tree", exact: true }).click(); + await screen.getByRole("button", { name: "Load more files", exact: true }).click(); + await expect.element(screen.getByText("2 test files hidden", { exact: true })).toBeVisible(); + await screen.getByRole("button", { name: "Hide file tree", exact: true }).click(); + await filter.click(); + + const scroller = await vi.waitFor(() => { + const surface = container.querySelector(".diff-render-surface"); + expect(surface).not.toBeNull(); + return surface!; + }); + scroller.scrollTop = scroller.scrollHeight; + + const diffToggle = async (path: string) => { + const header = screen.getByText(path, { exact: true }); + await expect.element(header).toBeVisible(); + const { host } = header.element().getRootNode() as ShadowRoot; + return page.elementLocator(host).getByRole("button", { name: /^(Expand|Collapse) diff$/ }); + }; + await expect.element(await diffToggle("late.ts")).toHaveAttribute("aria-expanded", "true"); + await expect.element(await diffToggle("late.test.ts")).toHaveAttribute("aria-expanded", "false"); +}); + it("never requests the diff of a selected commit the pull request no longer has", async () => { setup({ paged: false }); const container = document.createElement("div"); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 6186c6a2399b9..21562ac319302 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,8 +1,8 @@ import { + applyPullRequestDiffFold, + createPullRequestDiffFoldState, isFileDiffCollapsed, - preserveFileDiffFolds, withFileDiffFold, - type DiffFoldOverride, type FileDiffFoldChoices, } from "@t3tools/client-runtime/pull-request-diff-fold"; import { @@ -83,6 +83,7 @@ import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import { orderDiffFiles } from "./pullRequestFileOrder.logic"; import { + buildFileDiffContentVersion, buildFileDiffIdentityKey, buildFileDiffRenderKey, fnv1a32, @@ -240,6 +241,18 @@ type DiffModel = { const diffModels = new WeakMap, Map>(); const patchHashes = new WeakMap(); +const foldKeys = new WeakMap(); + +// A fold choice survives edits elsewhere on the page, but expires when its own patch changes. +function fileDiffFoldKey(file: FileDiffMetadata): string { + let key = foldKeys.get(file); + if (key === undefined) { + key = `${buildFileDiffIdentityKey(file)}\u0000${buildFileDiffContentVersion(file)}`; + foldKeys.set(file, key); + } + return key; +} + // Hashing, ordering and counting every file of a huge pull request costs a second, and the tab // renders far more often than its slices change, so the model is kept per slice list. function diffModel( @@ -453,12 +466,19 @@ function PullRequestCodeTab({ diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, })); - // Render keys change when any file on a page changes; fold choices follow file identity. - const [foldChoices, setFoldChoices] = useState(() => new Map()); + const [foldState, setFoldState] = useState(createPullRequestDiffFoldState); + const defaultFoldOverride = settings.diffFilesCollapsed ? "folded" : null; + const foldOverrideForPath = (path: string) => + (isTestChangedFile(path) ? foldState.testOverride : foldState.sourceOverride) ?? + defaultFoldOverride; + const setFoldChoices = (update: (choices: FileDiffFoldChoices) => FileDiffFoldChoices) => { + setFoldState((current) => { + const choices = update(current.choices); + return choices === current.choices ? current : { ...current, choices }; + }); + }; 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; @@ -499,8 +519,7 @@ function PullRequestCodeTab({ setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); - setFoldChoices(new Map()); - setFoldOverride(null); + setFoldState(createPullRequestDiffFoldState()); setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); @@ -709,7 +728,7 @@ function PullRequestCodeTab({ if (hasCutLines(data.patch)) cutFiles.add(file); } else withheldStatuses.set(path, "empty"); }); - // Open a withheld patch on first load. Refreshes keep the choice for that file. + // Open a withheld patch on first load, then let the saved choice follow that patch. const newlyShown = [...withheldFiles].filter(([path]) => !withheldLoads.shownPaths.has(path)); if (newlyShown.length > 0) { setWithheldLoads({ @@ -718,7 +737,7 @@ function PullRequestCodeTab({ }); setFoldChoices((current) => newlyShown.reduce( - (next, [, file]) => withFileDiffFold(next, buildFileDiffIdentityKey(file), false), + (next, [, file]) => withFileDiffFold(next, fileDiffFoldKey(file), false), current, ), ); @@ -946,9 +965,9 @@ function PullRequestCodeTab({ const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { const collapsed = isFileDiffCollapsed( - buildFileDiffIdentityKey(fileDiff), - effectiveFoldOverride, - foldChoices, + fileDiffFoldKey(fileDiff), + foldOverrideForPath(path), + foldState.choices, foldsAsViewed(path), ); const viewedMark = filesViewedEnabled @@ -994,14 +1013,11 @@ function PullRequestCodeTab({ const toggleFile = (fileKey: string) => { const file = annotatedFiles.find((file) => file.fileKey === fileKey); if (file === undefined) return; - const foldKey = buildFileDiffIdentityKey(file.fileDiff); + const foldKey = fileDiffFoldKey(file.fileDiff); const viewed = foldsAsViewed(file.path); + const override = foldOverrideForPath(file.path); setFoldChoices((current) => - withFileDiffFold( - current, - foldKey, - !isFileDiffCollapsed(foldKey, effectiveFoldOverride, current, viewed), - ), + withFileDiffFold(current, foldKey, !isFileDiffCollapsed(foldKey, override, current, viewed)), ); }; @@ -1021,8 +1037,8 @@ function PullRequestCodeTab({ (next, file) => withFileDiffFold( next, - buildFileDiffIdentityKey(file.fileDiff), - effectiveFoldOverride === null ? undefined : viewed, + fileDiffFoldKey(file.fileDiff), + foldOverrideForPath(file.path) === null ? undefined : viewed, ), current, ), @@ -1039,23 +1055,35 @@ function PullRequestCodeTab({ const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. - setFoldChoices((current) => - withFileDiffFold(current, buildFileDiffIdentityKey(item.fileDiff), false), - ); + setFoldChoices((current) => withFileDiffFold(current, fileDiffFoldKey(item.fileDiff), false)); if (range) setSelectedLines({ id: item.id, range }); codeViewReveal.request(item.id, range); }; const toggleAllFiles = () => { - setFoldOverride(allFilesCollapsed ? "expanded" : "folded"); const shownFiles = new Set(files); - const hiddenFiles = loadedFiles - .filter((file) => !shownFiles.has(file)) - .map((file) => ({ - key: buildFileDiffIdentityKey(file), - viewed: foldsAsViewed(resolveFileDiffPath(file)), - })); - setFoldChoices((current) => preserveFileDiffFolds(current, effectiveFoldOverride, hiddenFiles)); + const filteredTests = hideTestFiles + ? loadedFiles.flatMap((file) => { + const path = resolveFileDiffPath(file); + return isTestChangedFile(path) + ? [ + { + key: fileDiffFoldKey(file), + viewed: foldsAsViewed(path), + hidden: !shownFiles.has(file), + }, + ] + : []; + }) + : null; + setFoldState((current) => + applyPullRequestDiffFold( + current, + allFilesCollapsed ? "expanded" : "folded", + defaultFoldOverride, + filteredTests, + ), + ); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. @@ -1217,7 +1245,7 @@ function PullRequestCodeTab({ nextItem: CodeViewItem, ) => { if (nextItem.type !== "diff") return; - const foldKey = buildFileDiffIdentityKey(nextItem.fileDiff); + const foldKey = fileDiffFoldKey(nextItem.fileDiff); setFoldChoices((current) => withFileDiffFold(current, foldKey, nextItem.collapsed === true)); }, }; diff --git a/packages/client-runtime/src/pullRequestDiffFold.test.ts b/packages/client-runtime/src/pullRequestDiffFold.test.ts index 9b262fdf53bea..6de975c4ae2d5 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.test.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; import { + applyPullRequestDiffFold, + createPullRequestDiffFoldState, isFileDiffCollapsed, - preserveFileDiffFolds, withFileDiffFold, } from "./pullRequestDiffFold.ts"; @@ -44,28 +45,51 @@ describe("withFileDiffFold", () => { }); }); -describe("preserveFileDiffFolds", () => { +describe("applyPullRequestDiffFold", () => { it.each([ { before: null, after: "expanded", hiddenFold: true }, + { before: "folded", after: "expanded", hiddenFold: true }, { before: "expanded", after: "folded", hiddenFold: false }, ] as const)( "keeps hidden folds when switching from $before to $after", ({ before, after, hiddenFold }) => { - const kept = preserveFileDiffFolds( - new Map([ - ["hidden-explicit", !hiddenFold], - ["shown", after === "expanded"], - ]), - before, + const initial = createPullRequestDiffFoldState(); + const previous = + before === null ? initial : applyPullRequestDiffFold(initial, before, null, null); + const next = applyPullRequestDiffFold( + { + ...previous, + choices: new Map([ + ["hidden-explicit", !hiddenFold], + ["shown-source", after === "expanded"], + ]), + }, + after, + null, [ - { key: "hidden-viewed", viewed: true }, - { key: "hidden-explicit", viewed: true }, + { key: "hidden-viewed", viewed: true, hidden: true }, + { key: "hidden-explicit", viewed: true, hidden: true }, + { key: "shown-test", viewed: true, hidden: false }, ], ); - expect(isFileDiffCollapsed("hidden-viewed", after, kept, false)).toBe(hiddenFold); - expect(isFileDiffCollapsed("hidden-explicit", after, kept, false)).toBe(!hiddenFold); - expect(isFileDiffCollapsed("shown", after, kept)).toBe(after === "folded"); - expect(isFileDiffCollapsed("later-page", after, kept)).toBe(after === "folded"); + expect(isFileDiffCollapsed("hidden-viewed", next.testOverride, next.choices, false)).toBe( + hiddenFold, + ); + expect(isFileDiffCollapsed("hidden-explicit", next.testOverride, next.choices)).toBe( + !hiddenFold, + ); + expect(isFileDiffCollapsed("shown-test", next.testOverride, next.choices)).toBe( + after === "folded", + ); + expect(isFileDiffCollapsed("shown-source", next.sourceOverride, next.choices)).toBe( + after === "folded", + ); + expect(isFileDiffCollapsed("later-source", next.sourceOverride, next.choices)).toBe( + after === "folded", + ); + expect(isFileDiffCollapsed("later-test", next.testOverride, next.choices, true)).toBe( + hiddenFold, + ); }, ); }); diff --git a/packages/client-runtime/src/pullRequestDiffFold.ts b/packages/client-runtime/src/pullRequestDiffFold.ts index b26169b70672d..8a8581bf298f5 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.ts @@ -24,13 +24,40 @@ export function withFileDiffFold( return next; } -/** Keep the effective fold of files excluded from a bulk fold change. */ -export function preserveFileDiffFolds( - choices: FileDiffFoldChoices, - foldOverride: DiffFoldOverride, - files: ReadonlyArray<{ readonly key: string; readonly viewed: boolean }>, -): FileDiffFoldChoices { - return new Map( - files.map(({ key, viewed }) => [key, isFileDiffCollapsed(key, foldOverride, choices, viewed)]), - ); +export interface PullRequestDiffFoldState { + readonly sourceOverride: DiffFoldOverride; + readonly testOverride: DiffFoldOverride; + readonly choices: FileDiffFoldChoices; +} + +export function createPullRequestDiffFoldState(): PullRequestDiffFoldState { + return { sourceOverride: null, testOverride: null, choices: new Map() }; +} + +/** Scope the bulk override to the filter at click time, including for files that load later. */ +export function applyPullRequestDiffFold( + current: PullRequestDiffFoldState, + override: NonNullable, + defaultOverride: DiffFoldOverride, + filteredTests: ReadonlyArray<{ + readonly key: string; + readonly viewed: boolean; + readonly hidden: boolean; + }> | null, +): PullRequestDiffFoldState { + const choices = new Map(); + const previousTestOverride = current.testOverride ?? defaultOverride; + for (const { key, viewed, hidden } of filteredTests ?? []) { + choices.set( + key, + hidden + ? isFileDiffCollapsed(key, previousTestOverride, current.choices, viewed) + : override === "folded", + ); + } + return { + sourceOverride: override, + testOverride: filteredTests === null ? override : current.testOverride, + choices, + }; } From 20235c1c526fc3873be4de2991a6bd8b3a76f046 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:40:40 +0100 Subject: [PATCH 08/13] test(web): control when the fold regression loads the next page Co-authored-by: GPT 6.2 Sol --- .../PullRequestCodeTab.browser.test.tsx | 80 ++++++++++--------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 33951c12ef52c..866f397829c49 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -38,22 +38,23 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () truncated: false, nextCursor: null, }; - const pages: Record = { - first: { - patch: Array.from({ length: 40 }, (_, index) => - filePatch(index === 1 ? "early-1.test.ts" : `early-${index}.ts`), - ).join(""), - truncated: true, - nextCursor: "page-2", - }, - get "page-2"() { - return { - patch: (mocks.withLateSourceFile ? filePatch("late.ts") : "") + filePatch("late.test.ts"), + const pagedDiffAtom = Atom.family((shortPages: boolean) => { + const pages: Record = { + first: { + patch: Array.from({ length: shortPages ? 2 : 40 }, (_, index) => + filePatch(index === 1 ? "early-1.test.ts" : `early-${index}.ts`), + ).join(""), + truncated: true, + nextCursor: "page-2", + }, + "page-2": { + patch: (shortPages ? filePatch("late.ts") : "") + filePatch("late.test.ts"), truncated: false, nextCursor: null, - }; - }, - }; + }, + }; + return Atom.family((cursor: string) => Atom.make(AsyncResult.success(pages[cursor]!))); + }); return { // An environment query whose refetch returns equal content hands back the previous value // itself, so a refresh publishes a new result around the very same page. @@ -68,15 +69,13 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () nextCursor: null, }), ), - pagedDiffAtom: Atom.family((cursor: string) => - Atom.make(() => AsyncResult.success(pages[cursor]!)), - ), + pagedDiffAtom, }; }); const mocks = vi.hoisted(() => ({ paged: false, - withLateSourceFile: false, + shortPages: false, withTestFile: false, renameSourceOnRefresh: false, changeTestOnRefresh: false, @@ -128,14 +127,14 @@ vi.mock(import("~/state/pullRequests"), async (original) => { ...actual.pullRequestEnvironment, diff: (({ input }: { input: { cursor?: string; commit?: string } }) => { mocks.diffCommits.push(input.commit); - if (mocks.paged) return pagedDiffAtom(input.cursor ?? "first"); + if (mocks.paged) return pagedDiffAtom(mocks.shortPages)(input.cursor ?? "first"); return mocks.withTestFile ? testFileDiffAtom : diffAtom; }) as never, }, }; }); -import { render } from "../../../test/render"; +import { render, stubGlobal } from "../../../test/render"; import PullRequestCodeTab from "./PullRequestCodeTab"; const detail: PullRequestDetailView = { @@ -194,7 +193,7 @@ function setup({ paged }: { paged: boolean }) { window.localStorage.removeItem("t3code.diffHideTestFiles"); __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); mocks.paged = paged; - mocks.withLateSourceFile = false; + mocks.shortPages = false; mocks.withTestFile = false; mocks.renameSourceOnRefresh = false; mocks.changeTestOnRefresh = false; @@ -480,14 +479,24 @@ it("opens a hidden test file when a refresh changes its patch and makes its View it("expands later source files while keeping a later hidden test file folded", async () => { setup({ paged: true }); - mocks.withLateSourceFile = true; + mocks.shortPages = true; using _hidden = { [Symbol.dispose]() { window.localStorage.removeItem("t3code.diffHideTestFiles"); window.localStorage.removeItem("t3code.pullRequestFileTreeOpen"); }, }; - const container = pagedContainer(); + // Use the file tree's load button to control when the short first page gives way to the next. + using _observer = stubGlobal( + "IntersectionObserver", + class extends IntersectionObserver { + constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { + super(options?.rootMargin === "240px" ? () => {} : callback, options); + } + }, + ); + const container = document.createElement("div"); + container.className = "flex h-[1000px] w-[900px]"; await using screen = await render(tab(0), { container }); const filter = screen.getByRole("button", { name: "Hide test files" }); await filter.click(); @@ -500,21 +509,20 @@ it("expands later source files while keeping a later hidden test file folded", a await screen.getByRole("button", { name: "Hide file tree", exact: true }).click(); await filter.click(); - const scroller = await vi.waitFor(() => { - const surface = container.querySelector(".diff-render-surface"); - expect(surface).not.toBeNull(); - return surface!; - }); - scroller.scrollTop = scroller.scrollHeight; - - const diffToggle = async (path: string) => { - const header = screen.getByText(path, { exact: true }); - await expect.element(header).toBeVisible(); - const { host } = header.element().getRootNode() as ShadowRoot; + await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); + const diffToggle = (path: string) => { + const header = screen.getByText(path, { exact: true }).element(); + const { host } = header.getRootNode() as ShadowRoot; return page.elementLocator(host).getByRole("button", { name: /^(Expand|Collapse) diff$/ }); }; - await expect.element(await diffToggle("late.ts")).toHaveAttribute("aria-expanded", "true"); - await expect.element(await diffToggle("late.test.ts")).toHaveAttribute("aria-expanded", "false"); + await vi.waitFor(() => + expect(diffToggle("late.ts").element()).toHaveAttribute("aria-expanded", "true"), + ); + const scroller = container.querySelector(".diff-render-surface")!; + scroller.scrollTop = scroller.scrollHeight; + await vi.waitFor(() => + expect(diffToggle("late.test.ts").element()).toHaveAttribute("aria-expanded", "false"), + ); }); it("never requests the diff of a selected commit the pull request no longer has", async () => { From 96e221a799bc6bddf4b1c3eb43deb686608f8fbe Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:08:20 +0100 Subject: [PATCH 09/13] test(web): a hand fold on a later test page survives a refresh and filtered bulk toggles Replace the cases that pinned folds to patch content with one that folds a later test file, hides tests, refreshes, collapses and expands all, and shows tests again, and pin bulk folds to the source and test groups. Co-authored-by: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 160 ++++++++---------- .../pullRequest/PullRequestCodeTab.tsx | 123 +++++--------- .../src/pullRequestDiffFold.test.ts | 80 ++++----- .../client-runtime/src/pullRequestDiffFold.ts | 38 ----- 4 files changed, 140 insertions(+), 261 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 866f397829c49..c6f2a4ee47ef3 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -17,15 +17,15 @@ import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () => { const { AsyncResult, Atom } = await import("effect/reactivity"); - const filePatch = (path: string, changed = false) => + const filePatch = (path: string) => [ `diff --git a/${path} b/${path}`, - `index 1111111..${changed ? "3333333" : "2222222"} 100644`, + "index 1111111..2222222 100644", `--- a/${path}`, `+++ b/${path}`, "@@ -1,6 +1,6 @@", "-before()", - changed ? "+updated()" : "+after()", + "+after()", " one()", " two()", " three()", @@ -62,8 +62,8 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () testFileDiffAtom: Atom.make(() => AsyncResult.success({ patch: - filePatch(mocks.renameSourceOnRefresh ? "early-0-renamed.ts" : "early-0.ts") + - filePatch("early-1.test.ts", mocks.changeTestOnRefresh) + + filePatch("early-0.ts") + + filePatch("early-1.test.ts") + filePatch("early-2.generated.ts"), truncated: false, nextCursor: null, @@ -77,8 +77,6 @@ const mocks = vi.hoisted(() => ({ paged: false, shortPages: false, withTestFile: false, - renameSourceOnRefresh: false, - changeTestOnRefresh: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -105,7 +103,7 @@ vi.mock(import("./usePullRequestFilesViewed"), async () => { return { enabled: viewedPaths !== null, isViewed: (path: string) => viewedPaths?.has(path) === true, - isStale: (path: string) => mocks.changeTestOnRefresh && path === "early-1.test.ts", + isStale: () => false, setViewed: (path: string, viewed: boolean) => { const next = new Set(mocks.viewedPaths); if (viewed) next.add(path); @@ -195,8 +193,6 @@ function setup({ paged }: { paged: boolean }) { mocks.paged = paged; mocks.shortPages = false; mocks.withTestFile = false; - mocks.renameSourceOnRefresh = false; - mocks.changeTestOnRefresh = false; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -422,107 +418,85 @@ it("keeps a hidden test file open when all shown files collapse", async () => { .toHaveAttribute("aria-expanded", "true"); }); -it("keeps a hidden test file folded when a refresh renames another file after expand all", async () => { - setup({ paged: false }); - mocks.withTestFile = true; - using _hidden = { - [Symbol.dispose]() { - window.localStorage.removeItem("t3code.diffHideTestFiles"); - }, - }; +// Two short pages of a source and a test file each; the next page loads only through the file tree. +async function renderShortPages(stack: AsyncDisposableStack, diffFilesCollapsed = true) { + setup({ paged: true }); + mocks.shortPages = true; + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed }); + stack.defer(() => { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + window.localStorage.removeItem("t3code.pullRequestFileTreeOpen"); + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }); + stack.use( + stubGlobal( + "IntersectionObserver", + class extends IntersectionObserver { + constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { + super(options?.rootMargin === "240px" ? () => {} : callback, options); + } + }, + ), + ); const container = document.createElement("div"); container.className = "flex h-[1000px] w-[900px]"; - await using screen = await render(tab(0), { container }); + const screen = stack.use(await render(tab(0), { container })); + const loadNextPage = async () => { + await screen.getByRole("button", { name: "Show file tree", exact: true }).click(); + const loadMore = screen.getByRole("button", { name: "Load more files", exact: true }); + await loadMore.click(); + await expect.element(loadMore).not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Hide file tree", exact: true }).click(); + }; + // The later page sits at the bottom of the list, which grows as expanded files render. + const diffToggle = async (path: string) => { + const scroller = container.querySelector(".diff-render-surface")!; + const header = await vi.waitFor(() => { + scroller.scrollTop = scroller.scrollHeight; + return screen.getByText(path, { exact: true }).element(); + }); + const { host } = header.getRootNode() as ShadowRoot; + return page.elementLocator(host).getByRole("button", { name: /^(Expand|Collapse) diff$/ }); + }; const filter = screen.getByRole("button", { name: "Hide test files" }); + return { screen, loadNextPage, diffToggle, filter }; +} + +it("expands later source files while keeping a later hidden test file folded", async () => { + await using stack = new AsyncDisposableStack(); + const { screen, loadNextPage, diffToggle, filter } = await renderShortPages(stack); await filter.click(); + await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible(); await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - mocks.renameSourceOnRefresh = true; - await screen.rerender(tab(1)); - await expect.element(screen.getByText("early-0-renamed.ts", { exact: true })).toBeVisible(); + await loadNextPage(); + await expect.element(screen.getByText("2 test files hidden", { exact: true })).toBeVisible(); await filter.click(); - await expect.element(screen.getByText("early-1.test.ts", { exact: true })).toBeVisible(); - const toggles = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }); - await expect.element(toggles.nth(0)).toHaveAttribute("aria-expanded", "true"); - await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "false"); + await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); + await expect.element(await diffToggle("late.ts")).toHaveAttribute("aria-expanded", "true"); + await expect.element(await diffToggle("late.test.ts")).toHaveAttribute("aria-expanded", "false"); }); -it("opens a hidden test file when a refresh changes its patch and makes its Viewed mark stale", async () => { - setup({ paged: false }); - mocks.withTestFile = true; - mocks.viewedPaths = new Set(["early-1.test.ts"]); - __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); - using _preferences = { - [Symbol.dispose]() { - window.localStorage.removeItem("t3code.diffHideTestFiles"); - __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); - }, - }; - const container = document.createElement("div"); - container.className = "flex h-[1000px] w-[900px]"; - await using screen = await render(tab(0), { container }); - const toggles = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }); - await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "false"); - const filter = screen.getByRole("button", { name: "Hide test files" }); +it("keeps a later test file folded by hand through a refresh and bulk toggles while hidden", async () => { + await using stack = new AsyncDisposableStack(); + const { screen, loadNextPage, diffToggle, filter } = await renderShortPages(stack, false); + await loadNextPage(); + const lateTest = await diffToggle("late.test.ts"); + await lateTest.click(); + await expect.element(lateTest).toHaveAttribute("aria-expanded", "false"); await filter.click(); - await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); - await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - mocks.changeTestOnRefresh = true; + // A refresh drops the loaded later page, so the bulk toggles below run without it. await screen.rerender(tab(1)); - await filter.click(); - - await expect.element(toggles.nth(1)).toHaveAttribute("aria-expanded", "true"); - await expect.element(screen.getByText("updated()", { exact: true })).toBeVisible(); -}); - -it("expands later source files while keeping a later hidden test file folded", async () => { - setup({ paged: true }); - mocks.shortPages = true; - using _hidden = { - [Symbol.dispose]() { - window.localStorage.removeItem("t3code.diffHideTestFiles"); - window.localStorage.removeItem("t3code.pullRequestFileTreeOpen"); - }, - }; - // Use the file tree's load button to control when the short first page gives way to the next. - using _observer = stubGlobal( - "IntersectionObserver", - class extends IntersectionObserver { - constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { - super(options?.rootMargin === "240px" ? () => {} : callback, options); - } - }, - ); - const container = document.createElement("div"); - container.className = "flex h-[1000px] w-[900px]"; - await using screen = await render(tab(0), { container }); - const filter = screen.getByRole("button", { name: "Hide test files" }); - await filter.click(); await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible(); + await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - - await screen.getByRole("button", { name: "Show file tree", exact: true }).click(); - await screen.getByRole("button", { name: "Load more files", exact: true }).click(); - await expect.element(screen.getByText("2 test files hidden", { exact: true })).toBeVisible(); - await screen.getByRole("button", { name: "Hide file tree", exact: true }).click(); + await loadNextPage(); await filter.click(); await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); - const diffToggle = (path: string) => { - const header = screen.getByText(path, { exact: true }).element(); - const { host } = header.getRootNode() as ShadowRoot; - return page.elementLocator(host).getByRole("button", { name: /^(Expand|Collapse) diff$/ }); - }; - await vi.waitFor(() => - expect(diffToggle("late.ts").element()).toHaveAttribute("aria-expanded", "true"), - ); - const scroller = container.querySelector(".diff-render-surface")!; - scroller.scrollTop = scroller.scrollHeight; - await vi.waitFor(() => - expect(diffToggle("late.test.ts").element()).toHaveAttribute("aria-expanded", "false"), - ); + await expect.element(await diffToggle("late.test.ts")).toHaveAttribute("aria-expanded", "false"); }); it("never requests the diff of a selected commit the pull request no longer has", async () => { diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 21562ac319302..f29d002c2bf81 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,8 +1,7 @@ import { - applyPullRequestDiffFold, - createPullRequestDiffFoldState, isFileDiffCollapsed, withFileDiffFold, + type DiffFoldOverride, type FileDiffFoldChoices, } from "@t3tools/client-runtime/pull-request-diff-fold"; import { @@ -83,8 +82,6 @@ import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import { orderDiffFiles } from "./pullRequestFileOrder.logic"; import { - buildFileDiffContentVersion, - buildFileDiffIdentityKey, buildFileDiffRenderKey, fnv1a32, getDiffLineStat, @@ -241,18 +238,6 @@ type DiffModel = { const diffModels = new WeakMap, Map>(); const patchHashes = new WeakMap(); -const foldKeys = new WeakMap(); - -// A fold choice survives edits elsewhere on the page, but expires when its own patch changes. -function fileDiffFoldKey(file: FileDiffMetadata): string { - let key = foldKeys.get(file); - if (key === undefined) { - key = `${buildFileDiffIdentityKey(file)}\u0000${buildFileDiffContentVersion(file)}`; - foldKeys.set(file, key); - } - return key; -} - // Hashing, ordering and counting every file of a huge pull request costs a second, and the tab // renders far more often than its slices change, so the model is kept per slice list. function diffModel( @@ -466,19 +451,11 @@ function PullRequestCodeTab({ diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, })); - const [foldState, setFoldState] = useState(createPullRequestDiffFoldState); - const defaultFoldOverride = settings.diffFilesCollapsed ? "folded" : null; - const foldOverrideForPath = (path: string) => - (isTestChangedFile(path) ? foldState.testOverride : foldState.sourceOverride) ?? - defaultFoldOverride; - const setFoldChoices = (update: (choices: FileDiffFoldChoices) => FileDiffFoldChoices) => { - setFoldState((current) => { - const choices = update(current.choices); - return choices === current.choices ? current : { ...current, choices }; - }); - }; + 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; @@ -519,7 +496,8 @@ function PullRequestCodeTab({ setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); - setFoldState(createPullRequestDiffFoldState()); + setFoldChoices(new Map()); + setFoldOverride(null); setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); @@ -629,8 +607,9 @@ function PullRequestCodeTab({ const [withheldLoads, setWithheldLoads] = useState<{ readonly scope: string; readonly paths: ReadonlyArray; - readonly shownPaths: ReadonlySet; - }>({ scope: "", paths: NO_PATHS, shownPaths: new Set() }); + /** The render key each loaded file was last shown under; a changed patch gets a new one. */ + readonly shownKeys: ReadonlyMap; + }>({ scope: "", paths: NO_PATHS, shownKeys: new Map() }); const withheldPaths = withheldLoads.scope === scopeKey ? withheldLoads.paths : NO_PATHS; const withheldInput = { ...reference, ...(commit === null ? {} : { commit }) }; const atomRegistry = useContext(RegistryContext); @@ -728,18 +707,23 @@ function PullRequestCodeTab({ if (hasCutLines(data.patch)) cutFiles.add(file); } else withheldStatuses.set(path, "empty"); }); - // Open a withheld patch on first load, then let the saved choice follow that patch. - const newlyShown = [...withheldFiles].filter(([path]) => !withheldLoads.shownPaths.has(path)); - if (newlyShown.length > 0) { + // Fold choices follow render keys, so a loaded or refetched patch would otherwise fold again + // when marked Viewed: it opens on first load and keeps its earlier key's choice after. + const rekeyed = [...withheldFiles].flatMap(([path, file]) => { + const key = buildFileDiffRenderKey(file); + return withheldLoads.shownKeys.get(path) === key ? [] : [[path, key] as const]; + }); + if (withheldLoads.scope === scopeKey && rekeyed.length > 0) { setWithheldLoads({ ...withheldLoads, - shownPaths: new Set([...withheldLoads.shownPaths, ...newlyShown.map(([path]) => path)]), + shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]), }); setFoldChoices((current) => - newlyShown.reduce( - (next, [, file]) => withFileDiffFold(next, fileDiffFoldKey(file), false), - current, - ), + rekeyed.reduce((next, [path, key]) => { + const shown = withheldLoads.shownKeys.get(path); + const collapsed = shown === undefined ? false : current.get(shown); + return collapsed === undefined ? next : withFileDiffFold(next, key, collapsed); + }, current), ); } const loadedFiles = @@ -756,7 +740,7 @@ function PullRequestCodeTab({ setWithheldLoads({ scope: scopeKey, paths: [...withheldPaths, path], - shownPaths: withheldLoads.scope === scopeKey ? withheldLoads.shownPaths : new Set(), + shownKeys: withheldLoads.scope === scopeKey ? withheldLoads.shownKeys : new Map(), }); }; const linkAnchor = parsePullRequestAnchor(revealUrl); @@ -965,9 +949,9 @@ function PullRequestCodeTab({ const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { const collapsed = isFileDiffCollapsed( - fileDiffFoldKey(fileDiff), - foldOverrideForPath(path), - foldState.choices, + fileKey, + effectiveFoldOverride, + foldChoices, foldsAsViewed(path), ); const viewedMark = filesViewedEnabled @@ -1011,13 +995,14 @@ function PullRequestCodeTab({ }; const toggleFile = (fileKey: string) => { - const file = annotatedFiles.find((file) => file.fileKey === fileKey); - if (file === undefined) return; - const foldKey = fileDiffFoldKey(file.fileDiff); - const viewed = foldsAsViewed(file.path); - const override = foldOverrideForPath(file.path); + const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path; + const viewed = path !== undefined && foldsAsViewed(path); setFoldChoices((current) => - withFileDiffFold(current, foldKey, !isFileDiffCollapsed(foldKey, override, current, viewed)), + withFileDiffFold( + current, + fileKey, + !isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed), + ), ); }; @@ -1035,11 +1020,7 @@ function PullRequestCodeTab({ setFoldChoices((current) => range.reduce( (next, file) => - withFileDiffFold( - next, - fileDiffFoldKey(file.fileDiff), - foldOverrideForPath(file.path) === null ? undefined : viewed, - ), + withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), current, ), ); @@ -1055,35 +1036,14 @@ function PullRequestCodeTab({ const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. - setFoldChoices((current) => withFileDiffFold(current, fileDiffFoldKey(item.fileDiff), false)); + setFoldChoices((current) => withFileDiffFold(current, item.id, false)); if (range) setSelectedLines({ id: item.id, range }); codeViewReveal.request(item.id, range); }; const toggleAllFiles = () => { - const shownFiles = new Set(files); - const filteredTests = hideTestFiles - ? loadedFiles.flatMap((file) => { - const path = resolveFileDiffPath(file); - return isTestChangedFile(path) - ? [ - { - key: fileDiffFoldKey(file), - viewed: foldsAsViewed(path), - hidden: !shownFiles.has(file), - }, - ] - : []; - }) - : null; - setFoldState((current) => - applyPullRequestDiffFold( - current, - allFilesCollapsed ? "expanded" : "folded", - defaultFoldOverride, - filteredTests, - ), - ); + setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); + setFoldChoices(new Map()); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. @@ -1243,11 +1203,10 @@ function PullRequestCodeTab({ onItemCollapsedChange: ( _item: CodeViewItem, nextItem: CodeViewItem, - ) => { - if (nextItem.type !== "diff") return; - const foldKey = fileDiffFoldKey(nextItem.fileDiff); - setFoldChoices((current) => withFileDiffFold(current, foldKey, nextItem.collapsed === true)); - }, + ) => + setFoldChoices((current) => + withFileDiffFold(current, nextItem.id, nextItem.collapsed === true), + ), }; const runThreadCommand = async ( diff --git a/packages/client-runtime/src/pullRequestDiffFold.test.ts b/packages/client-runtime/src/pullRequestDiffFold.test.ts index 6de975c4ae2d5..9e2e870d979d1 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.test.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.test.ts @@ -1,10 +1,12 @@ import { describe, expect, it } from "vite-plus/test"; import { - applyPullRequestDiffFold, - createPullRequestDiffFoldState, + EMPTY_PULL_REQUEST_DIFF_FOLDS, + foldAllPullRequestDiffs, isFileDiffCollapsed, withFileDiffFold, + withPullRequestDiffFold, + type DiffFoldGroup, } from "./pullRequestDiffFold.ts"; describe("isFileDiffCollapsed", () => { @@ -45,51 +47,33 @@ describe("withFileDiffFold", () => { }); }); -describe("applyPullRequestDiffFold", () => { +describe("foldAllPullRequestDiffs", () => { it.each([ - { before: null, after: "expanded", hiddenFold: true }, - { before: "folded", after: "expanded", hiddenFold: true }, - { before: "expanded", after: "folded", hiddenFold: false }, - ] as const)( - "keeps hidden folds when switching from $before to $after", - ({ before, after, hiddenFold }) => { - const initial = createPullRequestDiffFoldState(); - const previous = - before === null ? initial : applyPullRequestDiffFold(initial, before, null, null); - const next = applyPullRequestDiffFold( - { - ...previous, - choices: new Map([ - ["hidden-explicit", !hiddenFold], - ["shown-source", after === "expanded"], - ]), - }, - after, - null, - [ - { key: "hidden-viewed", viewed: true, hidden: true }, - { key: "hidden-explicit", viewed: true, hidden: true }, - { key: "shown-test", viewed: true, hidden: false }, - ], - ); - expect(isFileDiffCollapsed("hidden-viewed", next.testOverride, next.choices, false)).toBe( - hiddenFold, - ); - expect(isFileDiffCollapsed("hidden-explicit", next.testOverride, next.choices)).toBe( - !hiddenFold, - ); - expect(isFileDiffCollapsed("shown-test", next.testOverride, next.choices)).toBe( - after === "folded", - ); - expect(isFileDiffCollapsed("shown-source", next.sourceOverride, next.choices)).toBe( - after === "folded", - ); - expect(isFileDiffCollapsed("later-source", next.sourceOverride, next.choices)).toBe( - after === "folded", - ); - expect(isFileDiffCollapsed("later-test", next.testOverride, next.choices, true)).toBe( - hiddenFold, - ); - }, - ); + { override: "expanded", testsHidden: false }, + { override: "expanded", testsHidden: true }, + { override: "folded", testsHidden: false }, + { override: "folded", testsHidden: true }, + ] as const)("$override with tests hidden: $testsHidden", ({ override, testsHidden }) => { + const bulk = override === "folded"; + let folds = withPullRequestDiffFold(EMPTY_PULL_REQUEST_DIFF_FOLDS, false, (choices) => + withFileDiffFold(choices, "source", !bulk), + ); + folds = withPullRequestDiffFold(folds, true, (choices) => + withFileDiffFold(withFileDiffFold(choices, "hidden-test", !bulk), "revealed-test", !bulk), + ); + const next = foldAllPullRequestDiffs( + folds, + override, + testsHidden ? { shownKeys: ["revealed-test"] } : null, + ); + const collapsed = (group: DiffFoldGroup, key: string, viewed = false) => + isFileDiffCollapsed(key, group.override, group.choices, viewed); + + expect(collapsed(next.source, "source")).toBe(bulk); + expect(collapsed(next.source, "later-source", !bulk)).toBe(bulk); + expect(collapsed(next.test, "revealed-test")).toBe(bulk); + // A hidden test keeps its own choice, or its live Viewed mark when it has none. + expect(collapsed(next.test, "hidden-test")).toBe(testsHidden ? !bulk : bulk); + expect(collapsed(next.test, "later-test", !bulk)).toBe(testsHidden ? !bulk : bulk); + }); }); diff --git a/packages/client-runtime/src/pullRequestDiffFold.ts b/packages/client-runtime/src/pullRequestDiffFold.ts index 8a8581bf298f5..8083c93c25b09 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.ts @@ -23,41 +23,3 @@ export function withFileDiffFold( else next.set(fileKey, collapsed); return next; } - -export interface PullRequestDiffFoldState { - readonly sourceOverride: DiffFoldOverride; - readonly testOverride: DiffFoldOverride; - readonly choices: FileDiffFoldChoices; -} - -export function createPullRequestDiffFoldState(): PullRequestDiffFoldState { - return { sourceOverride: null, testOverride: null, choices: new Map() }; -} - -/** Scope the bulk override to the filter at click time, including for files that load later. */ -export function applyPullRequestDiffFold( - current: PullRequestDiffFoldState, - override: NonNullable, - defaultOverride: DiffFoldOverride, - filteredTests: ReadonlyArray<{ - readonly key: string; - readonly viewed: boolean; - readonly hidden: boolean; - }> | null, -): PullRequestDiffFoldState { - const choices = new Map(); - const previousTestOverride = current.testOverride ?? defaultOverride; - for (const { key, viewed, hidden } of filteredTests ?? []) { - choices.set( - key, - hidden - ? isFileDiffCollapsed(key, previousTestOverride, current.choices, viewed) - : override === "folded", - ); - } - return { - sourceOverride: override, - testOverride: filteredTests === null ? override : current.testOverride, - choices, - }; -} From 79ec1f6c0b2a0903499b3da00936bbafcee1cb87 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:08:34 +0100 Subject: [PATCH 10/13] fix(web): keep test files in their own fold group in the pull request Code tab Expand or collapse all while tests are hidden now resets only the source files' override and choices and leaves the test group as it was, so a hidden test keeps its own fold, or its Viewed mark, even on a page not loaded at the click. Fold choices go back to the render keys the tab already used. Co-authored-by: Claude Opus 5.5 --- .../pullRequest/PullRequestCodeTab.tsx | 83 +++++++++++-------- .../client-runtime/src/pullRequestDiffFold.ts | 52 ++++++++++++ 2 files changed, 101 insertions(+), 34 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f29d002c2bf81..092abcf9a50b0 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,7 +1,9 @@ import { + EMPTY_PULL_REQUEST_DIFF_FOLDS, + foldAllPullRequestDiffs, isFileDiffCollapsed, withFileDiffFold, - type DiffFoldOverride, + withPullRequestDiffFold, type FileDiffFoldChoices, } from "@t3tools/client-runtime/pull-request-diff-fold"; import { @@ -451,11 +453,19 @@ function PullRequestCodeTab({ diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, })); - const [foldChoices, setFoldChoices] = useState(() => new Map()); + const [folds, setFolds] = useState(EMPTY_PULL_REQUEST_DIFF_FOLDS); + const foldGroup = (path: string) => { + const group = isTestChangedFile(path) ? folds.test : folds.source; + return group.override === null && settings.diffFilesCollapsed + ? { ...group, override: "folded" as const } + : group; + }; + const setFoldChoices = ( + path: string, + update: (choices: FileDiffFoldChoices) => FileDiffFoldChoices, + ) => setFolds((current) => withPullRequestDiffFold(current, isTestChangedFile(path), update)); 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; @@ -496,8 +506,7 @@ function PullRequestCodeTab({ setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); - setFoldChoices(new Map()); - setFoldOverride(null); + setFolds(EMPTY_PULL_REQUEST_DIFF_FOLDS); setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); @@ -718,13 +727,13 @@ function PullRequestCodeTab({ ...withheldLoads, shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]), }); - setFoldChoices((current) => - rekeyed.reduce((next, [path, key]) => { - const shown = withheldLoads.shownKeys.get(path); + for (const [path, key] of rekeyed) { + const shown = withheldLoads.shownKeys.get(path); + setFoldChoices(path, (current) => { const collapsed = shown === undefined ? false : current.get(shown); - return collapsed === undefined ? next : withFileDiffFold(next, key, collapsed); - }, current), - ); + return collapsed === undefined ? current : withFileDiffFold(current, key, collapsed); + }); + } } const loadedFiles = withheldFiles.size === 0 @@ -948,10 +957,11 @@ function PullRequestCodeTab({ filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { + const group = foldGroup(path); const collapsed = isFileDiffCollapsed( fileKey, - effectiveFoldOverride, - foldChoices, + group.override, + group.choices, foldsAsViewed(path), ); const viewedMark = filesViewedEnabled @@ -996,13 +1006,11 @@ function PullRequestCodeTab({ const toggleFile = (fileKey: string) => { const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path; - const viewed = path !== undefined && foldsAsViewed(path); - setFoldChoices((current) => - withFileDiffFold( - current, - fileKey, - !isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed), - ), + if (path === undefined) return; + const { override } = foldGroup(path); + const viewed = foldsAsViewed(path); + setFoldChoices(path, (current) => + withFileDiffFold(current, fileKey, !isFileDiffCollapsed(fileKey, override, current, viewed)), ); }; @@ -1017,13 +1025,10 @@ function PullRequestCodeTab({ // A commit's diff names that commit's version of the file, not the head's. setViewed(file.path, viewed, commit === null ? file.fileDiff.newObjectId : undefined); } - setFoldChoices((current) => - range.reduce( - (next, file) => - withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), - current, - ), - ); + for (const file of range) { + const collapsed = foldGroup(file.path).override === null ? undefined : viewed; + setFoldChoices(file.path, (current) => withFileDiffFold(current, file.fileKey, collapsed)); + } }; const fileViewedToggle = { enabled: filesViewedEnabled, @@ -1036,14 +1041,22 @@ function PullRequestCodeTab({ const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. - setFoldChoices((current) => withFileDiffFold(current, item.id, false)); + setFoldChoices(path, (current) => withFileDiffFold(current, item.id, false)); if (range) setSelectedLines({ id: item.id, range }); codeViewReveal.request(item.id, range); }; const toggleAllFiles = () => { - setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); - setFoldChoices(new Map()); + const shownTestKeys = annotatedFiles.flatMap((file) => + isTestChangedFile(file.path) ? [file.fileKey] : [], + ); + setFolds((current) => + foldAllPullRequestDiffs( + current, + allFilesCollapsed ? "expanded" : "folded", + hideTestFiles ? { shownKeys: shownTestKeys } : null, + ), + ); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. @@ -1203,10 +1216,12 @@ function PullRequestCodeTab({ onItemCollapsedChange: ( _item: CodeViewItem, nextItem: CodeViewItem, - ) => - setFoldChoices((current) => + ) => { + if (nextItem.type !== "diff") return; + setFoldChoices(resolveFileDiffPath(nextItem.fileDiff), (current) => withFileDiffFold(current, nextItem.id, nextItem.collapsed === true), - ), + ); + }, }; const runThreadCommand = async ( diff --git a/packages/client-runtime/src/pullRequestDiffFold.ts b/packages/client-runtime/src/pullRequestDiffFold.ts index 8083c93c25b09..3307afb7cb540 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.ts @@ -23,3 +23,55 @@ export function withFileDiffFold( else next.set(fileKey, collapsed); return next; } + +export interface DiffFoldGroup { + readonly override: DiffFoldOverride; + readonly choices: FileDiffFoldChoices; +} + +/** Test files keep their own group, so a bulk fold while they are hidden leaves them as they were. */ +export interface PullRequestDiffFolds { + readonly source: DiffFoldGroup; + readonly test: DiffFoldGroup; +} + +const EMPTY_GROUP: DiffFoldGroup = { override: null, choices: new Map() }; + +export const EMPTY_PULL_REQUEST_DIFF_FOLDS: PullRequestDiffFolds = { + source: EMPTY_GROUP, + test: EMPTY_GROUP, +}; + +export function withPullRequestDiffFold( + folds: PullRequestDiffFolds, + test: boolean, + update: (choices: FileDiffFoldChoices) => FileDiffFoldChoices, +): PullRequestDiffFolds { + const group = test ? folds.test : folds.source; + const choices = update(group.choices); + if (choices === group.choices) return folds; + return { ...folds, [test ? "test" : "source"]: { ...group, choices } }; +} + +/** + * Expand or fold every file, on later pages too. While test files are hidden, only the tests + * still shown (a revealed one) follow; the rest keep their choices and fallback. + */ +export function foldAllPullRequestDiffs( + folds: PullRequestDiffFolds, + override: NonNullable, + hiddenTests: { readonly shownKeys: ReadonlyArray } | null, +): PullRequestDiffFolds { + const all: DiffFoldGroup = { override, choices: new Map() }; + if (hiddenTests === null) return { source: all, test: all }; + return { + source: all, + test: { + ...folds.test, + choices: hiddenTests.shownKeys.reduce( + (choices, key) => withFileDiffFold(choices, key, override === "folded"), + folds.test.choices, + ), + }, + }; +} From f853607972904c29a79e9a1eae9f73dfa2a08029 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:37:02 +0100 Subject: [PATCH 11/13] fix(web): keep test file folds across pull request diff refreshes Co-authored-by: GPT 6.2 Sol --- .../PullRequestCodeTab.browser.test.tsx | 44 +++++++++++++++++-- .../pullRequest/PullRequestCodeTab.tsx | 41 +++++++++++------ 2 files changed, 68 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index c6f2a4ee47ef3..50d70f320bc87 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -17,7 +17,7 @@ import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () => { const { AsyncResult, Atom } = await import("effect/reactivity"); - const filePatch = (path: string) => + const filePatch = (path: string, addition = "after()") => [ `diff --git a/${path} b/${path}`, "index 1111111..2222222 100644", @@ -25,7 +25,7 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () `+++ b/${path}`, "@@ -1,6 +1,6 @@", "-before()", - "+after()", + `+${addition}`, " one()", " two()", " three()", @@ -62,8 +62,8 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () testFileDiffAtom: Atom.make(() => AsyncResult.success({ patch: - filePatch("early-0.ts") + - filePatch("early-1.test.ts") + + filePatch("early-0.ts", mocks.sourceAddition) + + filePatch("early-1.test.ts", "testOnly()") + filePatch("early-2.generated.ts"), truncated: false, nextCursor: null, @@ -77,6 +77,7 @@ const mocks = vi.hoisted(() => ({ paged: false, shortPages: false, withTestFile: false, + sourceAddition: "after()", diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -193,6 +194,7 @@ function setup({ paged }: { paged: boolean }) { mocks.paged = paged; mocks.shortPages = false; mocks.withTestFile = false; + mocks.sourceAddition = "after()"; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -361,6 +363,40 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it await expectFileHeaderShown(screen, container, "late.test.ts"); }); +it("keeps a linked test file expanded when a refresh changes only the source patch", async () => { + setup({ paged: false }); + mocks.withTestFile = true; + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: true }); + using _preferences = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }, + }; + 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: "Hide test files" }).click(); + + const path = "early-1.test.ts"; + const url = `${detail.url}/files#diff-${bytesToHex(sha256(new TextEncoder().encode(path)))}`; + const settled = vi.fn(); + await screen.rerender(tab(0, null, url, settled)); + await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url)); + await screen.rerender(tab(0)); + const testLine = screen.getByText("testOnly()", { exact: true }); + await expect.element(testLine).toBeVisible(); + await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); + await expect.element(testLine).not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + await expect.element(testLine).toBeVisible(); + + mocks.sourceAddition = "refreshed()"; + await screen.rerender(tab(1)); + await expect.element(screen.getByText("refreshed()", { exact: true })).toBeVisible(); + await expect.element(testLine).toBeVisible(); +}); + it("keeps a hidden test file folded when all shown files expand", async () => { setup({ paged: true }); // Test files sort after source files, so this diff puts its only test file second. diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 092abcf9a50b0..a1c3404f25085 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -84,6 +84,7 @@ import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import { orderDiffFiles } from "./pullRequestFileOrder.logic"; import { + buildFileDiffIdentityKey, buildFileDiffRenderKey, fnv1a32, getDiffLineStat, @@ -390,6 +391,13 @@ export interface PullRequestAgentSelectionInput { readonly request: string; } +// A test's fold belongs to the file even when filtering or a refresh replaces its viewer item. +function buildFileDiffFoldKey(fileDiff: FileDiffMetadata): string { + return isTestChangedFile(resolveFileDiffPath(fileDiff)) + ? buildFileDiffIdentityKey(fileDiff) + : buildFileDiffRenderKey(fileDiff); +} + function isRemovedLine(fileDiff: FileDiffMetadata, oldLine: number): boolean { return fileDiff.hunks.some((hunk) => { let next = hunk.deletionStart; @@ -716,10 +724,9 @@ function PullRequestCodeTab({ if (hasCutLines(data.patch)) cutFiles.add(file); } else withheldStatuses.set(path, "empty"); }); - // Fold choices follow render keys, so a loaded or refetched patch would otherwise fold again - // when marked Viewed: it opens on first load and keeps its earlier key's choice after. + // A withheld patch opens on first load and keeps its choice when its fold key changes. const rekeyed = [...withheldFiles].flatMap(([path, file]) => { - const key = buildFileDiffRenderKey(file); + const key = buildFileDiffFoldKey(file); return withheldLoads.shownKeys.get(path) === key ? [] : [[path, key] as const]; }); if (withheldLoads.scope === scopeKey && rekeyed.length > 0) { @@ -730,7 +737,7 @@ function PullRequestCodeTab({ for (const [path, key] of rekeyed) { const shown = withheldLoads.shownKeys.get(path); setFoldChoices(path, (current) => { - const collapsed = shown === undefined ? false : current.get(shown); + const collapsed = shown === undefined ? (current.get(key) ?? false) : current.get(shown); return collapsed === undefined ? current : withFileDiffFold(current, key, collapsed); }); } @@ -887,6 +894,7 @@ function PullRequestCodeTab({ } return { fileKey, + foldKey: buildFileDiffFoldKey(fileDiff), path, fileDiff, annotations, @@ -956,10 +964,10 @@ function PullRequestCodeTab({ const foldsAsViewed = (path: string) => filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); const items: CodeViewDiffItem[] = annotatedFiles.map( - ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { + ({ fileKey, foldKey, path, fileDiff, annotations, annotationsVersion }) => { const group = foldGroup(path); const collapsed = isFileDiffCollapsed( - fileKey, + foldKey, group.override, group.choices, foldsAsViewed(path), @@ -1005,12 +1013,13 @@ function PullRequestCodeTab({ }; const toggleFile = (fileKey: string) => { - const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path; - if (path === undefined) return; + const file = annotatedFiles.find((file) => file.fileKey === fileKey); + if (file === undefined) return; + const { path, foldKey } = file; const { override } = foldGroup(path); const viewed = foldsAsViewed(path); setFoldChoices(path, (current) => - withFileDiffFold(current, fileKey, !isFileDiffCollapsed(fileKey, override, current, viewed)), + withFileDiffFold(current, foldKey, !isFileDiffCollapsed(foldKey, override, current, viewed)), ); }; @@ -1027,7 +1036,7 @@ function PullRequestCodeTab({ } for (const file of range) { const collapsed = foldGroup(file.path).override === null ? undefined : viewed; - setFoldChoices(file.path, (current) => withFileDiffFold(current, file.fileKey, collapsed)); + setFoldChoices(file.path, (current) => withFileDiffFold(current, file.foldKey, collapsed)); } }; const fileViewedToggle = { @@ -1041,14 +1050,16 @@ function PullRequestCodeTab({ const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. - setFoldChoices(path, (current) => withFileDiffFold(current, item.id, false)); + setFoldChoices(path, (current) => + withFileDiffFold(current, buildFileDiffFoldKey(item.fileDiff), false), + ); if (range) setSelectedLines({ id: item.id, range }); codeViewReveal.request(item.id, range); }; const toggleAllFiles = () => { const shownTestKeys = annotatedFiles.flatMap((file) => - isTestChangedFile(file.path) ? [file.fileKey] : [], + isTestChangedFile(file.path) ? [file.foldKey] : [], ); setFolds((current) => foldAllPullRequestDiffs( @@ -1219,7 +1230,11 @@ function PullRequestCodeTab({ ) => { if (nextItem.type !== "diff") return; setFoldChoices(resolveFileDiffPath(nextItem.fileDiff), (current) => - withFileDiffFold(current, nextItem.id, nextItem.collapsed === true), + withFileDiffFold( + current, + buildFileDiffFoldKey(nextItem.fileDiff), + nextItem.collapsed === true, + ), ); }, }; From 89070ae9c0a247b5be564dc95f1d0152d903df6a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 17:00:03 +0000 Subject: [PATCH 12/13] test(web): keep only the Code tab fold cases the unit tests cannot reach The bulk-fold rules are covered in pullRequestDiffFold.test.ts; the browser file keeps the two refresh cases that exercise the component's fold keys. Co-Authored-By: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 79 +------------------ 1 file changed, 3 insertions(+), 76 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 50d70f320bc87..4486d06cec1ea 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -397,68 +397,11 @@ it("keeps a linked test file expanded when a refresh changes only the source pat await expect.element(testLine).toBeVisible(); }); -it("keeps a hidden test file folded when all shown files expand", async () => { - setup({ paged: true }); - // Test files sort after source files, so this diff puts its only test file second. - mocks.paged = false; - mocks.withTestFile = true; - using _hidden = { - [Symbol.dispose]() { - window.localStorage.removeItem("t3code.diffHideTestFiles"); - }, - }; - await using screen = await render(tab(0), { container: pagedContainer() }); - // Every expanded file stays rendered, so the toggles below keep their positions. - screen.container.className = "flex h-[1000px] w-[900px]"; - // Files keep their order, so the second header is early-1.test.ts while tests are shown. - const testFileToggle = screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1); - await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); - const filter = screen.getByRole("button", { name: "Hide test files" }); - await filter.click(); - await expect.element(filter).toHaveAttribute("aria-pressed", "true"); - - await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "true"); - await filter.click(); - - await expect.element(filter).toHaveAttribute("aria-pressed", "false"); - await expect.element(testFileToggle).toHaveAttribute("aria-expanded", "false"); -}); - -it("keeps a hidden test file open when all shown files collapse", async () => { - setup({ paged: false }); - mocks.withTestFile = true; - __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); - using _preferences = { - [Symbol.dispose]() { - window.localStorage.removeItem("t3code.diffHideTestFiles"); - __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); - }, - }; - const container = document.createElement("div"); - container.className = "flex h-[700px] w-[900px]"; - await using screen = await render(tab(0), { container }); - const filter = screen.getByRole("button", { name: "Hide test files" }); - await filter.click(); - await expect.element(filter).toHaveAttribute("aria-pressed", "true"); - - await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); - await expect - .element(screen.getByRole("button", { name: "Expand all files", exact: true })) - .toBeVisible(); - await filter.click(); - - await expect.element(screen.getByText("early-1.test.ts", { exact: true }).first()).toBeVisible(); - await expect - .element(screen.getByRole("button", { name: /^(Expand|Collapse) diff$/ }).nth(1)) - .toHaveAttribute("aria-expanded", "true"); -}); - // Two short pages of a source and a test file each; the next page loads only through the file tree. -async function renderShortPages(stack: AsyncDisposableStack, diffFilesCollapsed = true) { +async function renderShortPages(stack: AsyncDisposableStack) { setup({ paged: true }); mocks.shortPages = true; - __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed }); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); stack.defer(() => { window.localStorage.removeItem("t3code.diffHideTestFiles"); window.localStorage.removeItem("t3code.pullRequestFileTreeOpen"); @@ -498,25 +441,9 @@ async function renderShortPages(stack: AsyncDisposableStack, diffFilesCollapsed return { screen, loadNextPage, diffToggle, filter }; } -it("expands later source files while keeping a later hidden test file folded", async () => { - await using stack = new AsyncDisposableStack(); - const { screen, loadNextPage, diffToggle, filter } = await renderShortPages(stack); - await filter.click(); - await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible(); - await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - - await loadNextPage(); - await expect.element(screen.getByText("2 test files hidden", { exact: true })).toBeVisible(); - await filter.click(); - - await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); - await expect.element(await diffToggle("late.ts")).toHaveAttribute("aria-expanded", "true"); - await expect.element(await diffToggle("late.test.ts")).toHaveAttribute("aria-expanded", "false"); -}); - it("keeps a later test file folded by hand through a refresh and bulk toggles while hidden", async () => { await using stack = new AsyncDisposableStack(); - const { screen, loadNextPage, diffToggle, filter } = await renderShortPages(stack, false); + const { screen, loadNextPage, diffToggle, filter } = await renderShortPages(stack); await loadNextPage(); const lateTest = await diffToggle("late.test.ts"); await lateTest.click(); From a808ca0ae2b36413cccc12f26007aa35ee65f8e6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 17:25:28 +0000 Subject: [PATCH 13/13] test(web): make the linked test file refresh case deterministic Expand all only re-rendered the source file when the list happened to sit at the top, and on main it opened every file anyway, so the case neither held steady nor caught the bug. The refresh now adds a file and waits for the header count, so the revealed test file's own fold choice is what is checked. Co-Authored-By: Claude Opus 5.5 --- .../PullRequestCodeTab.browser.test.tsx | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 4486d06cec1ea..d18a551b892ad 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -62,9 +62,10 @@ const { diffAtom, testFileDiffAtom, pagedDiffAtom } = await vi.hoisted(async () testFileDiffAtom: Atom.make(() => AsyncResult.success({ patch: - filePatch("early-0.ts", mocks.sourceAddition) + + filePatch("early-0.ts") + filePatch("early-1.test.ts", "testOnly()") + - filePatch("early-2.generated.ts"), + filePatch("early-2.generated.ts") + + (mocks.refreshed ? filePatch("early-3.ts") : ""), truncated: false, nextCursor: null, }), @@ -77,7 +78,7 @@ const mocks = vi.hoisted(() => ({ paged: false, shortPages: false, withTestFile: false, - sourceAddition: "after()", + refreshed: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -194,7 +195,7 @@ function setup({ paged }: { paged: boolean }) { mocks.paged = paged; mocks.shortPages = false; mocks.withTestFile = false; - mocks.sourceAddition = "after()"; + mocks.refreshed = false; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -363,7 +364,7 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it await expectFileHeaderShown(screen, container, "late.test.ts"); }); -it("keeps a linked test file expanded when a refresh changes only the source patch", async () => { +it("keeps a linked test file expanded when a refresh changes the rest of the diff", async () => { setup({ paged: false }); mocks.withTestFile = true; __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: true }); @@ -386,14 +387,10 @@ it("keeps a linked test file expanded when a refresh changes only the source pat await screen.rerender(tab(0)); const testLine = screen.getByText("testOnly()", { exact: true }); await expect.element(testLine).toBeVisible(); - await screen.getByRole("button", { name: "Collapse all files", exact: true }).click(); - await expect.element(testLine).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); - await expect.element(testLine).toBeVisible(); - mocks.sourceAddition = "refreshed()"; + mocks.refreshed = true; await screen.rerender(tab(1)); - await expect.element(screen.getByText("refreshed()", { exact: true })).toBeVisible(); + await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); await expect.element(testLine).toBeVisible(); });