diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 4d305c4da66ed..d18a551b892ad 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -8,16 +8,16 @@ 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"; 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) => + const filePatch = (path: string, addition = "after()") => [ `diff --git a/${path} b/${path}`, "index 1111111..2222222 100644", @@ -25,7 +25,7 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { `+++ b/${path}`, "@@ -1,6 +1,6 @@", "-before()", - "+after()", + `+${addition}`, " one()", " two()", " three()", @@ -38,28 +38,47 @@ const { diffAtom, 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", - }, - "page-2": { patch: filePatch("late.test.ts"), truncated: false, nextCursor: null }, - }; + 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. diffAtom: Atom.make(() => AsyncResult.success(firstPage)), - pagedDiffAtom: Atom.family((cursor: string) => - Atom.make(() => AsyncResult.success(pages[cursor]!)), + testFileDiffAtom: Atom.make(() => + AsyncResult.success({ + patch: + filePatch("early-0.ts") + + filePatch("early-1.test.ts", "testOnly()") + + filePatch("early-2.generated.ts") + + (mocks.refreshed ? filePatch("early-3.ts") : ""), + truncated: false, + nextCursor: null, + }), ), + pagedDiffAtom, }; }); const mocks = vi.hoisted(() => ({ paged: false, + shortPages: false, + withTestFile: false, + refreshed: false, diffCommits: [] as Array, viewedPaths: null as ReadonlySet | null, viewedListeners: new Set<() => void>(), @@ -108,13 +127,14 @@ 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(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 = { @@ -173,6 +193,9 @@ function setup({ paged }: { paged: boolean }) { window.localStorage.removeItem("t3code.diffHideTestFiles"); __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); mocks.paged = paged; + mocks.shortPages = false; + mocks.withTestFile = false; + mocks.refreshed = false; mocks.diffCommits = []; mocks.viewedPaths = null; mocks.viewedListeners.clear(); @@ -341,6 +364,101 @@ 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 the rest of the diff", 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(); + + mocks.refreshed = true; + await screen.rerender(tab(1)); + await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); + await expect.element(testLine).toBeVisible(); +}); + +// 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) { + setup({ paged: true }); + mocks.shortPages = true; + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + 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]"; + 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("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); + await loadNextPage(); + const lateTest = await diffToggle("late.test.ts"); + await lateTest.click(); + await expect.element(lateTest).toHaveAttribute("aria-expanded", "false"); + await filter.click(); + + // A refresh drops the loaded later page, so the bulk toggles below run without it. + await screen.rerender(tab(1)); + 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 loadNextPage(); + await filter.click(); + + await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); + 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 f29d002c2bf81..a1c3404f25085 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 { @@ -82,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, @@ -388,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; @@ -451,11 +461,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 +514,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 }); @@ -707,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) { @@ -718,13 +734,13 @@ function PullRequestCodeTab({ ...withheldLoads, shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]), }); - 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), - ); + for (const [path, key] of rekeyed) { + const shown = withheldLoads.shownKeys.get(path); + setFoldChoices(path, (current) => { + const collapsed = shown === undefined ? (current.get(key) ?? false) : current.get(shown); + return collapsed === undefined ? current : withFileDiffFold(current, key, collapsed); + }); + } } const loadedFiles = withheldFiles.size === 0 @@ -878,6 +894,7 @@ function PullRequestCodeTab({ } return { fileKey, + foldKey: buildFileDiffFoldKey(fileDiff), path, fileDiff, annotations, @@ -947,11 +964,12 @@ 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, - effectiveFoldOverride, - foldChoices, + foldKey, + group.override, + group.choices, foldsAsViewed(path), ); const viewedMark = filesViewedEnabled @@ -995,14 +1013,13 @@ 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), - ), + 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, foldKey, !isFileDiffCollapsed(foldKey, override, current, viewed)), ); }; @@ -1017,13 +1034,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.foldKey, collapsed)); + } }; const fileViewedToggle = { enabled: filesViewedEnabled, @@ -1036,14 +1050,24 @@ 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, buildFileDiffFoldKey(item.fileDiff), 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.foldKey] : [], + ); + setFolds((current) => + foldAllPullRequestDiffs( + current, + allFilesCollapsed ? "expanded" : "folded", + hideTestFiles ? { shownKeys: shownTestKeys } : null, + ), + ); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. @@ -1203,10 +1227,16 @@ function PullRequestCodeTab({ onItemCollapsedChange: ( _item: CodeViewItem, nextItem: CodeViewItem, - ) => - setFoldChoices((current) => - withFileDiffFold(current, nextItem.id, nextItem.collapsed === true), - ), + ) => { + if (nextItem.type !== "diff") return; + setFoldChoices(resolveFileDiffPath(nextItem.fileDiff), (current) => + withFileDiffFold( + current, + buildFileDiffFoldKey(nextItem.fileDiff), + nextItem.collapsed === true, + ), + ); + }, }; const runThreadCommand = async ( 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/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; } diff --git a/packages/client-runtime/src/pullRequestDiffFold.test.ts b/packages/client-runtime/src/pullRequestDiffFold.test.ts index 34269c2212a05..9e2e870d979d1 100644 --- a/packages/client-runtime/src/pullRequestDiffFold.test.ts +++ b/packages/client-runtime/src/pullRequestDiffFold.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from "vite-plus/test"; -import { isFileDiffCollapsed, withFileDiffFold } from "./pullRequestDiffFold.ts"; +import { + EMPTY_PULL_REQUEST_DIFF_FOLDS, + foldAllPullRequestDiffs, + isFileDiffCollapsed, + withFileDiffFold, + withPullRequestDiffFold, + type DiffFoldGroup, +} from "./pullRequestDiffFold.ts"; describe("isFileDiffCollapsed", () => { it("collapses saved viewed files on reopening and when a later read marks them viewed", () => { @@ -39,3 +46,34 @@ describe("withFileDiffFold", () => { expect(withFileDiffFold(folded, "a.ts", undefined).has("a.ts")).toBe(false); }); }); + +describe("foldAllPullRequestDiffs", () => { + it.each([ + { 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 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, + ), + }, + }; +} 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"); + }, +);