Files
kandev/apps/web/components/task/file-browser.tsx
T
José Almeida 2b8513f902 feat: add multi-select and drag-to-move for file tree and changes panel (#490)
* feat: add multi-select and drag-to-move for file tree and changes panel

Add Shift-click range and Ctrl/Cmd-click toggle selection to the file
tree and staged/unstaged changes sections. Includes bulk actions
(delete, stage, unstage, discard), drag-and-drop file moving into
directories, keyboard shortcuts (Escape, Ctrl+A), and E2E tests.

* fix: move bulk action components to file-row to fix max-lines lint

* style: apply prettier formatting to all changed files

* fix: bulk delete all selected items and update anchor on stale shift-click

* fix: address CodeRabbit review comments

- Keep original file-row-* data-testid for backwards compat
- Remove eager onClearSelection from bulk actions (auto-pruned by hook)
- Variant-scope bulk-discard/bulk-unstage test ids
- Remove index.lock deletion from E2E GitHelper retry loop

* fix: fix E2E tests — create files after session open, remove DnD test

- Create files AFTER opening session so WS detects git status changes
- Add proper git env vars (GIT_AUTHOR_NAME, etc.) matching existing tests
- Use element.press("Escape") instead of page keyboard for proper focus
- Remove drag-to-directory test (Playwright dragTo doesn't support HTML5
  dataTransfer events needed by our DnD implementation)

* fix: rename E2E task titles to avoid ambiguous 'Changes' tab selector

* fix: make file list focusable for Escape key handler in E2E tests

* fix: improve selection styling and ignore right-clicks in selection handler

- Use text-accent-foreground on selected rows for dark mode readability
- Override child span colors with [&_span]:text-accent-foreground
- Use hover:bg-accent/80 instead of hover:bg-muted on selected items
- Skip selection handling on right-click (button === 2) so context menu
  works without clearing multi-selection

* fix: plain click should not select — only Ctrl/Cmd+click and Shift+click

Plain click now clears any selection and performs the original action
(open file / toggle folder / open diff). Selection only happens with
modifier keys. handleClick returns boolean to indicate whether the
click was consumed by selection logic.

* fix: fix multi-select bugs and expand E2E test coverage

Bug fixes:
- Change isSelected from boolean to function prop so children compute
  their own selection state (fixes nested file selection)
- Inline TreeNodeRow JSX into TreeNodeItem so ContextMenuTrigger asChild
  can attach refs directly (fixes right-click context menu)
- Set lastClickedRef on plain click so shift-click has a valid anchor
- Add click-outside handler to clear selection

E2E tests expanded to 14 file-tree tests + 3 changes-panel tests:
- Ctrl-click select, toggle, multi-select
- Plain click clears selection
- Shift-click range after plain click and ctrl-click anchors
- Directory selection and nested file selection
- Right-click context menu (single + bulk delete)
- Click outside clears selection
- Escape clears selection

* fix: move AlertDialog outside ContextMenu to fix delete action

The AlertDialog wrapping the ContextMenu caused Radix focus management
to intercept context menu item selection, making Delete trigger Rename.
Moving AlertDialog to a sibling of ContextMenu fixes the conflict.

* fix: reorder context menu — Delete first, Rename second

Radix ContextMenu auto-focuses the first item on open, which caused
accidental Rename triggers. Putting Delete first (the more common
action for selection) avoids this.

* fix: don't clear selection when clicking context menu or dialog

The click-outside handler was clearing selection when clicking on
context menu items or confirmation dialog buttons (rendered in portals
outside the tree container). Now skips clearing for elements with
role=menu, role=alertdialog, or role=dialog.

Also extended the bulk delete E2E test to verify both files are
actually removed after confirming the dialog.

* fix: hide file count in delete dialog when folder children not loaded

When a folder hasn't been expanded, its children aren't loaded yet so
countFilesInTree returns 0. Instead of showing "0 files", hide the
count entirely and just show "delete <folder name>".

* fix: show confirmation dialog for bulk discard in changes panel

Bulk discard was calling git.discard() directly, bypassing the
confirmation dialog. Now routes through handleBulkDiscardClick which
opens the DiscardDialog with a bulk message ("discard changes to N
files") before executing.

* fix: address remaining CodeRabbit review comments

- Deduplicate filenames on move: when moving files with identical names
  to the same directory, append "(1)", "(2)" etc. to avoid collisions.
  Both tree update and rename API calls use the same deduplication.
- Replace void operator with .catch(() => {}) for bulk stage/unstage
  to prevent unhandled promise rejections.
- Add document-level dragend listener as safety net to clear stuck drag
  state if the element's onDragEnd doesn't fire (Escape, out-of-window).

* test: add unit tests for file tree move deduplication and visible paths

* fix: address all remaining PR review comments

- Move onSelectionChange out of React state updater (side effect fix)
- Stabilize keyboard listener deps (pass callbacks not object)
- Remove unnecessary useMemo in BulkActionBar
- Fix ghost-restore on partial bulk delete (remove all at once)
- Fix blank filename on single-file bulk discard
- Add aria-selected and role=treeitem for accessibility
- Extract computeNextSelection params into object (max-params lint)

* fix: add missing bulk action props to WorkingTreeProps type

WorkingTreeSections referenced onBulkStage, onBulkUnstage, and
onBulkDiscard but WorkingTreeProps Pick didn't include them, causing
a TypeScript build failure.

* fix: address final review comments

- Add unit tests for computeNextSelection (8 tests covering ctrl-click,
  shift-click range, stale anchor, reverse range, shift+ctrl extend)
- Extract shared E2E helpers (GitHelper, makeGitEnv, openTaskSession,
  createStandardProfile) to e2e/helpers/git-helper.ts
- Fix misleading comment in bulk delete (says "re-insert only failed"
  but implementation restores full snapshot)

* fix: use Promise.all for bulk delete to prevent partial rollback

Individual .catch() handlers could restore already-deleted files
if a later delete failed. Now uses Promise.all so rollback only
happens if any delete rejects.

* test: add renderHook tests for useMultiSelect hook behaviors

- Stale-path pruning: items shrink → selected paths auto-pruned
- Plain click: returns false, clears existing selection
- selectAll/clearSelection: work correctly, fire onSelectionChange
- Install @testing-library/react for renderHook support

* fix: handle false returns from onDeleteFile in bulk delete Promise.all

* chore: remove unused @testing-library/react-hooks dependency
2026-04-11 17:43:21 +01:00

473 lines
16 KiB
TypeScript

"use client";
import React, { useEffect, useMemo, useCallback, useRef, useState } from "react";
import { ScrollArea } from "@kandev/ui/scroll-area";
import type { FileTreeNode, OpenFileTab } from "@/lib/types/backend";
import { useSession } from "@/hooks/domains/session/use-session";
import { useRepository } from "@/hooks/domains/workspace/use-repository";
import { useSessionGitStatus } from "@/hooks/domains/session/use-session-git-status";
import { useOpenSessionFolder } from "@/hooks/use-open-session-folder";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import { useToast } from "@/components/toast-provider";
import { useMultiSelect } from "@/hooks/use-multi-select";
import { FileBrowserSearchHeader } from "./file-browser-search-header";
import {
insertNodeInTree,
removeNodeFromTree,
FileBrowserToolbar,
FileBrowserContentArea,
} from "./file-browser-parts";
import {
useFileBrowserSearch,
useFileBrowserTree,
useScrollPersistence,
loadNodeChildren,
fetchAndOpenFile,
} from "./file-browser-hooks";
import { getVisiblePaths, moveNodesInTree, computeMoveTargets } from "./file-tree-utils";
type FileBrowserHeaderProps = {
treeLoaded: boolean;
search: ReturnType<typeof useFileBrowserSearch>;
displayPath: string;
fullPath: string;
copied: boolean;
expandedPathsSize: number;
onCopyPath: (value: string) => void | Promise<void>;
onStartCreate?: () => void;
onOpenFolder: () => void;
onCollapseAll: () => void;
showCreateButton: boolean;
};
function FileBrowserHeader({
treeLoaded,
search,
displayPath,
fullPath,
copied,
expandedPathsSize,
onCopyPath,
onStartCreate,
onOpenFolder,
onCollapseAll,
showCreateButton,
}: FileBrowserHeaderProps) {
if (!treeLoaded) return null;
if (search.isSearchActive) {
return (
<FileBrowserSearchHeader
isSearching={search.isSearching}
localSearchQuery={search.localSearchQuery}
searchInputRef={search.searchInputRef}
onSearchChange={search.handleSearchChange}
onCloseSearch={search.handleCloseSearch}
/>
);
}
return (
<FileBrowserToolbar
displayPath={displayPath}
fullPath={fullPath}
copied={copied}
expandedPathsSize={expandedPathsSize}
onCopyPath={onCopyPath}
onStartCreate={onStartCreate}
onOpenFolder={onOpenFolder}
onStartSearch={() => search.setIsSearchActive(true)}
onCollapseAll={onCollapseAll}
showCreateButton={showCreateButton}
/>
);
}
type FileBrowserProps = {
sessionId: string;
environmentId?: string | null;
onOpenFile: (file: OpenFileTab) => void;
onCreateFile?: (path: string) => Promise<boolean>;
onDeleteFile?: (path: string) => Promise<boolean>;
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>;
activeFilePath?: string | null;
};
function useFileBrowserHandlers(
sessionId: string,
onOpenFile: (file: OpenFileTab) => void,
onCreateFile: FileBrowserProps["onCreateFile"],
treeState: ReturnType<typeof useFileBrowserTree>,
) {
const { toast } = useToast();
const [creatingInPath, setCreatingInPath] = useState<string | null>(null);
const [activeFolderPath, setActiveFolderPath] = useState<string>("");
const handleStartCreate = useCallback(() => {
if (activeFolderPath && !treeState.expandedPaths.has(activeFolderPath)) {
treeState.setExpandedPaths((prev) => new Set(prev).add(activeFolderPath));
}
setCreatingInPath(activeFolderPath);
}, [activeFolderPath, treeState]);
const handleCreateFileSubmit = useCallback(
(parentPath: string, name: string) => {
setCreatingInPath(null);
const newPath = parentPath ? `${parentPath}/${name}` : name;
const newNode: FileTreeNode = { name, path: newPath, is_dir: false, size: 0 };
treeState.setTree((prev) => (prev ? insertNodeInTree(prev, parentPath, newNode) : prev));
onCreateFile?.(newPath)
.then((ok) => {
if (!ok) treeState.setTree((prev) => (prev ? removeNodeFromTree(prev, newPath) : prev));
})
.catch(() => {
treeState.setTree((prev) => (prev ? removeNodeFromTree(prev, newPath) : prev));
});
},
[onCreateFile, treeState],
);
const toggleExpand = useCallback(
async (node: FileTreeNode) => {
if (!node.is_dir) return;
setActiveFolderPath(node.path);
const newExpanded = new Set(treeState.expandedPaths);
if (newExpanded.has(node.path)) {
newExpanded.delete(node.path);
} else {
await loadNodeChildren(node, sessionId, treeState);
newExpanded.add(node.path);
}
treeState.setExpandedPaths(newExpanded);
},
[treeState, sessionId],
);
const openFileByPath = useCallback(
(path: string) => fetchAndOpenFile(sessionId, path, onOpenFile, toast),
[sessionId, onOpenFile, toast],
);
const handleCancelCreate = useCallback(() => setCreatingInPath(null), []);
return {
creatingInPath,
activeFolderPath,
handleStartCreate,
handleCreateFileSubmit,
toggleExpand,
openFileByPath,
handleCancelCreate,
};
}
function isDropInvalid(sources: string[], targetPath: string): boolean {
return sources.some((s) => s === targetPath || targetPath.startsWith(`${s}/`));
}
type MoveFilesParams = {
sources: string[];
targetPath: string;
treeState: ReturnType<typeof useFileBrowserTree>;
setSelectedPaths: (paths: Set<string>) => void;
onRenameFile: (oldPath: string, newPath: string) => Promise<boolean>;
};
function executeMoveFiles(params: MoveFilesParams, toast: ReturnType<typeof useToast>["toast"]) {
const { sources, targetPath, treeState, setSelectedPaths, onRenameFile } = params;
const snapshot = treeState.tree;
// Compute deduplicated target paths before modifying the tree
const targets = treeState.tree ? computeMoveTargets(treeState.tree, sources, targetPath) : [];
treeState.setTree((prev) => (prev ? moveNodesInTree(prev, sources, targetPath) : prev));
setSelectedPaths(new Set());
const movePromises = targets.map(({ oldPath, newPath }) => onRenameFile(oldPath, newPath));
Promise.all(movePromises)
.then((results) => {
if (results.some((ok) => !ok)) {
treeState.setTree(snapshot);
toast({
title: "Move failed",
description: "Some files could not be moved",
variant: "error",
});
}
})
.catch(() => {
treeState.setTree(snapshot);
toast({
title: "Move failed",
description: "An error occurred while moving files",
variant: "error",
});
});
}
function useDragAndDrop(
treeState: ReturnType<typeof useFileBrowserTree>,
selectedPaths: Set<string>,
setSelectedPaths: (paths: Set<string>) => void,
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>,
) {
const { toast } = useToast();
const [isDragging, setIsDragging] = useState(false);
const [dragOverPath, setDragOverPath] = useState<string | null>(null);
const dragPathsRef = useRef<string[]>([]);
const handleDragStart = useCallback(
(path: string, e: React.DragEvent) => {
const paths = selectedPaths.has(path) ? [...selectedPaths] : [path];
if (!selectedPaths.has(path)) setSelectedPaths(new Set([path]));
dragPathsRef.current = paths;
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", JSON.stringify(paths));
setIsDragging(true);
},
[selectedPaths, setSelectedPaths],
);
const handleDragEnd = useCallback(() => {
setIsDragging(false);
setDragOverPath(null);
dragPathsRef.current = [];
}, []);
// Safety net: clear drag state if dragend doesn't fire on the element
// (e.g. Escape key, drag outside browser window)
useEffect(() => {
if (!isDragging) return;
const cleanup = () => {
setIsDragging(false);
setDragOverPath(null);
dragPathsRef.current = [];
};
document.addEventListener("dragend", cleanup);
return () => document.removeEventListener("dragend", cleanup);
}, [isDragging]);
const handleDragOver = useCallback((targetPath: string, e: React.DragEvent) => {
const sources = dragPathsRef.current;
if (isDropInvalid(sources, targetPath)) return;
const allSameParent = sources.every((s) => {
const parent = s.includes("/") ? s.substring(0, s.lastIndexOf("/")) : "";
return parent === targetPath;
});
if (allSameParent) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setDragOverPath(targetPath);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
const related = e.relatedTarget as Node | null;
if (related && (e.currentTarget as Node).contains(related)) return;
setDragOverPath(null);
}, []);
const handleDrop = useCallback(
(targetPath: string, e: React.DragEvent) => {
e.preventDefault();
setDragOverPath(null);
setIsDragging(false);
if (!onRenameFile) return;
const sources = dragPathsRef.current;
if (sources.length === 0 || isDropInvalid(sources, targetPath)) return;
executeMoveFiles({ sources, targetPath, treeState, setSelectedPaths, onRenameFile }, toast);
},
[onRenameFile, treeState, setSelectedPaths, toast],
);
return {
isDragging,
dragOverPath,
handleDragStart,
handleDragEnd,
handleDragOver,
handleDragLeave,
handleDrop,
};
}
function useAutoExpandAncestors(
activeFilePath: string | null | undefined,
setExpandedPaths: React.Dispatch<React.SetStateAction<Set<string>>>,
) {
useEffect(() => {
if (!activeFilePath) return;
const parts = activeFilePath.split("/");
if (parts.length <= 1) return;
const ancestors: string[] = [];
for (let i = 1; i < parts.length; i++) {
ancestors.push(parts.slice(0, i).join("/"));
}
setExpandedPaths((prev) => {
if (ancestors.every((p) => prev.has(p))) return prev;
const next = new Set(prev);
for (const p of ancestors) next.add(p);
return next;
});
}, [activeFilePath, setExpandedPaths]);
}
function useSelectionInteractions(
treeState: ReturnType<typeof useFileBrowserTree>,
containerRef: React.RefObject<HTMLDivElement | null>,
activeFilePath: string | null | undefined,
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>,
) {
const visiblePaths = useMemo(
() => (treeState.tree ? getVisiblePaths(treeState.tree, treeState.expandedPaths) : []),
[treeState.tree, treeState.expandedPaths],
);
const multiSelect = useMultiSelect({ items: visiblePaths });
const dnd = useDragAndDrop(
treeState,
multiSelect.selectedPaths,
multiSelect.setSelectedPaths,
onRenameFile,
);
useKeyboardShortcuts(containerRef, multiSelect.clearSelection, multiSelect.selectAll);
useAutoExpandAncestors(activeFilePath, treeState.setExpandedPaths);
const handleClickOutside = useCallback(
(e: React.MouseEvent) => {
if (multiSelect.selectedPaths.size === 0) return;
const target = e.target as HTMLElement;
// Don't clear if clicking on a tree node, context menu, or dialog
if (
target.closest("[data-testid='file-tree-node']") ||
target.closest("[role='menu']") ||
target.closest("[role='alertdialog']") ||
target.closest("[role='dialog']")
)
return;
multiSelect.clearSelection();
},
[multiSelect],
);
return { multiSelect, dnd, handleClickOutside };
}
function useKeyboardShortcuts(
containerRef: React.RefObject<HTMLDivElement | null>,
clearSelection: () => void,
selectAll: () => void,
) {
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (!container.contains(document.activeElement) && document.activeElement !== container)
return;
if (e.key === "Escape") {
clearSelection();
} else if ((e.ctrlKey || e.metaKey) && e.key === "a") {
e.preventDefault();
selectAll();
}
};
container.addEventListener("keydown", handleKeyDown);
return () => container.removeEventListener("keydown", handleKeyDown);
}, [containerRef, clearSelection, selectAll]);
}
export function FileBrowser({
sessionId,
environmentId,
onOpenFile,
onCreateFile,
onDeleteFile,
onRenameFile,
activeFilePath,
}: FileBrowserProps) {
const { session, isFailed: isSessionFailed, errorMessage: sessionError } = useSession(sessionId);
const repository = useRepository(session?.repository_id ?? null);
const gitStatus = useSessionGitStatus(sessionId);
const { open: openFolder } = useOpenSessionFolder(sessionId);
const { copied, copy: copyPath } = useCopyToClipboard(1000);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const search = useFileBrowserSearch(sessionId);
const treeState = useFileBrowserTree(sessionId, environmentId ?? undefined);
const isTreeLoaded = !treeState.isLoadingTree && treeState.tree !== null;
useScrollPersistence(sessionId, isTreeLoaded, scrollAreaRef, treeState.tree);
const fileStatuses = useMemo(
() =>
new Map(Object.entries(gitStatus?.files ?? {}).map(([path, info]) => [path, info.status])),
[gitStatus?.files],
);
const fullPath = session?.worktree_path || repository?.local_path || "";
const displayPath = fullPath.replace(/^\/(?:Users|home)\/[^/]+\//, "~/");
const handlers = useFileBrowserHandlers(sessionId, onOpenFile, onCreateFile, treeState);
const { multiSelect, dnd, handleClickOutside } = useSelectionInteractions(
treeState,
containerRef,
activeFilePath,
onRenameFile,
);
return (
<div
className="flex flex-col h-full"
ref={containerRef}
tabIndex={-1}
onMouseDown={handleClickOutside}
>
<FileBrowserHeader
treeLoaded={Boolean(treeState.tree && treeState.loadState === "loaded")}
search={search}
displayPath={displayPath}
fullPath={fullPath}
copied={copied}
expandedPathsSize={treeState.expandedPaths.size}
onCopyPath={copyPath}
onStartCreate={onCreateFile ? handlers.handleStartCreate : undefined}
onOpenFolder={openFolder}
onCollapseAll={treeState.collapseAll}
showCreateButton={Boolean(onCreateFile)}
/>
<ScrollArea className="flex-1" ref={scrollAreaRef}>
<FileBrowserContentArea
isSearchActive={search.isSearchActive}
searchResults={search.searchResults}
isSessionFailed={isSessionFailed}
sessionError={sessionError}
loadState={treeState.loadState}
isLoadingTree={treeState.isLoadingTree}
tree={treeState.tree}
loadError={treeState.loadError}
creatingInPath={handlers.creatingInPath}
fileStatuses={fileStatuses}
expandedPaths={treeState.expandedPaths}
activeFolderPath={handlers.activeFolderPath}
activeFilePath={activeFilePath}
visibleLoadingPaths={treeState.visibleLoadingPaths}
onOpenFile={handlers.openFileByPath}
onToggleExpand={handlers.toggleExpand}
onDeleteFile={onDeleteFile}
onRenameFile={onRenameFile}
onCreateFileSubmit={handlers.handleCreateFileSubmit}
onCancelCreate={handlers.handleCancelCreate}
onRetry={() => void treeState.loadTree({ resetRetry: true })}
setTree={treeState.setTree}
isSelectedFn={multiSelect.isSelected}
onSelect={multiSelect.handleClick}
isDragging={dnd.isDragging}
dragOverPath={dnd.dragOverPath}
onDragStart={dnd.handleDragStart}
onDragEnd={dnd.handleDragEnd}
onDragOver={dnd.handleDragOver}
onDragLeave={dnd.handleDragLeave}
onDrop={dnd.handleDrop}
selectedCount={multiSelect.selectedPaths.size}
selectedPaths={multiSelect.selectedPaths}
/>
</ScrollArea>
</div>
);
}