TypeScript
fix(web): pull request diff follows the file tree, with a hide-tests filter (#26730)
Julius Marmingea5448f4c5030
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsxindex 80391ef4060..446794800ea 100644--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx@@ -41,7 +41,7 @@ import {pullRequestDiffInitialPosition,} from "./pullRequestDiffDebug";import { usePullRequestDiffHighlightFiles } from "./usePullRequestDiffHighlightFiles";-import { isPullRequestTestFile } from "./pullRequestFileFilters";+import { isTestChangedFile } from "@t3tools/shared/changedFileKind";import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";import type { NativeStackNavigationProp } from "@react-navigation/native-stack";import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";@@ -1035,7 +1035,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {const jumpedUnder = useRef<boolean | null>(filter.hideTestFiles);const hasTestFiles =result.parsed.kind === "files" &&- result.parsed.files.some((file) => isPullRequestTestFile(file.path));+ result.parsed.files.some((file) => isTestChangedFile(file.path));const jumpStarted = () =>jumpedUnder.current !== null && (!hasTestFiles || jumpedUnder.current === filter.hideTestFiles);const scrollToFile = (fileId: string) => {diff --git a/apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts b/apps/mobile/src/features/pull-requests/pullRequestFileFilters.tsindex 2d8e3a94fe4..2e0424ddbba 100644--- a/apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts@@ -1,12 +1,6 @@-import { classifyChangedFile } from "@t3tools/shared/changedFileKind";+import { isTestChangedFile } from "@t3tools/shared/changedFileKind";import type { ReviewParsedDiff } from "../review/reviewModel";-/** Test support such as fixtures and snapshots is hidden along with the tests. */-export function isPullRequestTestFile(path: string): boolean {- const kind = classifyChangedFile(path);- return kind === "tests" || kind === "mocks";-}-export function filterPullRequestTestFiles(parsed: ReviewParsedDiff,hideTestFiles: boolean,@@ -14,7 +8,7 @@ export function filterPullRequestTestFiles(): ReviewParsedDiff {if (!hideTestFiles || parsed.kind !== "files") return parsed;const files = parsed.files.filter(- (file) => file.path === includePath || !isPullRequestTestFile(file.path),+ (file) => file.path === includePath || !isTestChangedFile(file.path),);if (files.length === parsed.files.length) return parsed;return {diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex c257d0ea52d..ddce50db3cf 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -12,6 +12,7 @@ import {CheckIcon,ChevronDownIcon,Columns2Icon,+ FlaskConicalOffIcon,FolderTreeIcon,PilcrowIcon,Rows3Icon,@@ -37,6 +38,8 @@ import {useDiffPanelStore,} from "../diffPanelStore";import { useLocalStorage } from "../hooks/useLocalStorage";+import { isTestChangedFile } from "@t3tools/shared/changedFileKind";+import { useHideTestFiles } from "./diffs/useHideTestFiles";import { useRenderedAppearance } from "../hooks/useTheme";import { useStableCallback } from "../hooks/useStableCallback";import {@@ -218,6 +221,7 @@ export default function DiffPanel({false,Schema.Boolean,);+ const [hideTestFiles, setHideTestFiles] = useHideTestFiles();const [baseRefQuery, setBaseRefQuery] = useState("");const [codeViewRevision, setCodeViewRevision] = useState(0);@@ -539,6 +543,16 @@ export default function DiffPanel({const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;const renderableFileEntries = renderableFiles.map(getCachedFileEntry);const diffFileKeys = renderableFileEntries.map((file) => file.fileKey);+ const testFileCount = renderableFiles.filter((file) =>+ isTestChangedFile(resolveFileDiffPath(file)),+ ).length;+ // Hiding is display-only: lazy loading indexes into the full list. A requested file stays visible.+ const isFileShown = (file: FileDiffMetadata) => {+ const path = resolveFileDiffPath(file);+ return !hideTestFiles || path === selectedFilePath || !isTestChangedFile(path);+ };+ const shownFileEntries = renderableFileEntries.filter(({ fileDiff }) => isFileShown(fileDiff));+ const shownFileKeys = shownFileEntries.map((file) => file.fileKey);const defaultCollapsedDiffFileKeys = settings.diffFilesCollapsed? new Set(diffFileKeys): EMPTY_COLLAPSED_DIFF_FILE_KEYS;@@ -561,7 +575,7 @@ export default function DiffPanel({count={renderableFiles.length - settledFileCount}/>) : null;- const codeViewFiles = renderableFileEntries+ const codeViewFiles = shownFileEntries.filter(({ fileDiff }) =>!lazySource || !readyFilePaths || readyFilePaths.has(resolveFileDiffPath(fileDiff)),@@ -574,10 +588,12 @@ export default function DiffPanel({collapsed:collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,}));- const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));- const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);+ const pendingFiles = renderableFiles.filter(+ (file) => file.cacheKey?.endsWith(":pending") && isFileShown(file),+ );+ const allDiffFilesCollapsed = areAllDiffFilesCollapsed(shownFileKeys, collapsedDiffFileKeys);const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);- const fileTreeEntries = diffFileTreeEntries(renderableFiles);+ const fileTreeEntries = diffFileTreeEntries(renderableFiles.filter(isFileShown));const codeViewReveal = useCodeViewFileReveal();const revealDiffFile = (filePath: string) => {const index = renderableFileEntries.findIndex(@@ -661,7 +677,7 @@ export default function DiffPanel({const toggleDiffFileCollapse = () => {setCodeViewRevision((current) => current + 1);- updateCollapsedDiffFiles((current) => toggleAllDiffFiles(diffFileKeys, current));+ updateCollapsedDiffFiles((current) => toggleAllDiffFiles(shownFileKeys, current));};const selectTurn = (runId: RunId) => {@@ -991,6 +1007,28 @@ export default function DiffPanel({{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}</TooltipPopup></Tooltip>+ {testFileCount > 0 && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Toggle+ aria-label="Hide test files"+ variant="ghost"+ size="sm"+ pressed={hideTestFiles}+ onPressedChange={(pressed) => setHideTestFiles(Boolean(pressed))}+ />+ }+ >+ <FlaskConicalOffIcon className="size-3.5" />+ </TooltipTrigger>+ <TooltipPopup side="top">+ {hideTestFiles+ ? `Show ${testFileCount} hidden test ${testFileCount === 1 ? "file" : "files"}`+ : "Hide test files"}+ </TooltipPopup>+ </Tooltip>+ )}{diffFileKeys.length > 0 && (<Tooltip><TooltipTriggerdiff --git a/apps/web/src/components/diffs/diffFileTree.logic.test.ts b/apps/web/src/components/diffs/diffFileTree.logic.test.tsindex 757ab3f83de..dea4b9981c8 100644--- a/apps/web/src/components/diffs/diffFileTree.logic.test.ts+++ b/apps/web/src/components/diffs/diffFileTree.logic.test.ts@@ -1,7 +1,11 @@import type { FileDiffMetadata } from "@pierre/diffs";import { describe, expect, it } from "vite-plus/test";-import { buildDiffFileTreeUpdates, diffFileTreeEntries } from "./diffFileTree.logic";+import {+ buildDiffFileTreeUpdates,+ diffFileTreeEntries,+ orderDiffFilesLikeTree,+} from "./diffFileTree.logic";function file(type: FileDiffMetadata["type"], name: string, prevName = name): FileDiffMetadata {return { type, name, prevName } as FileDiffMetadata;@@ -24,6 +28,26 @@ describe("diffFileTreeEntries", () => {});});+describe("orderDiffFilesLikeTree", () => {+ it("pulls a test listed last into its directory, keeping the first-seen order", () => {+ expect(+ orderDiffFilesLikeTree([+ file("change", "server/device/Host.ts"),+ file("change", "web/settings.ts"),+ file("change", "server/ws.ts"),+ file("change", "server/device/Host.test.ts"),+ file("change", "web/settings.test.ts"),+ ]).map((entry) => entry.name),+ ).toEqual([+ "server/device/Host.ts",+ "server/device/Host.test.ts",+ "server/ws.ts",+ "web/settings.ts",+ "web/settings.test.ts",+ ]);+ });+});+describe("buildDiffFileTreeUpdates", () => {it("adds a new file's directories before the file", () => {expect(buildDiffFileTreeUpdates(["README.md"], ["README.md", "src/lib/a.ts"])).toEqual([diff --git a/apps/web/src/components/diffs/diffFileTree.logic.ts b/apps/web/src/components/diffs/diffFileTree.logic.tsindex abb3a00c768..41d2a5e676e 100644--- a/apps/web/src/components/diffs/diffFileTree.logic.ts+++ b/apps/web/src/components/diffs/diffFileTree.logic.ts@@ -98,6 +98,36 @@ export function diffFileTreePositions(paths: ReadonlyArray<string>): ReadonlyMapreturn positions;}+// A flat list in tree order: each directory stays contiguous, siblings ranked as+// compareDiffFileTreeEntries ranks them, so the list never disagrees with the tree.+export function orderDiffFilesLikeTree(+ files: ReadonlyArray<FileDiffMetadata>,+): ReadonlyArray<FileDiffMetadata> {+ const paths = files.map(resolveFileDiffPath);+ const positions = diffFileTreePositions(paths);+ const keys = paths.map((path) => {+ const key: number[] = [];+ let directory = "";+ for (const segment of path.split("/").slice(0, -1)) {+ directory += `${segment}/`;+ key.push(positions.get(directory)!);+ }+ key.push(positions.get(path)!);+ return key;+ });+ return files+ .map((file, index) => ({ file, key: keys[index]! }))+ .toSorted((left, right) => {+ const length = Math.min(left.key.length, right.key.length);+ for (let index = 0; index < length; index++) {+ const difference = left.key[index]! - right.key[index]!;+ if (difference !== 0) return difference;+ }+ return left.key.length - right.key.length;+ })+ .map(({ file }) => file);+}+export function compareDiffFileTreeEntries(getPositions: () => ReadonlyMap<string, number>,): FileTreeSortComparator {diff --git a/apps/web/src/components/diffs/useHideTestFiles.ts b/apps/web/src/components/diffs/useHideTestFiles.tsnew file mode 100644index 00000000000..a1f806ecb46--- /dev/null+++ b/apps/web/src/components/diffs/useHideTestFiles.ts@@ -0,0 +1,9 @@+import * as Schema from "effect/Schema";++import { useLocalStorage } from "~/hooks/useLocalStorage";++const HIDE_TEST_FILES_STORAGE_KEY = "t3code.diffHideTestFiles";++export function useHideTestFiles() {+ return useLocalStorage(HIDE_TEST_FILES_STORAGE_KEY, false, Schema.Boolean);+}diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex d1b165c6214..94f4ccda825 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -19,6 +19,7 @@ import {ChevronDownIcon,ChevronRightIcon,Columns2Icon,+ FlaskConicalOffIcon,FolderTreeIcon,InfoIcon,MessageSquareOffIcon,@@ -51,6 +52,7 @@ import {canEditPullRequestComment,canResolvePullRequestThread,} from "@t3tools/client-runtime/pull-request-editing";+import { isTestChangedFile } from "@t3tools/shared/changedFileKind";import { orderDiffFiles } from "./pullRequestFileOrder.logic";import {buildFileDiffRenderKey,@@ -80,7 +82,8 @@ import { useDiffWorkerPool } from "../DiffWorkerPoolProvider";import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";import { DiffFileTree } from "../diffs/DiffFileTree";import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";-import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";+import { useHideTestFiles } from "../diffs/useHideTestFiles";+import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic";import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";import { Button } from "../ui/button";import { MorphIcon } from "~/components/MorphIcon";@@ -307,6 +310,7 @@ function PullRequestCodeTab({false,Schema.Boolean,);+ const [hideTestFiles, setHideTestFiles] = useHideTestFiles();const [selectedLines, setSelectedLines] = useState<{id: string;range: SelectedLineRange;@@ -496,9 +500,22 @@ function PullRequestCodeTab({ignoreWhitespace,),);- const files = parsedSlices.flatMap((parsed) =>- parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],+ const loadedFiles = orderDiffFilesLikeTree(+ parsedSlices.flatMap((parsed) =>+ parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],+ ),);+ const testFileCount = loadedFiles.filter((file) =>+ isTestChangedFile(resolveFileDiffPath(file)),+ ).length;+ // A requested file stays visible so a jump to a hidden test still lands.+ const files = hideTestFiles+ ? loadedFiles.filter((file) => {+ const path = resolveFileDiffPath(file);+ return path === revealRequest?.path || !isTestChangedFile(path);+ })+ : loadedFiles;+ const hiddenTestFileCount = loadedFiles.length - files.length;const filePaths = files.map((file) => resolveFileDiffPath(file));const omittedFileStats = new Map(loadedSlices.flatMap((slice) =>@@ -1071,6 +1088,11 @@ function PullRequestCodeTab({{files.length} {files.length === 1 ? "file" : "files"}{nextCursor === null ? "" : "+"}</span>+ {hiddenTestFileCount > 0 ? (+ <Button type="button" size="xs" variant="link" onClick={() => setHideTestFiles(false)}>+ {hiddenTestFileCount} test {hiddenTestFileCount === 1 ? "file" : "files"} hidden+ </Button>+ ) : null}{filesViewed.enabled && files.length > 0 ? (<span className="flex min-w-0 items-center gap-1 tabular-nums"><span className="shrink-0">@@ -1283,6 +1305,26 @@ function PullRequestCodeTab({</TooltipPopup></Tooltip>) : null}+ {testFileCount > 0 ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Toggle+ aria-label="Hide test files"+ variant="ghost"+ size="sm"+ pressed={hideTestFiles}+ onPressedChange={(pressed) => setHideTestFiles(Boolean(pressed))}+ />+ }+ >+ <FlaskConicalOffIcon className="size-3.5" />+ </TooltipTrigger>+ <TooltipPopup side="top">+ {hideTestFiles ? "Show test files" : "Hide test files"}+ </TooltipPopup>+ </Tooltip>+ ) : null}{fileKeys.length > 0 ? (<Tooltip><TooltipTriggerdiff --git a/packages/shared/src/changedFileKind.ts b/packages/shared/src/changedFileKind.tsindex 9fd5c0c7edc..01cbe899b26 100644--- a/packages/shared/src/changedFileKind.ts+++ b/packages/shared/src/changedFileKind.ts@@ -67,6 +67,11 @@ const NOT_DOCS_NAME = /^(requirements.*|constraints.*|CMakeLists|robots|llms)\.t* output count as generated, and test support (mocks, fixtures, snapshots) is kept apart from the* tests themselves, and prose (Markdown, plain text) is its own kind, so a reviewer can see how much of a change is logic.*/+export function isTestChangedFile(path: string): boolean {+ const kind = classifyChangedFile(path);+ return kind === "tests" || kind === "mocks";+}+export function classifyChangedFile(path: string): ChangedFileKind {const segments = path.replaceAll("\\", "/").split("/");const name = segments.pop() ?? "";