TypeScript
feat(web): add a file tree to the diff panel and pull request code tab (#9330)
Julius Marminge1aa44a071f66
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex c55eaa09478..c773617a7cf 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -15,12 +15,14 @@ import {ChevronsDownUpIcon,ChevronsUpDownIcon,Columns2Icon,+ FolderTreeIcon,PilcrowIcon,RefreshCwIcon,Rows3Icon,SearchIcon,TextWrapIcon,} from "lucide-react";+import * as Schema from "effect/Schema";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useOpenInPreferredEditor } from "../editorPreferences";import { type DraftId } from "../composerDraftStore";@@ -28,6 +30,7 @@ import { openDiffFilePrimaryAction } from "../diffFileActions";import { useCheckpointDiff } from "~/lib/checkpointDiffState";import { cn } from "~/lib/utils";import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";+import { useLocalStorage } from "../hooks/useLocalStorage";import { useTheme } from "../hooks/useTheme";import {buildFileDiffContentVersion,@@ -50,6 +53,8 @@ import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";import { DiffStatLabel } from "./chat/DiffStatLabel";import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";+import { DiffFileTree } from "./diffs/DiffFileTree";+import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";import { Button } from "./ui/button";import { ToggleGroup, Toggle } from "./ui/toggle-group";import { Switch } from "./ui/switch";@@ -82,6 +87,7 @@ import { createGitDiffFileContentsLoader } from "../lib/diffFileContents";type DiffThemeType = "light" | "dark";const AUTOMATIC_BASE_REF = "__automatic_base_ref__";+const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen";interface CollapsedDiffFilesState {readonly scopeKey: string | null;@@ -112,6 +118,11 @@ export default function DiffPanel({const updateClientSettings = useUpdateClientSettings();const [wordWrap, setWordWrap] = useState(settings.wordWrap);const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);+ const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(+ DIFF_FILE_TREE_STORAGE_KEY,+ false,+ Schema.Boolean,+ );const [baseRefQuery, setBaseRefQuery] = useState("");const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({scopeKey: null,@@ -431,6 +442,7 @@ export default function DiffPanel({const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);+ const fileTreeEntries = useMemo(() => diffFileTreeEntries(renderableFiles), [renderableFiles]);const selectedDiffFileKey = selectedFilePath? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null): null;@@ -440,6 +452,29 @@ export default function DiffPanel({codeViewRef.current?.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });}, [codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);+ // Held as state so the scroll runs after a collapsed file has been drawn open again; scrolling+ // in the same tick would land on the folded header's position.+ const [treeReveal, setTreeReveal] = useState<{ fileKey: string; id: number } | null>(null);+ useEffect(() => {+ if (treeReveal === null) return;+ codeViewRef.current?.scrollTo({ type: "item", id: treeReveal.fileKey, align: "start" });+ }, [treeReveal]);+ const revealDiffFile = useCallback(+ (filePath: string) => {+ const file = codeViewFiles.find((candidate) => candidate.filePath === filePath);+ if (!file) return;+ if (file.collapsed) {+ setCollapsedDiffFiles((current) => {+ const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []);+ next.delete(file.fileKey);+ return { scopeKey: collapseScopeKey, fileKeys: next };+ });+ }+ setTreeReveal((current) => ({ fileKey: file.fileKey, id: (current?.id ?? 0) + 1 }));+ },+ [codeViewFiles, collapseScopeKey],+ );+const openDiffFile = useCallback((filePath: string) => {openDiffFilePrimaryAction({@@ -825,6 +860,26 @@ export default function DiffPanel({{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}</TooltipPopup></Tooltip>+ {codeViewFiles.length > 0 && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Toggle+ aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}+ variant="ghost"+ size="sm"+ pressed={fileTreeOpen}+ onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}+ />+ }+ >+ <FolderTreeIcon className="size-3.5" />+ </TooltipTrigger>+ <TooltipPopup side="top">+ {fileTreeOpen ? "Hide file tree" : "Show file tree"}+ </TooltipPopup>+ </Tooltip>+ )}</div></>);@@ -878,97 +933,114 @@ export default function DiffPanel({</div>)) : renderablePatch.kind === "files" ? (- <div- className="min-h-0 flex-1"- onClickCapture={(event) => {- const composedPath = event.nativeEvent.composedPath?.() ?? [];- for (const node of composedPath) {- if (!(node instanceof HTMLElement)) continue;- // Header controls keep their own actions. In particular, the chevron must- // not also trigger the row handler or the two toggles cancel each other.- if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {+ <div className="flex min-h-0 flex-1 overflow-hidden">+ <div+ className="min-h-0 min-w-0 flex-1"+ onClickCapture={(event) => {+ const composedPath = event.nativeEvent.composedPath?.() ?? [];+ for (const node of composedPath) {+ if (!(node instanceof HTMLElement)) continue;+ // Header controls keep their own actions. In particular, the chevron must+ // not also trigger the row handler or the two toggles cancel each other.+ if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {+ return;+ }+ }+ const title = composedPath.find(+ (node): node is HTMLElement =>+ node instanceof HTMLElement && node.hasAttribute("data-title"),+ );+ const filePath = title?.textContent?.trim();+ // The filename remains the explicit "open in editor" affordance.+ if (filePath) {+ openDiffFile(filePath);return;}- }- const title = composedPath.find(- (node): node is HTMLElement =>- node instanceof HTMLElement && node.hasAttribute("data-title"),- );- const filePath = title?.textContent?.trim();- // The filename remains the explicit "open in editor" affordance.- if (filePath) {- openDiffFile(filePath);- return;- }- const header = composedPath.find(- (node): node is HTMLElement =>- node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),- );- const headerFilePath = header?.querySelector("[data-title]")?.textContent?.trim();- if (!headerFilePath) return;- const file = codeViewFiles.find(- (candidate) => candidate.filePath === headerFilePath,- );- if (file) toggleDiffFileCollapsed(file.fileKey);- }}- >- <AnnotatableCodeView- key={collapseScopeKey ?? reviewSectionId}- viewerRef={codeViewRef}- codeViewKey={codeViewMountKey}- className="h-full min-h-0 overflow-auto"- files={codeViewFiles}- sectionId={reviewSectionId}- sectionTitle={reviewSectionTitle}- composerDraftTarget={composerDraftTarget}- renderHeaderFilenameSuffix={(fileDiff) => (- <DiffFilePathCopyButton filePath={resolveFileDiffPath(fileDiff)} />- )}- renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {- const filePath = resolveFileDiffPath(fileDiff);- return (- <Tooltip>- <TooltipTrigger- render={- <Button- size="icon-micro"- variant="ghost"- className={cn(- "-ms-0.5 [--control-icon-color:currentColor] bg-transparent hover:bg-foreground/10",- getDiffCollapseIconClassName(fileDiff),- )}- aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}- aria-expanded={!collapsed}- onClick={(event) => {- event.stopPropagation();- toggleDiffFileCollapsed(fileKey);- }}- />- }- >- {collapsed ? (- <ChevronRightIcon className="size-4" />- ) : (- <ChevronDownIcon className="size-4" />- )}- </TooltipTrigger>- <TooltipPopup side="top">- {collapsed ? "Expand diff" : "Collapse diff"}- </TooltipPopup>- </Tooltip>+ const header = composedPath.find(+ (node): node is HTMLElement =>+ node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),);+ const headerFilePath = header+ ?.querySelector("[data-title]")+ ?.textContent?.trim();+ if (!headerFilePath) return;+ const file = codeViewFiles.find(+ (candidate) => candidate.filePath === headerFilePath,+ );+ if (file) toggleDiffFileCollapsed(file.fileKey);}}- options={{- diffStyle: diffLayout === "split" ? "split" : "unified",- lineDiffType: "none",- overflow: wordWrap ? "wrap" : "scroll",- theme: resolveDiffThemeName(resolvedTheme),- preferredHighlighter: PREFERRED_HIGHLIGHTER,- themeType: resolvedTheme as DiffThemeType,- stickyHeaders: true,- ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),- }}- />+ >+ <AnnotatableCodeView+ key={collapseScopeKey ?? reviewSectionId}+ viewerRef={codeViewRef}+ codeViewKey={codeViewMountKey}+ className="h-full min-h-0 overflow-auto"+ files={codeViewFiles}+ sectionId={reviewSectionId}+ sectionTitle={reviewSectionTitle}+ composerDraftTarget={composerDraftTarget}+ renderHeaderFilenameSuffix={(fileDiff) => (+ <DiffFilePathCopyButton filePath={resolveFileDiffPath(fileDiff)} />+ )}+ renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {+ const filePath = resolveFileDiffPath(fileDiff);+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-micro"+ variant="ghost"+ className={cn(+ "-ms-0.5 [--control-icon-color:currentColor] bg-transparent hover:bg-foreground/10",+ getDiffCollapseIconClassName(fileDiff),+ )}+ aria-label={+ collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`+ }+ aria-expanded={!collapsed}+ onClick={(event) => {+ event.stopPropagation();+ toggleDiffFileCollapsed(fileKey);+ }}+ />+ }+ >+ {collapsed ? (+ <ChevronRightIcon className="size-4" />+ ) : (+ <ChevronDownIcon className="size-4" />+ )}+ </TooltipTrigger>+ <TooltipPopup side="top">+ {collapsed ? "Expand diff" : "Collapse diff"}+ </TooltipPopup>+ </Tooltip>+ );+ }}+ options={{+ diffStyle: diffLayout === "split" ? "split" : "unified",+ lineDiffType: "none",+ overflow: wordWrap ? "wrap" : "scroll",+ theme: resolveDiffThemeName(resolvedTheme),+ preferredHighlighter: PREFERRED_HIGHLIGHTER,+ themeType: resolvedTheme as DiffThemeType,+ stickyHeaders: true,+ ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),+ }}+ />+ </div>+ {fileTreeOpen ? (+ <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">+ <DiffFileTree+ ariaLabel={`${reviewSectionTitle} files`}+ entries={fileTreeEntries}+ selectedPath={selectedFilePath}+ revealRequestId={selectedFileRevealRequestId}+ onSelectFile={revealDiffFile}+ />+ </aside>+ ) : null}</div>) : (<div className="min-h-0 flex-1 overflow-auto p-2">diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsxnew file mode 100644index 00000000000..3715b62ca15--- /dev/null+++ b/apps/web/src/components/diffs/DiffFileTree.tsx@@ -0,0 +1,186 @@+import type { GitStatusEntry } from "@pierre/trees";+import { FileTree, useFileTree, useFileTreeSelector } from "@pierre/trees/react";+import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";+import { useEffect, useMemo, useRef, type ReactNode } from "react";++import { useTheme } from "~/hooks/useTheme";+import { cn } from "~/lib/utils";+import { T3_PIERRE_ICONS } from "~/pierre-icons";+import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";++import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "../files/fileTreeExpansion";+import { Button } from "../ui/button";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";+import {+ buildDiffFileTreeUpdates,+ collectDirectoryPaths,+ type DiffFileTreeEntry,+} from "./diffFileTree.logic";++export type { DiffFileTreeEntry } from "./diffFileTree.logic";++interface DiffFileTreeProps {+ readonly entries: ReadonlyArray<DiffFileTreeEntry>;+ /** Called with the file's path when the reader picks a file row. */+ readonly onSelectFile: (path: string) => void;+ /**+ * The file the diff is currently showing, kept selected in the tree. Bump `revealRequestId` to+ * scroll the tree to the same path again.+ */+ readonly selectedPath?: string | null;+ readonly revealRequestId?: number;+ readonly ariaLabel: string;+ /** Right-aligned content in the header row, after the file count. */+ readonly headerAccessory?: ReactNode;+ /** Rendered under the tree, for a host that still has files to fetch. */+ readonly footer?: ReactNode;+ readonly className?: string;+}++/**+ * A directory tree of the files in a diff. Every directory starts open: a diff is a short list+ * compared to a workspace, and the reader came for the files, not the folders.+ */+export function DiffFileTree({+ entries,+ onSelectFile,+ selectedPath = null,+ revealRequestId = 0,+ ariaLabel,+ headerAccessory,+ footer,+ className,+}: DiffFileTreeProps) {+ const { resolvedTheme } = useTheme();+ const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);+ const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);+ const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(+ () => entries.map((entry) => ({ path: entry.path, status: entry.status })),+ [entries],+ );+ const filePathsRef = useRef<ReadonlySet<string>>(new Set(paths));+ const onSelectFileRef = useRef(onSelectFile);+ // Selection driven by `selectedPath` below is an echo of a file already on screen, not a+ // request to scroll to it again.+ const syncingSelectionRef = useRef(false);+ const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);+ const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);++ useEffect(() => {+ filePathsRef.current = new Set(paths);+ onSelectFileRef.current = onSelectFile;+ }, [onSelectFile, paths]);++ const { model } = useFileTree({+ density: "compact",+ flattenEmptyDirectories: true,+ initialExpansion: "open",+ icons: T3_PIERRE_ICONS,+ onSelectionChange: (selectedPaths) => {+ if (syncingSelectionRef.current) return;+ const path = selectedPaths.at(-1)?.replace(/\/$/, "");+ if (path && filePathsRef.current.has(path)) onSelectFileRef.current(path);+ },+ paths: [],+ search: false,+ unsafeCSS: PIERRE_TREE_UNSAFE_CSS,+ });+ const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>+ areAllDirectoriesExpanded(currentModel, directoryPaths),+ );++ useEffect(() => {+ const mountedPaths = mountedPathsRef.current;+ if (mountedPaths === paths) return;+ mountedPathsRef.current = paths;+ if (mountedPaths === null) {+ model.resetPaths(paths);+ } else {+ const updates = buildDiffFileTreeUpdates(mountedPaths, paths);+ if (updates.length > 0) model.batch(updates);+ }+ model.setGitStatus(gitStatus);+ }, [gitStatus, model, paths]);++ useEffect(() => {+ if (selectedPath === null) {+ handledRevealRef.current = null;+ return;+ }+ // A path list that changes under an already-revealed file (a refresh, a later slice) must+ // not pull the tree back to it over whatever the reader has picked since.+ const item = model.getItem(selectedPath);+ if (item === null || item.isDirectory()) {+ // A file that left the diff has to be revealed again when it comes back.+ handledRevealRef.current = null;+ return;+ }+ const handled = handledRevealRef.current;+ if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;+ handledRevealRef.current = { path: selectedPath, revealRequestId };+ syncingSelectionRef.current = true;+ for (const path of model.getSelectedPaths()) {+ if (path !== selectedPath) model.getItem(path)?.deselect();+ }+ let ancestor = "";+ for (const segment of selectedPath.split("/").slice(0, -1)) {+ ancestor += `${segment}/`;+ const directory = model.getItem(ancestor);+ if (directory !== null && "expand" in directory) directory.expand();+ }+ item.select();+ model.scrollToPath(selectedPath, { offset: "nearest" });+ queueMicrotask(() => {+ syncingSelectionRef.current = false;+ });+ // `paths` is a dependency so a file that arrives after it was asked for is still revealed.+ }, [model, paths, revealRequestId, selectedPath]);++ return (+ <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>+ <div+ className="flex h-10 min-h-10 shrink-0 items-center gap-1 border-b border-border/60 bg-background px-2 text-xs text-muted-foreground in-data-[preview-panel-mode=inline]:mb-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent"+ data-surface-subheader+ >+ <span className="px-1 font-medium text-foreground">Files</span>+ <span className="ml-auto tabular-nums">{entries.length}</span>+ {headerAccessory}+ {directoryPaths.length > 0 ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label={+ allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"+ }+ onClick={() =>+ setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)+ }+ />+ }+ >+ {allDirectoriesExpanded ? (+ <ChevronsDownUpIcon className="size-3.5" />+ ) : (+ <ChevronsUpDownIcon className="size-3.5" />+ )}+ </TooltipTrigger>+ <TooltipPopup>+ {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}+ </TooltipPopup>+ </Tooltip>+ ) : null}+ </div>+ <FileTree+ model={model}+ aria-label={ariaLabel}+ className="min-h-0 flex-1 overflow-hidden"+ style={pierreTreeStyle(resolvedTheme)}+ />+ {footer}+ </div>+ );+}diff --git a/apps/web/src/components/diffs/diffFileTree.logic.test.ts b/apps/web/src/components/diffs/diffFileTree.logic.test.tsnew file mode 100644index 00000000000..d8e24968dce--- /dev/null+++ b/apps/web/src/components/diffs/diffFileTree.logic.test.ts@@ -0,0 +1,69 @@+import type { FileDiffMetadata } from "@pierre/diffs";+import { describe, expect, it } from "vite-plus/test";++import {+ buildDiffFileTreeUpdates,+ collectDirectoryPaths,+ diffFileTreeEntries,+} from "./diffFileTree.logic";++function file(type: FileDiffMetadata["type"], name: string, prevName = name): FileDiffMetadata {+ return { type, name: `b/${name}`, prevName: `a/${prevName}` } as FileDiffMetadata;+}++describe("diffFileTreeEntries", () => {+ it("maps each change type to its git status under the file's current path", () => {+ expect(+ diffFileTreeEntries([+ file("new", "src/a.ts"),+ file("deleted", "src/b.ts"),+ file("rename-pure", "src/c.ts", "src/old-c.ts"),+ file("rename-changed", "src/d.ts", "src/old-d.ts"),+ file("change", "README.md"),+ ]),+ ).toEqual([+ { path: "src/a.ts", status: "added" },+ { path: "src/b.ts", status: "deleted" },+ { path: "src/c.ts", status: "renamed" },+ { path: "src/d.ts", status: "renamed" },+ { path: "README.md", status: "modified" },+ ]);+ });+});++describe("collectDirectoryPaths", () => {+ it("lists every ancestor once, parents first, with Pierre's trailing slash", () => {+ expect(collectDirectoryPaths(["apps/web/src/a.ts", "apps/web/b.ts", "README.md"])).toEqual([+ "apps/",+ "apps/web/",+ "apps/web/src/",+ ]);+ });+});++describe("buildDiffFileTreeUpdates", () => {+ it("adds a new file's directories before the file", () => {+ expect(buildDiffFileTreeUpdates(["README.md"], ["README.md", "src/lib/a.ts"])).toEqual([+ { type: "add", path: "src/" },+ { type: "add", path: "src/lib/" },+ { type: "add", path: "src/lib/a.ts" },+ ]);+ });++ it("removes files before their now-empty directories, deepest first", () => {+ expect(buildDiffFileTreeUpdates(["src/lib/a.ts", "src/b.ts"], ["src/b.ts"])).toEqual([+ { type: "remove", path: "src/lib/a.ts" },+ { type: "remove", path: "src/lib/", recursive: true },+ ]);+ });++ it("keeps a directory that still holds a file", () => {+ expect(buildDiffFileTreeUpdates(["src/a.ts", "src/b.ts"], ["src/b.ts"])).toEqual([+ { type: "remove", path: "src/a.ts" },+ ]);+ });++ it("produces nothing when the paths are unchanged", () => {+ expect(buildDiffFileTreeUpdates(["src/a.ts"], ["src/a.ts"])).toEqual([]);+ });+});diff --git a/apps/web/src/components/diffs/diffFileTree.logic.ts b/apps/web/src/components/diffs/diffFileTree.logic.tsnew file mode 100644index 00000000000..4535ece8b14--- /dev/null+++ b/apps/web/src/components/diffs/diffFileTree.logic.ts@@ -0,0 +1,93 @@+import type { FileDiffMetadata } from "@pierre/diffs";+import type { FileTreeBatchOperation, GitStatus } from "@pierre/trees";++import { resolveFileDiffPath } from "~/lib/diffRendering";++/** One changed file as the tree shows it: its current path and how it changed. */+export interface DiffFileTreeEntry {+ readonly path: string;+ readonly status: GitStatus;+}++function toGitStatus(file: FileDiffMetadata): GitStatus {+ switch (file.type) {+ case "new":+ return "added";+ case "deleted":+ return "deleted";+ case "rename-pure":+ case "rename-changed":+ return "renamed";+ case "change":+ return "modified";+ }+}++/** Maps parsed diff files to tree entries, keeping the diff's own order. */+export function diffFileTreeEntries(+ files: ReadonlyArray<FileDiffMetadata>,+): ReadonlyArray<DiffFileTreeEntry> {+ return files.map((file) => ({ path: resolveFileDiffPath(file), status: toGitStatus(file) }));+}++/**+ * Every directory on the way to each file, registered with the trailing slash Pierre uses for+ * directory ids. Parents come before children so the tree can add them in order.+ */+export function collectDirectoryPaths(paths: ReadonlyArray<string>): ReadonlyArray<string> {+ const directories = new Set<string>();+ for (const path of paths) {+ const segments = path.split("/");+ let directory = "";+ for (const segment of segments.slice(0, -1)) {+ directory += `${segment}/`;+ directories.add(directory);+ }+ }+ return [...directories];+}++function pathDepth(path: string): number {+ return path.split("/").filter(Boolean).length;+}++/**+ * The adds and removes that turn one set of file paths into another, so a diff that changes+ * under the reader (a new slice, a refresh after an agent edit) keeps the directories they+ * have already opened or closed instead of rebuilding the tree from scratch.+ *+ * Directories are removed only once no file needs them; a directory that gains its first file+ * is added before that file.+ */+export function buildDiffFileTreeUpdates(+ previousPaths: ReadonlyArray<string>,+ nextPaths: ReadonlyArray<string>,+): FileTreeBatchOperation[] {+ const previousDirectories = new Set(collectDirectoryPaths(previousPaths));+ const nextDirectories = new Set(collectDirectoryPaths(nextPaths));+ const previous = new Set(previousPaths);+ const next = new Set(nextPaths);+ const updates: FileTreeBatchOperation[] = [];++ for (const path of previousPaths) {+ if (!next.has(path)) updates.push({ type: "remove", path });+ }+ // Deepest first: a directory can only go once everything under it has.+ const removedDirectories = [...previousDirectories]+ .filter((directory) => !nextDirectories.has(directory))+ .toSorted((left, right) => pathDepth(right) - pathDepth(left));+ for (const directory of removedDirectories) {+ updates.push({ type: "remove", path: directory, recursive: true });+ }++ // Shallowest first: a file's directory has to exist before the file does.+ const addedDirectories = [...nextDirectories]+ .filter((directory) => !previousDirectories.has(directory))+ .toSorted((left, right) => pathDepth(left) - pathDepth(right));+ for (const directory of addedDirectories) updates.push({ type: "add", path: directory });+ for (const path of nextPaths) {+ if (!previous.has(path)) updates.push({ type: "add", path });+ }++ return updates;+}diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsxindex 5e4ce19335a..dc3cfcef013 100644--- a/apps/web/src/components/files/FileBrowserPanel.tsx+++ b/apps/web/src/components/files/FileBrowserPanel.tsx@@ -19,6 +19,7 @@ import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefreshimport { cn } from "~/lib/utils";import { readLocalApi } from "~/localApi";import { T3_PIERRE_ICONS } from "~/pierre-icons";+import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";import { createFileTreeDragMentionController } from "./fileTreeDragMention";import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";@@ -38,18 +39,6 @@ interface FileBrowserPanelProps {workspaceMutationId: string | null;}-const TREE_UNSAFE_CSS = `- :host {- --trees-bg-override: transparent;- --trees-selected-bg-override: color-mix(in srgb, currentColor 12%, transparent);- --trees-hover-bg-override: color-mix(in srgb, currentColor 7%, transparent);- --trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);- --trees-font-family-override: var(--font-sans);- --trees-font-size-override: 12px;- }- button[data-type='item'] { border-radius: 5px; }-`;-function treePath(entry: ProjectEntry): string {return entry.kind === "directory" ? `${entry.path}/` : entry.path;}@@ -255,7 +244,7 @@ export default function FileBrowserPanel({},paths: [],search: false,- unsafeCSS: TREE_UNSAFE_CSS,+ unsafeCSS: PIERRE_TREE_UNSAFE_CSS,});const search = useFileTreeSearch(model);const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>@@ -429,10 +418,7 @@ export default function FileBrowserPanel({model={model}aria-label={`${projectName} files`}className="min-h-0 flex-1 overflow-hidden"- style={{- colorScheme: resolvedTheme,- ["--trees-fg-override" as string]: "var(--contrast-foreground)",- }}+ style={pierreTreeStyle(resolvedTheme)}/>)}</div>diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex ebae8847bf3..cc9bf0f6188 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -1,5 +1,5 @@import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";-import type { CodeViewDiffItem } from "@pierre/diffs/react";+import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";import type {EnvironmentId,PullRequestDetailView,@@ -16,6 +16,7 @@ import {ChevronsDownUpIcon,ChevronsUpDownIcon,Columns2Icon,+ FolderTreeIcon,MessageSquareIcon,MessageSquareOffIcon,Rows3Icon,@@ -24,8 +25,10 @@ import {XIcon,} from "lucide-react";import { useAtomRefresh } from "@effect/atom-react";+import * as Schema from "effect/Schema";import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useLocalStorage } from "~/hooks/useLocalStorage";import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";import { useTheme } from "~/hooks/useTheme";import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";@@ -57,6 +60,8 @@ import { useAtomCommand } from "~/state/use-atom-command";import { DiffPanelLoadingState } from "../DiffPanelShell";import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";+import { DiffFileTree } from "../diffs/DiffFileTree";+import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";import { Button } from "../ui/button";import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";@@ -97,6 +102,8 @@ type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>;/** Commits per press of "Show more" in the scope menu. */const COMMIT_PAGE_SIZE = 10;+const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen";+/** One answer from the host: a whole number of files, and where the next one carries on. */interface DiffSlice {/** What was asked for, null being the first slice. Identifies the slice among the loaded ones. */@@ -220,6 +227,11 @@ export function PullRequestCodeTab({const diffLayout = settings.diffLayout;const updateClientSettings = useUpdateClientSettings();const [wordWrap, setWordWrap] = useState(settings.wordWrap);+ const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(+ PULL_REQUEST_FILE_TREE_STORAGE_KEY,+ false,+ Schema.Boolean,+ );const [selectedLines, setSelectedLines] = useState<{id: string;range: SelectedLineRange;@@ -238,6 +250,7 @@ export function PullRequestCodeTab({readonly slices: ReadonlyArray<DiffSlice>;}>({ key: "", cursor: null, slices: NO_SLICES });const parseCache = useRef(new Map<string, RenderablePatch>());+ const viewerRef = useRef<CodeViewHandle<ReviewAnnotationGroup> | null>(null);const referenceKey = pullRequestReviewKey(reference);const commit = selectedCommitOid;@@ -544,34 +557,35 @@ export function PullRequestCodeTab({[items],);const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys);+ const fileTreeEntries = useMemo(() => diffFileTreeEntries(files), [files]);++ // A failed slice must not be asked for again on its own. The files already loaded keep the+ // sentinel on screen, so re-arming it after a failure would request the same slice forever.+ const canLoadNextSlice =+ nextCursor !== null &&+ nextCursor !== cursor &&+ !diffQuery.isPending &&+ diffQuery.error === null;+ const loadNextSlice = useCallback(() => {+ if (nextCursor === null) return;+ setSliceState((previous) => ({ ...previous, cursor: nextCursor }));+ }, [nextCursor]);// The sentinel is held as state rather than a ref because the viewer mounts its own footer:// an effect reading a ref could run before that node exists and would never arm the observer.const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);useEffect(() => {- // A failed slice must stop the observer. The files already loaded keep the sentinel on- // screen, so re-arming it after a failure would ask for the same slice again, forever.- if (- sentinel === null ||- nextCursor === null ||- nextCursor === cursor ||- diffQuery.isPending ||- diffQuery.error !== null- ) {- return;- }+ if (sentinel === null || !canLoadNextSlice) return;const observer = new IntersectionObserver((observed) => {- if (observed.some((entry) => entry.isIntersecting)) {- setSliceState((previous) => ({ ...previous, cursor: nextCursor }));- }+ if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();},// Start the next slice slightly before the sentinel is on screen.{ rootMargin: "240px" },);observer.observe(sentinel);return () => observer.disconnect();- }, [cursor, diffQuery.error, diffQuery.isPending, nextCursor, sentinel]);+ }, [canLoadNextSlice, loadNextSlice, sentinel]);// A stable identity: the viewer's SlotPortals memoizes each file's header/annotation portal on// these render props, so a fresh function here would recreate every visible file's portal on@@ -589,6 +603,23 @@ export function PullRequestCodeTab({[],);+ // Held as state so the scroll runs after a folded file has been drawn open; scrolling in the+ // same tick would land on the folded header's position.+ const [treeReveal, setTreeReveal] = useState<{ fileKey: string; id: number } | null>(null);+ useEffect(() => {+ if (treeReveal === null) return;+ viewerRef.current?.scrollTo({ type: "item", id: treeReveal.fileKey, align: "start" });+ }, [treeReveal]);+ const revealFile = useCallback(+ (path: string) => {+ const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);+ if (item === undefined) return;+ if (item.collapsed === true) toggleFile(item.id);+ setTreeReveal((current) => ({ fileKey: item.id, id: (current?.id ?? 0) + 1 }));+ },+ [items, toggleFile],+ );+const toggleAllFiles = () => {// Held as an override of the default rather than as the file keys on screen: a diff that is// still paging would otherwise bring its next slice in folded, moments after the reader@@ -1150,6 +1181,26 @@ export function PullRequestCodeTab({{wordWrap ? "Disable line wrapping" : "Enable line wrapping"}</TooltipPopup></Tooltip>+ {fileKeys.length > 0 ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Toggle+ aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}+ variant="ghost"+ size="sm"+ pressed={fileTreeOpen}+ onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}+ />+ }+ >+ <FolderTreeIcon className="size-3.5" />+ </TooltipTrigger>+ <TooltipPopup side="top">+ {fileTreeOpen ? "Hide file tree" : "Show file tree"}+ </TooltipPopup>+ </Tooltip>+ ) : null}</div></div>);@@ -1305,58 +1356,94 @@ export function PullRequestCodeTab({</CollapsiblePanel></Collapsible>) : null}- {/* Relative wrapper so the review overlay floats over the diff rather than pushing it+ <div className="flex min-h-0 flex-1 overflow-hidden">+ {/* Relative wrapper so the review overlay floats over the diff rather than pushing itup; the viewer inside still owns its own scrolling. */}- <div- className="relative min-h-0 flex-1"- // The chevron answers this too, but the whole header row is the target a reader- // actually aims for. The header lives in the viewer's shadow tree, so the capture- // listener walks `composedPath` — the only way to see through the shadow boundary.- onClickCapture={(event) => {- const composedPath = event.nativeEvent.composedPath?.() ?? [];- for (const node of composedPath) {- if (!(node instanceof HTMLElement)) continue;- // A control inside the header — the collapse chevron — handles itself, and- // this capture listener fires before its own click does. Leave it alone or- // the two toggles cancel out.- if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {- return;- }- if (node.hasAttribute("data-diffs-header")) {- const filePath = node.querySelector("[data-title]")?.textContent?.trim();- if (filePath === undefined || filePath === "") return;- const item = items.find(- (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,- );- if (item !== undefined) toggleFile(item.id);- return;+ <div+ className="relative min-h-0 min-w-0 flex-1"+ // The chevron answers this too, but the whole header row is the target a reader+ // actually aims for. The header lives in the viewer's shadow tree, so the capture+ // listener walks `composedPath` — the only way to see through the shadow boundary.+ onClickCapture={(event) => {+ const composedPath = event.nativeEvent.composedPath?.() ?? [];+ for (const node of composedPath) {+ if (!(node instanceof HTMLElement)) continue;+ // A control inside the header — the collapse chevron — handles itself, and+ // this capture listener fires before its own click does. Leave it alone or+ // the two toggles cancel out.+ if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {+ return;+ }+ if (node.hasAttribute("data-diffs-header")) {+ const filePath = node.querySelector("[data-title]")?.textContent?.trim();+ if (filePath === undefined || filePath === "") return;+ const item = items.find(+ (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,+ );+ if (item !== undefined) toggleFile(item.id);+ return;+ }}- }- }}- >- {/* The viewer virtualizes against the element it is told is scrolling and places its+ }}+ >+ {/* The viewer virtualizes against the element it is told is scrolling and places itsrows absolutely, so it has to own that element — the thread diff panel hands it thesame one. Scrolling from a parent instead leaves it painting over its neighbours. */}- <StyledDiffCodeView<ReviewAnnotationGroup>- // Keep scrollbar space stable so file metadata and line numbers do not shift as a- // diff crosses the overflow boundary. The viewer is itself focusable for keyboard- // interaction, but its native host outline clips and competes with the focus- // indicators on its actual controls.- className="h-full overflow-auto [scrollbar-gutter:stable]"- items={items}- selectedLines={selectedLines}- onSelectedLinesChange={setSelectedLines}- options={diffViewOptions}- // The viewer owns the scroll container, so the sentinel that asks for the next slice- // has to live inside it — at the end of the files, where reaching it means the reader- // is running out of diff.- renderCodeViewFooter={renderCodeViewFooter}- renderHeaderPrefix={renderHeaderPrefix}- renderHeaderMetadata={renderHeaderMetadata}- renderAnnotation={renderAnnotation}- unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}- />- {reviewOverlay}+ <StyledDiffCodeView<ReviewAnnotationGroup>+ // Keep scrollbar space stable so file metadata and line numbers do not shift as a+ // diff crosses the overflow boundary. The viewer is itself focusable for keyboard+ // interaction, but its native host outline clips and competes with the focus+ // indicators on its actual controls.+ className="h-full overflow-auto [scrollbar-gutter:stable]"+ viewerRef={viewerRef}+ items={items}+ selectedLines={selectedLines}+ onSelectedLinesChange={setSelectedLines}+ options={diffViewOptions}+ // The viewer owns the scroll container, so the sentinel that asks for the next slice+ // has to live inside it — at the end of the files, where reaching it means the reader+ // is running out of diff.+ renderCodeViewFooter={renderCodeViewFooter}+ renderHeaderPrefix={renderHeaderPrefix}+ renderHeaderMetadata={renderHeaderMetadata}+ renderAnnotation={renderAnnotation}+ unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}+ />+ {reviewOverlay}+ </div>+ {fileTreeOpen ? (+ <aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">+ <DiffFileTree+ ariaLabel={`Pull request #${detail.number} files`}+ entries={fileTreeEntries}+ onSelectFile={revealFile}+ // The tree lists only what has arrived; a footer says so while the diff is still+ // paging, and lets the reader pull the rest in without scrolling for it.+ footer={+ nextCursor === null ? null : (+ <div className="shrink-0 border-t border-border/60 p-2">+ <Button+ type="button"+ size="xs"+ variant="outline"+ className="w-full"+ disabled={diffQuery.isPending}+ onClick={+ diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice+ }+ >+ {diffQuery.error !== null+ ? "Retry"+ : diffQuery.isPending+ ? "Loading more files..."+ : "Load more files"}+ </Button>+ </div>+ )+ }+ />+ </aside>+ ) : null}</div>{unstructured}</div>diff --git a/apps/web/src/pierre-tree-theme.ts b/apps/web/src/pierre-tree-theme.tsnew file mode 100644index 00000000000..1c7bd7f2d53--- /dev/null+++ b/apps/web/src/pierre-tree-theme.ts@@ -0,0 +1,22 @@+import type { CSSProperties } from "react";++/** Shadow-root overrides that make a Pierre file tree read as part of the app chrome. */+export const PIERRE_TREE_UNSAFE_CSS = `+ :host {+ --trees-bg-override: transparent;+ --trees-selected-bg-override: color-mix(in srgb, currentColor 12%, transparent);+ --trees-hover-bg-override: color-mix(in srgb, currentColor 7%, transparent);+ --trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);+ --trees-font-family-override: var(--font-sans);+ --trees-font-size-override: 12px;+ }+ button[data-type='item'] { border-radius: 5px; }+`;++/** Host styles that keep a Pierre tree on the active color scheme and foreground. */+export function pierreTreeStyle(colorScheme: "light" | "dark"): CSSProperties {+ return {+ colorScheme,+ ["--trees-fg-override" as string]: "var(--contrast-foreground)",+ };+}diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex 10d1995fa66..937cf91c903 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -56,6 +56,9 @@ T3 Code works with the platforms your team already uses:brought in from the base branch- While working in a thread, open linked reviews in the same compact right-panel tabs withoutleaving the conversation+- Show a file tree next to a review's **Code** tab, or a thread's **Diff** panel, to browse the+ changed files as folders and jump straight to any of them. The toolbar toggle remembers your+ choice.- Enable **Settings → General → Proactive panels** to open a newly linked review automatically andswitch to the completed turn's diff when agent work finishes- Open the review directly in your browser with one click