@devries-cameron20 / t3code Mirror · read-only / commits / 207e7e89d1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 01:45 UTC

fix(web): keep colliding diff paths readable and selectable (#18133)

Co-authored-by: macodev00 <macodev00@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

maco committed Oct 19, 2026 at 22:26 UTC 207e7e89d18298e54cf56f2de44879e7de61fc51
3 files changed +238 -45
apps/web/src/components/diffs/DiffFileTree.browser.test.tsx
+138 -10
@@ -42,9 +42,11 @@ describe("diff tree file activation", () => {
42 function Panel({
43 files = entries,
44 selectedPath = null,
45 + revealRequestId = 0,
46 }: {
47 files?: DiffFileTreeEntry[];
48 selectedPath?: string | null;
49 + revealRequestId?: number;
50 }) {
51 const reveal = useCodeViewFileReveal(viewer, "working-tree");
52 return (
@@ -52,6 +54,7 @@ describe("diff tree file activation", () => {
54 entries={files}
55 ariaLabel="Working tree files"
56 selectedPath={selectedPath}
57 + revealRequestId={revealRequestId}
58 onSelectFile={(path) => reveal(`${path}\0${path}`)}
59 />
60 );
@@ -73,9 +76,18 @@ describe("diff tree file activation", () => {
76 return element!;
77 }
78
76 - async function activate(path: string, modifiers: MouseEventInit = {}) {
79 + function fileRows(): HTMLElement[] {
80 + const host = container.querySelector("file-tree-container");
81 + return [
82 + ...(host?.shadowRoot ?? container).querySelectorAll<HTMLElement>(
83 + '[role="treeitem"][data-item-type="file"]',
84 + ),
85 + ];
86 + }
87 +
88 + async function activate(target: string | HTMLElement, modifiers: MouseEventInit = {}) {
89 await act(async () => {
78 - row(path).dispatchEvent(
90 + (typeof target === "string" ? row(target) : target).dispatchEvent(
91 new MouseEvent("click", {
92 bubbles: true,
93 composed: true,
@@ -99,6 +111,7 @@ describe("diff tree file activation", () => {
111 await act(async () => root?.unmount());
112 root = undefined;
113 container.remove();
114 + vi.restoreAllMocks();
115 vi.unstubAllGlobals();
116 });
117
@@ -200,16 +213,131 @@ describe("diff tree file activation", () => {
213 expect(folder.isExpanded()).toBe(false);
214 });
215
203 - it("does not echo controlled selection, but lets the reader activate it", async () => {
204 - await mount({ selectedPath: "02-short.ts" });
205 - expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
216 + it("reveals real diff paths and statuses when a directory is replaced by a file", async () => {
217 + const files: DiffFileTreeEntry[] = [
218 + { path: "office/config.ts", status: "deleted" },
219 + { path: "office", status: "added" },
220 + ];
221 + await mount({ files, selectedPath: "office" });
222 + expect(fileRows().map((row) => row.getAttribute("data-item-git-status"))).toEqual([
223 + "deleted",
224 + "added",
225 + ]);
226 + expect(fileRows()[1]!.getAttribute("aria-selected")).toBe("true");
227 expect(targets).toEqual([]);
207 - await activate("02-short.ts");
208 - expect(targets).toHaveLength(1);
209 - await act(async () => {
210 - root!.render(<Panel selectedPath="03-medium.ts" />);
228 + await activate(fileRows()[1]!);
229 + await activate(fileRows()[0]!);
230 + await activate("office/");
231 + expect(targets).toEqual([
232 + { type: "item", id: "office\0office", align: "start" },
233 + { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },
234 + ]);
235 + expect(row("office/").getAttribute("aria-expanded")).toBe("false");
236 + await mount({ files, selectedPath: "office/config.ts" });
237 + expect(row("office/").getAttribute("aria-expanded")).toBe("true");
238 + expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");
239 + expect(targets).toHaveLength(2);
240 + });
241 +
242 + it("keeps selection, focus, and collapsed folders through a colliding slice and refresh", async () => {
243 + const files: DiffFileTreeEntry[] = [
244 + { path: "office", status: "deleted" },
245 + { path: "src/route.ts", status: "modified" },
246 + ];
247 + await mount({ files });
248 + await activate("src/");
249 + await activate("office");
250 + await act(async () => model().focusPath("office"));
251 + expect(model().getFocusedPath()).toBe("office");
252 + expect(row("office").getAttribute("aria-selected")).toBe("true");
253 + const appended: DiffFileTreeEntry[] = [...files, { path: "office/config.ts", status: "added" }];
254 + await mount({ files: appended });
255 + expect(row("src/").getAttribute("aria-expanded")).toBe("false");
256 + expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");
257 + expect(row("office/").getAttribute("aria-selected")).toBe("false");
258 + expect.soft(model().getFocusedPath()).toBe("office\u200b");
259 + expect(targets).toEqual([{ type: "item", id: "office\0office", align: "start" }]);
260 + await activate(fileRows()[0]!);
261 + await activate(fileRows()[1]!);
262 + expect(targets).toEqual([
263 + { type: "item", id: "office\0office", align: "start" },
264 + { type: "item", id: "office\0office", align: "start" },
265 + { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },
266 + ]);
267 + await activate("office/");
268 + await mount({ files: appended.map((file) => ({ ...file })) });
269 + expect(row("src/").getAttribute("aria-expanded")).toBe("false");
270 + expect(row("office/").getAttribute("aria-expanded")).toBe("false");
271 + await activate(fileRows()[0]!);
272 + expect(targets.at(-1)).toEqual({ type: "item", id: "office\0office", align: "start" });
273 + expect(targets).toHaveLength(4);
274 + });
275 +
276 + it("preserves filename and extension icons when files become directory prefixes", async () => {
277 + const files: DiffFileTreeEntry[] = [
278 + { path: "AGENTS.md", status: "deleted" },
279 + { path: "config.ts", status: "deleted" },
280 + ];
281 + const rootFileIcons = () =>
282 + fileRows()
283 + .filter((row) => row.getAttribute("aria-level") === "1")
284 + .map((row) => row.querySelector('[data-item-section="icon"] use')?.getAttribute("href"));
285 + await mount({ files });
286 + const icons = rootFileIcons();
287 + expect(icons).toEqual(["#t3-file-icon-agents", "#file-tree-builtin-typescript"]);
288 + await mount({
289 + files: [
290 + ...files,
291 + { path: "AGENTS.md/note.txt", status: "added" },
292 + { path: "config.ts/note.txt", status: "added" },
293 + ],
294 });
212 - expect(model().getSelectedPaths()).toEqual(["03-medium.ts"]);
295 + expect(rootFileIcons()).toEqual(icons);
296 + });
297 +
298 + it("preserves a collapsed controlled selection through paging until explicitly revealed", async () => {
299 + const files: DiffFileTreeEntry[] = [
300 + { path: "src/office", status: "deleted" },
301 + { path: "src/route.ts", status: "modified" },
302 + ];
303 + await mount({ files, selectedPath: "src/office" });
304 + expect(model().getSelectedPaths()).toEqual(["src/office"]);
305 + expect(targets).toEqual([]);
306 + await activate("src/office");
307 + expect(targets).toEqual([{ type: "item", id: "src/office\0src/office", align: "start" }]);
308 +
309 + const folder = model().getItem("src/")!;
310 + if (!("collapse" in folder)) throw new Error("Expected the directory handle");
311 + await act(async () => folder.collapse());
312 + expect(row("src/").getAttribute("aria-expanded")).toBe("false");
313 + const scroll = vi.spyOn(model(), "scrollToPath");
314 + const appended: DiffFileTreeEntry[] = [...files, { path: "src/office/x.ts", status: "added" }];
315 + await mount({ files: appended, selectedPath: "src/office" });
316 + expect.soft(row("src/").getAttribute("aria-expanded")).toBe("false");
317 + expect.soft(scroll).not.toHaveBeenCalled();
318 + const selected = model().getSelectedPaths();
319 + expect(selected).toHaveLength(1);
320 + expect(model().getItem(selected[0]!)?.isDirectory()).toBe(false);
321 expect(targets).toHaveLength(1);
322 +
323 + await act(async () => folder.collapse());
324 + scroll.mockClear();
325 + await mount({ files: appended, selectedPath: "src/office", revealRequestId: 1 });
326 + expect(row("src/").getAttribute("aria-expanded")).toBe("true");
327 + expect(model().getSelectedPaths()).toEqual(selected);
328 + expect(row(selected[0]!).getAttribute("aria-selected")).toBe("true");
329 + expect(scroll).toHaveBeenCalledOnce();
330 + expect(targets).toHaveLength(1);
331 + await activate(selected[0]!);
332 + expect(targets).toEqual([
333 + { type: "item", id: "src/office\0src/office", align: "start" },
334 + { type: "item", id: "src/office\0src/office", align: "start" },
335 + ]);
336 +
337 + await act(async () => folder.collapse());
338 + await mount({ files: appended, selectedPath: "src/route.ts", revealRequestId: 1 });
339 + expect(row("src/").getAttribute("aria-expanded")).toBe("true");
340 + expect(model().getSelectedPaths()).toEqual(["src/route.ts"]);
341 + expect(targets).toHaveLength(2);
342 });
343 });
apps/web/src/components/diffs/DiffFileTree.tsx
+62 -34
@@ -6,7 +6,6 @@ import { useEffect, useRef, useState, type ReactNode } from "react";
6 import { useStableCallback } from "~/hooks/useStableCallback";
7 import { useTheme } from "~/hooks/useTheme";
8 import { cn } from "~/lib/utils";
9 -import { T3_PIERRE_ICONS } from "~/pierre-icons";
9 import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
10
11 import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "../files/fileTreeExpansion";
@@ -17,6 +16,7 @@ import {
16 buildDiffFileTreeUpdates,
17 compareDiffFileTreeEntries,
18 collectDirectoryPaths,
19 + diffFileTreeModel,
20 diffFileTreePositions,
21 type DiffFileTreeEntry,
22 } from "./diffFileTree.logic";
@@ -46,8 +46,11 @@ export function DiffFileTree({
46 }: DiffFileTreeProps) {
47 const { resolvedTheme } = useTheme();
48 const paths = entries.map((entry) => entry.path);
49 - const directoryPaths = collectDirectoryPaths(paths);
50 - const positions = diffFileTreePositions(paths);
49 + const presented = diffFileTreeModel(paths);
50 + const modelPaths = presented.paths;
51 + const icons = presented.icons;
52 + const directoryPaths = collectDirectoryPaths(modelPaths);
53 + const positions = diffFileTreePositions(modelPaths);
54 const [ordering] = useState(() => {
55 let currentPositions: ReadonlyMap<string, number> = new Map();
56 return {
@@ -58,25 +61,30 @@ export function DiffFileTree({
61 };
62 });
63 const gitStatus: ReadonlyArray<GitStatusEntry> = entries.map((entry) => ({
61 - path: entry.path,
64 + path: presented.modelPath(entry.path),
65 status: entry.status,
66 }));
67 const syncingSelectionRef = useRef(false);
65 - const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);
66 - const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);
68 + const handledRevealRef = useRef<{
69 + path: string;
70 + revealRequestId: number;
71 + } | null>(null);
72 + const mountedPresentationRef = useRef<ReturnType<typeof diffFileTreeModel> | null>(null);
73
74 // The tree model keeps the first selection handler it was given.
75 const handleSelectionChange = useStableCallback((selectedPaths: ReadonlyArray<string>) => {
76 if (syncingSelectionRef.current) return;
71 - const path = selectedPaths.at(-1)?.replace(/\/$/, "");
72 - if (path && paths.includes(path)) onSelectFile(path);
77 + const modelPath = selectedPaths.at(-1);
78 + if (modelPath && modelPaths.includes(modelPath)) {
79 + onSelectFile(presented.selectionPath(modelPath));
80 + }
81 });
82
83 const { model } = useFileTree({
84 density: "compact",
85 flattenEmptyDirectories: true,
86 initialExpansion: "open",
79 - icons: T3_PIERRE_ICONS,
87 + icons,
88 onSelectionChange: handleSelectionChange,
89 paths: [],
90 search: false,
@@ -87,67 +95,87 @@ export function DiffFileTree({
95 areAllDirectoriesExpanded(currentModel, directoryPaths),
96 );
97
98 + useEffect(() => {
99 + model.setIcons(icons);
100 + }, [icons, model]);
101 +
102 useEffect(() => {
103 ordering.update(positions);
92 - const mountedPaths = mountedPathsRef.current;
93 - if (mountedPaths === paths) return;
94 - mountedPathsRef.current = paths;
95 - if (mountedPaths === null) {
96 - model.resetPaths(paths);
97 - } else if (mountedPaths.every((path, index) => paths[index] === path)) {
98 - const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
104 + const mounted = mountedPresentationRef.current;
105 + if (mounted?.paths === modelPaths) return;
106 + mountedPresentationRef.current = presented;
107 + if (mounted === null) {
108 + model.resetPaths(modelPaths);
109 + } else if (mounted.paths.every((path, index) => modelPaths[index] === path)) {
110 + const updates = buildDiffFileTreeUpdates(mounted.paths, modelPaths);
111 if (updates.length > 0) model.batch(updates);
112 } else {
101 - // A refreshed diff can change the rank of existing siblings. Mutations do not reorder
102 - // those rows, so rebuild while carrying the reader's folder expansion forward.
113 + // A reset can turn a file path into a directory. Carry selection and focus
114 + // through real paths so paging keeps the same file without revealing it again.
115 + const focusedPath = model.getFocusedPath();
116 + const nextFocusedPath =
117 + focusedPath === null ? null : presented.modelPath(mounted.selectionPath(focusedPath));
118 + const selectedPaths = model
119 + .getSelectedPaths()
120 + .map((path) => presented.modelPath(mounted.selectionPath(path)))
121 + .filter((path) => path.endsWith("/") || modelPaths.includes(path));
122 const collapsedDirectories = directoryPaths.filter((path) => {
123 const directory = model.getItem(path);
124 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
125 });
107 - model.resetPaths(paths);
126 + syncingSelectionRef.current = true;
127 + model.resetPaths(modelPaths);
128 + for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect();
129 + for (const path of selectedPaths) model.getItem(path)?.select();
130 + queueMicrotask(() => {
131 + syncingSelectionRef.current = false;
132 + });
133 for (const path of collapsedDirectories) {
134 const directory = model.getItem(path);
135 if (directory !== null && "collapse" in directory) directory.collapse();
136 }
137 + if (
138 + nextFocusedPath !== null &&
139 + (modelPaths.includes(nextFocusedPath) || directoryPaths.includes(nextFocusedPath))
140 + ) {
141 + model.focusPath(nextFocusedPath);
142 + }
143 }
144 model.setGitStatus(gitStatus);
114 - }, [directoryPaths, gitStatus, model, ordering, paths, positions]);
145 + }, [directoryPaths, gitStatus, model, modelPaths, ordering, positions, presented]);
146
147 useEffect(() => {
148 if (selectedPath === null) {
149 handledRevealRef.current = null;
150 return;
151 }
121 - const item = model.getItem(selectedPath);
152 + const modelPath = presented.modelPath(selectedPath);
153 + const item = model.getItem(modelPath);
154 if (item === null || item.isDirectory()) {
155 handledRevealRef.current = null;
156 return;
157 }
158 const handled = handledRevealRef.current;
127 - if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
159 + if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) {
160 + return;
161 + }
162 handledRevealRef.current = { path: selectedPath, revealRequestId };
163 syncingSelectionRef.current = true;
164 for (const path of model.getSelectedPaths()) {
131 - if (path !== selectedPath) model.getItem(path)?.deselect();
165 + if (path !== modelPath) model.getItem(path)?.deselect();
166 }
167 let ancestor = "";
134 - for (const segment of selectedPath.split("/").slice(0, -1)) {
168 + for (const segment of modelPath.split("/").slice(0, -1)) {
169 ancestor += `${segment}/`;
170 const directory = model.getItem(ancestor);
171 if (directory !== null && "expand" in directory) directory.expand();
172 }
173 item.select();
140 - model.scrollToPath(selectedPath, { offset: "nearest" });
174 + model.scrollToPath(modelPath, { offset: "nearest" });
175 queueMicrotask(() => {
176 syncingSelectionRef.current = false;
177 });
144 - }, [
145 - model,
146 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A file that arrives after it was asked for is still revealed.
147 - paths,
148 - revealRequestId,
149 - selectedPath,
150 - ]);
178 + }, [model, presented, revealRequestId, selectedPath]);
179
180 return (
181 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
@@ -204,13 +232,13 @@ export function DiffFileTree({
232 // Read selection before the row handles the click so new selections reveal only once.
233 const selected = model.getSelectedPaths();
234 const path = selected.length === 1 ? selected[0] : undefined;
207 - if (!path || !paths.includes(path)) return;
235 + if (!path || !modelPaths.includes(path)) return;
236 const clickedSelectedRow = event.nativeEvent
237 .composedPath()
238 .some(
239 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
240 );
213 - if (clickedSelectedRow) onSelectFile(path);
241 + if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));
242 }}
243 className="min-h-0 flex-1 overflow-hidden"
244 style={pierreTreeStyle(resolvedTheme)}
apps/web/src/components/diffs/diffFileTree.logic.ts
+38 -1
@@ -1,7 +1,13 @@
1 import type { FileDiffMetadata } from "@pierre/diffs";
2 -import type { FileTreeBatchOperation, FileTreeSortComparator, GitStatus } from "@pierre/trees";
2 +import type {
3 + FileTreeBatchOperation,
4 + FileTreeIconConfig,
5 + FileTreeSortComparator,
6 + GitStatus,
7 +} from "@pierre/trees";
8
9 import { resolveFileDiffPath } from "~/lib/diffRendering";
10 +import { basenameOfPath, resolvePierreIconForEntry, T3_PIERRE_ICONS } from "~/pierre-icons";
11
12 export interface DiffFileTreeEntry {
13 readonly path: string;
@@ -35,6 +41,37 @@ export function diffFileTreeEntries(
41 return [...statusByPath].map(([path, status]) => ({ path, status }));
42 }
43
44 +// Pierre cannot store a file and a directory at the same path. Give only those
45 +// files an invisible suffix, keeping real paths at the diff/viewer boundary.
46 +export function diffFileTreeModel(paths: ReadonlyArray<string>) {
47 + const directories = new Set(collectDirectoryPaths(paths));
48 + // Icon overrides match basenames case-insensitively, so aliases must also avoid
49 + // real names in other directories, including names that already contain the suffix.
50 + const occupiedNames = new Set(paths.flatMap((path) => path.toLowerCase().split("/")));
51 + const selectionByModelPath = new Map<string, string>();
52 + const modelBySelectionPath = new Map<string, string>();
53 + const byFileName: FileTreeIconConfig["byFileName"] = { ...T3_PIERRE_ICONS.byFileName };
54 + const modelPaths = paths.map((path) => {
55 + if (!directories.has(`${path}/`)) return path;
56 + let modelPath = path;
57 + do {
58 + modelPath += "\u200b";
59 + } while (occupiedNames.has(basenameOfPath(modelPath).toLowerCase()));
60 + occupiedNames.add(basenameOfPath(modelPath).toLowerCase());
61 + selectionByModelPath.set(modelPath, path);
62 + modelBySelectionPath.set(path, modelPath);
63 + const icon = resolvePierreIconForEntry(path, "file");
64 + if (icon !== null) byFileName[basenameOfPath(modelPath)] = icon;
65 + return modelPath;
66 + });
67 + return {
68 + paths: modelBySelectionPath.size === 0 ? paths : modelPaths,
69 + selectionPath: (modelPath: string) => selectionByModelPath.get(modelPath) ?? modelPath,
70 + modelPath: (path: string) => modelBySelectionPath.get(path) ?? path,
71 + icons: modelBySelectionPath.size === 0 ? T3_PIERRE_ICONS : { ...T3_PIERRE_ICONS, byFileName },
72 + };
73 +}
74 +
75 export function collectDirectoryPaths(paths: ReadonlyArray<string>): ReadonlyArray<string> {
76 const directories = new Set<string>();
77 for (const path of paths) {