TypeScript
fix(web): keep colliding diff paths readable and selectable (#18133)
maco207e7e89d182
diff --git a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsxindex 1e5814cef2e..e3ab74f2d51 100644--- a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx+++ b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx@@ -42,9 +42,11 @@ describe("diff tree file activation", () => {function Panel({files = entries,selectedPath = null,+ revealRequestId = 0,}: {files?: DiffFileTreeEntry[];selectedPath?: string | null;+ revealRequestId?: number;}) {const reveal = useCodeViewFileReveal(viewer, "working-tree");return (@@ -52,6 +54,7 @@ describe("diff tree file activation", () => {entries={files}ariaLabel="Working tree files"selectedPath={selectedPath}+ revealRequestId={revealRequestId}onSelectFile={(path) => reveal(`${path}\0${path}`)}/>);@@ -73,9 +76,18 @@ describe("diff tree file activation", () => {return element!;}- async function activate(path: string, modifiers: MouseEventInit = {}) {+ function fileRows(): HTMLElement[] {+ const host = container.querySelector("file-tree-container");+ return [+ ...(host?.shadowRoot ?? container).querySelectorAll<HTMLElement>(+ '[role="treeitem"][data-item-type="file"]',+ ),+ ];+ }++ async function activate(target: string | HTMLElement, modifiers: MouseEventInit = {}) {await act(async () => {- row(path).dispatchEvent(+ (typeof target === "string" ? row(target) : target).dispatchEvent(new MouseEvent("click", {bubbles: true,composed: true,@@ -99,6 +111,7 @@ describe("diff tree file activation", () => {await act(async () => root?.unmount());root = undefined;container.remove();+ vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -200,16 +213,131 @@ describe("diff tree file activation", () => {expect(folder.isExpanded()).toBe(false);});- it("does not echo controlled selection, but lets the reader activate it", async () => {- await mount({ selectedPath: "02-short.ts" });- expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);+ it("reveals real diff paths and statuses when a directory is replaced by a file", async () => {+ const files: DiffFileTreeEntry[] = [+ { path: "office/config.ts", status: "deleted" },+ { path: "office", status: "added" },+ ];+ await mount({ files, selectedPath: "office" });+ expect(fileRows().map((row) => row.getAttribute("data-item-git-status"))).toEqual([+ "deleted",+ "added",+ ]);+ expect(fileRows()[1]!.getAttribute("aria-selected")).toBe("true");expect(targets).toEqual([]);- await activate("02-short.ts");- expect(targets).toHaveLength(1);- await act(async () => {- root!.render(<Panel selectedPath="03-medium.ts" />);+ await activate(fileRows()[1]!);+ await activate(fileRows()[0]!);+ await activate("office/");+ expect(targets).toEqual([+ { type: "item", id: "office\0office", align: "start" },+ { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },+ ]);+ expect(row("office/").getAttribute("aria-expanded")).toBe("false");+ await mount({ files, selectedPath: "office/config.ts" });+ expect(row("office/").getAttribute("aria-expanded")).toBe("true");+ expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");+ expect(targets).toHaveLength(2);+ });++ it("keeps selection, focus, and collapsed folders through a colliding slice and refresh", async () => {+ const files: DiffFileTreeEntry[] = [+ { path: "office", status: "deleted" },+ { path: "src/route.ts", status: "modified" },+ ];+ await mount({ files });+ await activate("src/");+ await activate("office");+ await act(async () => model().focusPath("office"));+ expect(model().getFocusedPath()).toBe("office");+ expect(row("office").getAttribute("aria-selected")).toBe("true");+ const appended: DiffFileTreeEntry[] = [...files, { path: "office/config.ts", status: "added" }];+ await mount({ files: appended });+ expect(row("src/").getAttribute("aria-expanded")).toBe("false");+ expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");+ expect(row("office/").getAttribute("aria-selected")).toBe("false");+ expect.soft(model().getFocusedPath()).toBe("office\u200b");+ expect(targets).toEqual([{ type: "item", id: "office\0office", align: "start" }]);+ await activate(fileRows()[0]!);+ await activate(fileRows()[1]!);+ expect(targets).toEqual([+ { type: "item", id: "office\0office", align: "start" },+ { type: "item", id: "office\0office", align: "start" },+ { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },+ ]);+ await activate("office/");+ await mount({ files: appended.map((file) => ({ ...file })) });+ expect(row("src/").getAttribute("aria-expanded")).toBe("false");+ expect(row("office/").getAttribute("aria-expanded")).toBe("false");+ await activate(fileRows()[0]!);+ expect(targets.at(-1)).toEqual({ type: "item", id: "office\0office", align: "start" });+ expect(targets).toHaveLength(4);+ });++ it("preserves filename and extension icons when files become directory prefixes", async () => {+ const files: DiffFileTreeEntry[] = [+ { path: "AGENTS.md", status: "deleted" },+ { path: "config.ts", status: "deleted" },+ ];+ const rootFileIcons = () =>+ fileRows()+ .filter((row) => row.getAttribute("aria-level") === "1")+ .map((row) => row.querySelector('[data-item-section="icon"] use')?.getAttribute("href"));+ await mount({ files });+ const icons = rootFileIcons();+ expect(icons).toEqual(["#t3-file-icon-agents", "#file-tree-builtin-typescript"]);+ await mount({+ files: [+ ...files,+ { path: "AGENTS.md/note.txt", status: "added" },+ { path: "config.ts/note.txt", status: "added" },+ ],});- expect(model().getSelectedPaths()).toEqual(["03-medium.ts"]);+ expect(rootFileIcons()).toEqual(icons);+ });++ it("preserves a collapsed controlled selection through paging until explicitly revealed", async () => {+ const files: DiffFileTreeEntry[] = [+ { path: "src/office", status: "deleted" },+ { path: "src/route.ts", status: "modified" },+ ];+ await mount({ files, selectedPath: "src/office" });+ expect(model().getSelectedPaths()).toEqual(["src/office"]);+ expect(targets).toEqual([]);+ await activate("src/office");+ expect(targets).toEqual([{ type: "item", id: "src/office\0src/office", align: "start" }]);++ const folder = model().getItem("src/")!;+ if (!("collapse" in folder)) throw new Error("Expected the directory handle");+ await act(async () => folder.collapse());+ expect(row("src/").getAttribute("aria-expanded")).toBe("false");+ const scroll = vi.spyOn(model(), "scrollToPath");+ const appended: DiffFileTreeEntry[] = [...files, { path: "src/office/x.ts", status: "added" }];+ await mount({ files: appended, selectedPath: "src/office" });+ expect.soft(row("src/").getAttribute("aria-expanded")).toBe("false");+ expect.soft(scroll).not.toHaveBeenCalled();+ const selected = model().getSelectedPaths();+ expect(selected).toHaveLength(1);+ expect(model().getItem(selected[0]!)?.isDirectory()).toBe(false);expect(targets).toHaveLength(1);++ await act(async () => folder.collapse());+ scroll.mockClear();+ await mount({ files: appended, selectedPath: "src/office", revealRequestId: 1 });+ expect(row("src/").getAttribute("aria-expanded")).toBe("true");+ expect(model().getSelectedPaths()).toEqual(selected);+ expect(row(selected[0]!).getAttribute("aria-selected")).toBe("true");+ expect(scroll).toHaveBeenCalledOnce();+ expect(targets).toHaveLength(1);+ await activate(selected[0]!);+ expect(targets).toEqual([+ { type: "item", id: "src/office\0src/office", align: "start" },+ { type: "item", id: "src/office\0src/office", align: "start" },+ ]);++ await act(async () => folder.collapse());+ await mount({ files: appended, selectedPath: "src/route.ts", revealRequestId: 1 });+ expect(row("src/").getAttribute("aria-expanded")).toBe("true");+ expect(model().getSelectedPaths()).toEqual(["src/route.ts"]);+ expect(targets).toHaveLength(2);});});diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsxindex 59b49647dbe..cda48198c79 100644--- a/apps/web/src/components/diffs/DiffFileTree.tsx+++ b/apps/web/src/components/diffs/DiffFileTree.tsx@@ -6,7 +6,6 @@ import { useEffect, useRef, useState, type ReactNode } from "react";import { useStableCallback } from "~/hooks/useStableCallback";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";@@ -17,6 +16,7 @@ import {buildDiffFileTreeUpdates,compareDiffFileTreeEntries,collectDirectoryPaths,+ diffFileTreeModel,diffFileTreePositions,type DiffFileTreeEntry,} from "./diffFileTree.logic";@@ -46,8 +46,11 @@ export function DiffFileTree({}: DiffFileTreeProps) {const { resolvedTheme } = useTheme();const paths = entries.map((entry) => entry.path);- const directoryPaths = collectDirectoryPaths(paths);- const positions = diffFileTreePositions(paths);+ const presented = diffFileTreeModel(paths);+ const modelPaths = presented.paths;+ const icons = presented.icons;+ const directoryPaths = collectDirectoryPaths(modelPaths);+ const positions = diffFileTreePositions(modelPaths);const [ordering] = useState(() => {let currentPositions: ReadonlyMap<string, number> = new Map();return {@@ -58,25 +61,30 @@ export function DiffFileTree({};});const gitStatus: ReadonlyArray<GitStatusEntry> = entries.map((entry) => ({- path: entry.path,+ path: presented.modelPath(entry.path),status: entry.status,}));const syncingSelectionRef = useRef(false);- const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);- const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);+ const handledRevealRef = useRef<{+ path: string;+ revealRequestId: number;+ } | null>(null);+ const mountedPresentationRef = useRef<ReturnType<typeof diffFileTreeModel> | null>(null);// The tree model keeps the first selection handler it was given.const handleSelectionChange = useStableCallback((selectedPaths: ReadonlyArray<string>) => {if (syncingSelectionRef.current) return;- const path = selectedPaths.at(-1)?.replace(/\/$/, "");- if (path && paths.includes(path)) onSelectFile(path);+ const modelPath = selectedPaths.at(-1);+ if (modelPath && modelPaths.includes(modelPath)) {+ onSelectFile(presented.selectionPath(modelPath));+ }});const { model } = useFileTree({density: "compact",flattenEmptyDirectories: true,initialExpansion: "open",- icons: T3_PIERRE_ICONS,+ icons,onSelectionChange: handleSelectionChange,paths: [],search: false,@@ -87,67 +95,87 @@ export function DiffFileTree({areAllDirectoriesExpanded(currentModel, directoryPaths),);+ useEffect(() => {+ model.setIcons(icons);+ }, [icons, model]);+useEffect(() => {ordering.update(positions);- const mountedPaths = mountedPathsRef.current;- if (mountedPaths === paths) return;- mountedPathsRef.current = paths;- if (mountedPaths === null) {- model.resetPaths(paths);- } else if (mountedPaths.every((path, index) => paths[index] === path)) {- const updates = buildDiffFileTreeUpdates(mountedPaths, paths);+ const mounted = mountedPresentationRef.current;+ if (mounted?.paths === modelPaths) return;+ mountedPresentationRef.current = presented;+ if (mounted === null) {+ model.resetPaths(modelPaths);+ } else if (mounted.paths.every((path, index) => modelPaths[index] === path)) {+ const updates = buildDiffFileTreeUpdates(mounted.paths, modelPaths);if (updates.length > 0) model.batch(updates);} else {- // A refreshed diff can change the rank of existing siblings. Mutations do not reorder- // those rows, so rebuild while carrying the reader's folder expansion forward.+ // A reset can turn a file path into a directory. Carry selection and focus+ // through real paths so paging keeps the same file without revealing it again.+ const focusedPath = model.getFocusedPath();+ const nextFocusedPath =+ focusedPath === null ? null : presented.modelPath(mounted.selectionPath(focusedPath));+ const selectedPaths = model+ .getSelectedPaths()+ .map((path) => presented.modelPath(mounted.selectionPath(path)))+ .filter((path) => path.endsWith("/") || modelPaths.includes(path));const collapsedDirectories = directoryPaths.filter((path) => {const directory = model.getItem(path);return directory !== null && "isExpanded" in directory && !directory.isExpanded();});- model.resetPaths(paths);+ syncingSelectionRef.current = true;+ model.resetPaths(modelPaths);+ for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect();+ for (const path of selectedPaths) model.getItem(path)?.select();+ queueMicrotask(() => {+ syncingSelectionRef.current = false;+ });for (const path of collapsedDirectories) {const directory = model.getItem(path);if (directory !== null && "collapse" in directory) directory.collapse();}+ if (+ nextFocusedPath !== null &&+ (modelPaths.includes(nextFocusedPath) || directoryPaths.includes(nextFocusedPath))+ ) {+ model.focusPath(nextFocusedPath);+ }}model.setGitStatus(gitStatus);- }, [directoryPaths, gitStatus, model, ordering, paths, positions]);+ }, [directoryPaths, gitStatus, model, modelPaths, ordering, positions, presented]);useEffect(() => {if (selectedPath === null) {handledRevealRef.current = null;return;}- const item = model.getItem(selectedPath);+ const modelPath = presented.modelPath(selectedPath);+ const item = model.getItem(modelPath);if (item === null || item.isDirectory()) {handledRevealRef.current = null;return;}const handled = handledRevealRef.current;- if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;+ 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();+ if (path !== modelPath) model.getItem(path)?.deselect();}let ancestor = "";- for (const segment of selectedPath.split("/").slice(0, -1)) {+ for (const segment of modelPath.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" });+ model.scrollToPath(modelPath, { offset: "nearest" });queueMicrotask(() => {syncingSelectionRef.current = false;});- }, [- model,- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A file that arrives after it was asked for is still revealed.- paths,- revealRequestId,- selectedPath,- ]);+ }, [model, presented, revealRequestId, selectedPath]);return (<div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>@@ -204,13 +232,13 @@ export function DiffFileTree({// Read selection before the row handles the click so new selections reveal only once.const selected = model.getSelectedPaths();const path = selected.length === 1 ? selected[0] : undefined;- if (!path || !paths.includes(path)) return;+ if (!path || !modelPaths.includes(path)) return;const clickedSelectedRow = event.nativeEvent.composedPath().some((node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,);- if (clickedSelectedRow) onSelectFile(path);+ if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));}}className="min-h-0 flex-1 overflow-hidden"style={pierreTreeStyle(resolvedTheme)}diff --git a/apps/web/src/components/diffs/diffFileTree.logic.ts b/apps/web/src/components/diffs/diffFileTree.logic.tsindex 61509a7bb3d..6d67f203d0f 100644--- a/apps/web/src/components/diffs/diffFileTree.logic.ts+++ b/apps/web/src/components/diffs/diffFileTree.logic.ts@@ -1,7 +1,13 @@import type { FileDiffMetadata } from "@pierre/diffs";-import type { FileTreeBatchOperation, FileTreeSortComparator, GitStatus } from "@pierre/trees";+import type {+ FileTreeBatchOperation,+ FileTreeIconConfig,+ FileTreeSortComparator,+ GitStatus,+} from "@pierre/trees";import { resolveFileDiffPath } from "~/lib/diffRendering";+import { basenameOfPath, resolvePierreIconForEntry, T3_PIERRE_ICONS } from "~/pierre-icons";export interface DiffFileTreeEntry {readonly path: string;@@ -35,6 +41,37 @@ export function diffFileTreeEntries(return [...statusByPath].map(([path, status]) => ({ path, status }));}+// Pierre cannot store a file and a directory at the same path. Give only those+// files an invisible suffix, keeping real paths at the diff/viewer boundary.+export function diffFileTreeModel(paths: ReadonlyArray<string>) {+ const directories = new Set(collectDirectoryPaths(paths));+ // Icon overrides match basenames case-insensitively, so aliases must also avoid+ // real names in other directories, including names that already contain the suffix.+ const occupiedNames = new Set(paths.flatMap((path) => path.toLowerCase().split("/")));+ const selectionByModelPath = new Map<string, string>();+ const modelBySelectionPath = new Map<string, string>();+ const byFileName: FileTreeIconConfig["byFileName"] = { ...T3_PIERRE_ICONS.byFileName };+ const modelPaths = paths.map((path) => {+ if (!directories.has(`${path}/`)) return path;+ let modelPath = path;+ do {+ modelPath += "\u200b";+ } while (occupiedNames.has(basenameOfPath(modelPath).toLowerCase()));+ occupiedNames.add(basenameOfPath(modelPath).toLowerCase());+ selectionByModelPath.set(modelPath, path);+ modelBySelectionPath.set(path, modelPath);+ const icon = resolvePierreIconForEntry(path, "file");+ if (icon !== null) byFileName[basenameOfPath(modelPath)] = icon;+ return modelPath;+ });+ return {+ paths: modelBySelectionPath.size === 0 ? paths : modelPaths,+ selectionPath: (modelPath: string) => selectionByModelPath.get(modelPath) ?? modelPath,+ modelPath: (path: string) => modelBySelectionPath.get(path) ?? path,+ icons: modelBySelectionPath.size === 0 ? T3_PIERRE_ICONS : { ...T3_PIERRE_ICONS, byFileName },+ };+}+export function collectDirectoryPaths(paths: ReadonlyArray<string>): ReadonlyArray<string> {const directories = new Set<string>();for (const path of paths) {