diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx index 2d29be6d8b5ec..8957f95c8a97e 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx @@ -219,6 +219,7 @@ function setup(integrated = false) { const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex: data.rows.length - 1, targetFileId, focusIndex: -1, isIos: true, diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index d72cbe743f23e..0ae3386b45b45 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -1,3 +1,8 @@ +import { + isFileDiffCollapsed, + withFileDiffFold, + type FileDiffFoldChoices, +} from "@t3tools/client-runtime/pull-request-diff-fold"; import { parsePullRequestAnchor, pullRequestAnchorMatchesUrl, @@ -130,8 +135,6 @@ import { sourceControlClients, } from "@t3tools/client-runtime/source-control-clients"; -const EMPTY_IDS: readonly string[] = []; - function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityFilter) { const navigation = useNavigation(); const result = useEnvironmentQuery(composerPullRequests.activity(requestTarget(params))); @@ -1088,7 +1091,26 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { const focusIndex = focusedRows.length ? data.rows.findIndex((row) => row.id === focusedRows[0]?.id) : -1; - const [collapsedIds, setCollapsedIds] = useState(EMPTY_IDS); + const [foldChoices, setFoldChoices] = useState(() => new Map()); + const [foldScope, setFoldScope] = useState(`${scopeKey}:${commit ?? "all"}`); + const [revealedFileId, setRevealedFileId] = useState(null); + if (foldScope !== `${scopeKey}:${commit ?? "all"}`) { + setFoldScope(`${scopeKey}:${commit ?? "all"}`); + setFoldChoices(new Map()); + setRevealedFileId(null); + } + const requestedFileId = + (jumpPath ? data.files.find((file) => file.path === jumpPath)?.id : null) ?? null; + // A linked file must stay open if its Viewed response arrives after the first native draw. + if (requestedFileId !== revealedFileId) { + setRevealedFileId(requestedFileId); + if (requestedFileId) + setFoldChoices((current) => withFileDiffFold(current, requestedFileId, false)); + } + const viewedIdSet = new Set(viewedIds); + const collapsedIds = data.files + .filter((file) => isFileDiffCollapsed(file.id, null, foldChoices, viewedIdSet.has(file.id))) + .map((file) => file.id); const [visibleFileId, setVisibleFileId] = useState(null); const nativeView = useRef(null); // The filter the current jump was made under. Hiding or showing test files replaces the rows, @@ -1114,7 +1136,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { jumpedUnder.current = null; const file = data.files.find((entry) => entry.path === path); if (!file) return; - setCollapsedIds((ids) => ids.filter((id) => id !== file.id)); + setFoldChoices((current) => withFileDiffFold(current, file.id, false)); scrollToFile(file.id); }); // Subscribed for the whole screen, so a pick made while the diff is still loading is kept for @@ -1138,9 +1160,14 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { useEffect(() => { if (!targetFile) loadMore(); }, [targetFile, loadMore]); + const lastFileRowIndex = data.rows.findLastIndex((row) => row.kind === "file"); + const lastFileId = data.rows[lastFileRowIndex]?.fileId; + const lastShownRowIndex = + lastFileId && collapsedIds.includes(lastFileId) ? lastFileRowIndex : data.rows.length - 1; const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex, targetFileId: targetFile?.id, focusIndex, isIos: Platform.OS === "ios", @@ -1155,8 +1182,8 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { const onToggleFile: NonNullable = (event) => { const id = event.nativeEvent.fileId; if (!id) return; - setCollapsedIds((ids) => - ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id], + setFoldChoices((current) => + withFileDiffFold(current, id, !isFileDiffCollapsed(id, null, current, viewedIdSet.has(id))), ); }; const visibleFile = data.files.find((file) => file.id === visibleFileId) ?? targetFile; @@ -1270,7 +1297,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null }); jumpedUnder.current = null; setSelectedRowId(null); - setCollapsedIds(EMPTY_IDS); + setFoldChoices(new Map()); }} /> @@ -1311,16 +1338,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { onToggleViewedFile={(event) => { const file = data.files.find((file) => file.id === event.nativeEvent.fileId); if (!file || (!commit && !viewed.canToggle)) return; - const wasViewed = commit - ? commitViewedPaths.has(file.path) - : viewed.isViewed(file.path); - setCollapsedIds((ids) => - wasViewed - ? ids.filter((id) => id !== file.id) - : ids.includes(file.id) - ? ids - : [...ids, file.id], - ); + setFoldChoices((current) => withFileDiffFold(current, file.id, undefined)); if (commit) setCommitViewedPaths((current) => { const next = new Set(current); diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts index 23f5ba4726d62..80ccb09e50da2 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts @@ -42,9 +42,11 @@ it.each([true, false])( lastRowIndex: nativeEvent.lastRowIndex as number, }); }; + let lastShownRowIndex = 999; const emit = (nativeEvent: Record) => handlePullRequestDiffDebugEvent({ nativeEvent } as Parameters[0], { rowCount: 1000, + lastShownRowIndex, targetFileId: "last-file", focusIndex: -1, isIos, @@ -74,6 +76,10 @@ it.each([true, false])( expect(loadMore).not.toHaveBeenCalled(); emit({ message: "visible-range", firstRowIndex: 950, lastRowIndex: 990, totalRows: 1000 }); expect(loadMore).toHaveBeenCalledOnce(); + // A folded final file ends at its header, short of the full payload's tail. + lastShownRowIndex = 920; + emit({ message: "visible-range", firstRowIndex: 880, lastRowIndex: 920, totalRows: 1000 }); + expect(loadMore).toHaveBeenCalledTimes(2); } finally { scheduler.cancel(); vi.useRealTimers(); diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts index b6db266c38aa5..52fe61a65a4cc 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts @@ -21,6 +21,8 @@ export function handlePullRequestDiffDebugEvent( event: Parameters>[0], input: { readonly rowCount: number; + /** The last row native can draw: a folded final file ends at its header. */ + readonly lastShownRowIndex: number; readonly targetFileId: string | undefined; readonly focusIndex: number; readonly isIos: boolean; @@ -60,5 +62,9 @@ export function handlePullRequestDiffDebugEvent( } if (!drawn) return; const lastRow = event.nativeEvent.lastRowIndex; - if (typeof lastRow === "number" && lastRow >= input.rowCount - 40) input.loadMore(); + if ( + typeof lastRow === "number" && + lastRow >= Math.min(input.rowCount - 40, input.lastShownRowIndex) + ) + input.loadMore(); } diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 5b9d0af32a129..21f5c099a54cb 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -8,6 +8,7 @@ import { type PullRequestDiffResult, } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { __setClientSettingsForTests } from "../../hooks/useSettings"; @@ -85,7 +86,12 @@ vi.mock(import("./usePullRequestFilesViewed"), async () => { enabled: viewedPaths !== null, isViewed: (path: string) => viewedPaths?.has(path) === true, isStale: () => false, - setViewed: () => {}, + setViewed: (path: string, viewed: boolean) => { + const next = new Set(mocks.viewedPaths); + if (viewed) next.add(path); + else next.delete(path); + deliverViewedPaths(next); + }, truncated: false, error: null, refresh: () => {}, @@ -207,6 +213,52 @@ it("keeps the diff after a refresh that brings back the same page", async () => await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible(); }); +it("restores saved Viewed folds, follows cleared marks, and allows explicit expansion", async () => { + setup({ paged: false }); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + using _preferences = { + [Symbol.dispose]() { + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }, + }; + mocks.viewedPaths = new Set(["a.ts"]); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render(tab(0), { container }); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked(); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); + + await screen.getByRole("button", { name: "Expand diff", exact: true }).click(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + screen.getByRole("checkbox", { name: "Viewed" }).element().focus(); + await userEvent.keyboard(" "); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + screen.getByRole("checkbox", { name: "Viewed" }).element().focus(); + await userEvent.keyboard(" "); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); + + deliverViewedPaths(new Set()); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + deliverViewedPaths(new Set(["a.ts"])); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + + await screen.rerender(
); + await screen.rerender(tab(1)); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); +}); + // regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it it("keeps a revealed file open when its Viewed mark loads afterwards", async () => { setup({ paged: false }); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f52f1a064277f..5acc37153d736 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,3 +1,9 @@ +import { + isFileDiffCollapsed, + withFileDiffFold, + type DiffFoldOverride, + type FileDiffFoldChoices, +} from "@t3tools/client-runtime/pull-request-diff-fold"; import { parsePullRequestAnchor, pullRequestDiffPathMatches, @@ -132,14 +138,7 @@ import { toViewerSide, } from "./PullRequestReviewAnnotation"; import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea"; -import { - getFileViewedRange, - isFileDiffCollapsed, - isLineInFileDiff, - withFileDiffFold, - type DiffFoldOverride, - type FileDiffFoldChoices, -} from "./pullRequestDiff.logic"; +import { getFileViewedRange, isLineInFileDiff } from "./pullRequestDiff.logic"; import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation"; import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState"; import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed"; @@ -439,8 +438,7 @@ function PullRequestCodeTab({ const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); const [foldOverride, setFoldOverride] = useState(null); - const effectiveFoldOverride = - foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded"); + const effectiveFoldOverride = foldOverride ?? (settings.diffFilesCollapsed ? "folded" : null); const diffLayout = settings.diffLayout; const [wordWrapOverride, setWordWrapOverride] = useState(null); const wordWrap = wordWrapOverride ?? settings.wordWrap; @@ -932,9 +930,8 @@ function PullRequestCodeTab({
); - // A stale mark means the file changed since it was viewed; Fold all and Expand all outrank marks. const foldsAsViewed = (path: string) => - foldOverride === null && filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); + filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { const collapsed = isFileDiffCollapsed( @@ -1007,7 +1004,11 @@ function PullRequestCodeTab({ setViewed(file.path, viewed, commit === null ? file.fileDiff.newObjectId : undefined); } setFoldChoices((current) => - range.reduce((next, file) => withFileDiffFold(next, file.fileKey, viewed), current), + range.reduce( + (next, file) => + withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), + current, + ), ); }; const fileViewedToggle = { diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts index 47f309b3e32c0..ce73f75d2db0c 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts @@ -1,12 +1,7 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; -import { - getFileViewedRange, - isFileDiffCollapsed, - isLineInFileDiff, - withFileDiffFold, -} from "./pullRequestDiff.logic"; +import { getFileViewedRange, isLineInFileDiff } from "./pullRequestDiff.logic"; function fileWithHunks( hunks: ReadonlyArray<{ @@ -40,35 +35,6 @@ describe("isLineInFileDiff", () => { }); }); -describe("isFileDiffCollapsed", () => { - // regression: #9174 diffs now expand by default; a reader's fold must survive new slices - it("keeps a file the reader folded closed as the next slice arrives", () => { - const choices = new Map([["b.ts", true]]); - expect(isFileDiffCollapsed("b.ts", "expanded", choices)).toBe(true); - expect(isFileDiffCollapsed("c.ts", "expanded", choices)).toBe(false); - }); - - it("folds a file marked Viewed when the Code tab mounts again with no fold choices", () => { - expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), true)).toBe(true); - expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), false)).toBe(false); - }); - - it("keeps a reader's choice when the file's Viewed mark loads later", () => { - const choices = new Map([["a.ts", false]]); - expect(isFileDiffCollapsed("a.ts", "expanded", choices, false)).toBe(false); - expect(isFileDiffCollapsed("a.ts", "expanded", choices, true)).toBe(false); - }); -}); - -describe("withFileDiffFold", () => { - it("records an absolute choice and keeps the same map when nothing changes", () => { - const folded = withFileDiffFold(new Map(), "a.ts", true); - expect(folded.get("a.ts")).toBe(true); - expect(withFileDiffFold(folded, "a.ts", true)).toBe(folded); - expect(withFileDiffFold(folded, "a.ts", false).get("a.ts")).toBe(false); - }); -}); - describe("getFileViewedRange", () => { const files = ["c.ts", "a.ts", "b.ts", "d.ts"].map((fileKey) => ({ fileKey })); diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts index da3844e90e1bb..f0c01a0611c3b 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts @@ -14,33 +14,6 @@ export function isLineInFileDiff( ); } -export type DiffFoldOverride = "expanded" | "folded" | null; - -/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */ -export type FileDiffFoldChoices = ReadonlyMap; - -/** - * A reader's own choice wins. Otherwise the toolbar decides, and a file still marked Viewed - * starts folded. Fold all and Expand all clear the choices, so later pages follow the toolbar. - */ -export function isFileDiffCollapsed( - fileKey: string, - foldOverride: DiffFoldOverride, - choices: FileDiffFoldChoices, - viewed = false, -): boolean { - return choices.get(fileKey) ?? (foldOverride === "folded" || viewed); -} - -export function withFileDiffFold( - choices: FileDiffFoldChoices, - fileKey: string, - collapsed: boolean, -): FileDiffFoldChoices { - if (choices.get(fileKey) === collapsed) return choices; - return new Map(choices).set(fileKey, collapsed); -} - export function getFileViewedRange( files: ReadonlyArray, fileKey: string, diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 19989716bc3c6..6fa96cdd493ae 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -3,6 +3,10 @@ "private": true, "type": "module", "exports": { + "./pull-request-diff-fold": { + "types": "./src/pullRequestDiffFold.ts", + "default": "./src/pullRequestDiffFold.ts" + }, "./assembly-highlighting": { "types": "./src/assemblyHighlighting.ts", "default": "./src/assemblyHighlighting.ts" diff --git a/packages/client-runtime/src/pullRequestDiffFold.test.ts b/packages/client-runtime/src/pullRequestDiffFold.test.ts new file mode 100644 index 0000000000000..34269c2212a05 --- /dev/null +++ b/packages/client-runtime/src/pullRequestDiffFold.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { isFileDiffCollapsed, withFileDiffFold } from "./pullRequestDiffFold.ts"; + +describe("isFileDiffCollapsed", () => { + it("collapses saved viewed files on reopening and when a later read marks them viewed", () => { + const overrides = new Map(); + expect(isFileDiffCollapsed("a.ts", null, overrides, false)).toBe(false); + expect(isFileDiffCollapsed("a.ts", null, overrides, true)).toBe(true); + expect(isFileDiffCollapsed("a.ts", null, overrides, false)).toBe(false); + }); + + it("preserves individual choices while viewed state and loaded pages change", () => { + const overrides = new Map([ + ["a.ts", false], + ["b.ts", true], + ]); + expect(isFileDiffCollapsed("a.ts", null, overrides, true)).toBe(false); + expect(isFileDiffCollapsed("b.ts", null, overrides, false)).toBe(true); + expect(isFileDiffCollapsed("c.ts", null, overrides, true)).toBe(true); + expect(isFileDiffCollapsed("d.ts", null, overrides, false)).toBe(false); + }); + + it("respects expand all and fold all, including later pages and individual exceptions", () => { + const overrides = new Map(); + expect(isFileDiffCollapsed("a.ts", "expanded", overrides, true)).toBe(false); + expect(isFileDiffCollapsed("b.ts", "folded", overrides, false)).toBe(true); + expect(isFileDiffCollapsed("c.ts", "folded", new Map([["c.ts", false]]), true)).toBe(false); + expect(isFileDiffCollapsed("d.ts", "expanded", new Map([["d.ts", true]]), false)).toBe(true); + }); +}); + +describe("withFileDiffFold", () => { + it("records or clears a choice and keeps the same map when nothing changes", () => { + const folded = withFileDiffFold(new Map(), "a.ts", true); + expect(folded.get("a.ts")).toBe(true); + expect(withFileDiffFold(folded, "a.ts", true)).toBe(folded); + expect(withFileDiffFold(folded, "a.ts", false).get("a.ts")).toBe(false); + expect(withFileDiffFold(folded, "a.ts", undefined).has("a.ts")).toBe(false); + }); +}); diff --git a/packages/client-runtime/src/pullRequestDiffFold.ts b/packages/client-runtime/src/pullRequestDiffFold.ts new file mode 100644 index 0000000000000..8083c93c25b09 --- /dev/null +++ b/packages/client-runtime/src/pullRequestDiffFold.ts @@ -0,0 +1,25 @@ +export type DiffFoldOverride = "expanded" | "folded" | null; + +/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */ +export type FileDiffFoldChoices = ReadonlyMap; + +export function isFileDiffCollapsed( + fileKey: string, + foldOverride: DiffFoldOverride, + choices: FileDiffFoldChoices, + viewed = false, +): boolean { + return choices.get(fileKey) ?? (foldOverride === null ? viewed : foldOverride === "folded"); +} + +export function withFileDiffFold( + choices: FileDiffFoldChoices, + fileKey: string, + collapsed: boolean | undefined, +): FileDiffFoldChoices { + if (choices.get(fileKey) === collapsed) return choices; + const next = new Map(choices); + if (collapsed === undefined) next.delete(fileKey); + else next.set(fileKey, collapsed); + return next; +}