Files
kandev/apps/web/components/task/file-browser-parts.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

412 lines
13 KiB
TypeScript

"use client";
import React from "react";
import {
IconChevronRight,
IconChevronDown,
IconFolder,
IconFolderOpen,
IconRefresh,
} from "@tabler/icons-react";
import { cn } from "@/lib/utils";
import { FileIcon } from "@/components/ui/file-icon";
import type { FileTreeNode } from "@/lib/types/backend";
import type { FileInfo } from "@/lib/state/store";
import { InlineFileInput } from "./inline-file-input";
import { renderSessionOrLoadState } from "./file-browser-load-state";
import { compareTreeNodes } from "./file-tree-utils";
import {
FileContextMenu,
useFileRename,
TreeNodeName,
getGitStatusTextClass,
} from "./file-context-menu";
export {
compareTreeNodes,
mergeTreeNodes,
insertNodeInTree,
removeNodeFromTree,
renameNodeInTree,
} from "./file-tree-utils";
type GitFileStatus = FileInfo["status"] | undefined;
type TreeNodeItemProps = {
node: FileTreeNode;
depth: number;
expandedPaths: Set<string>;
activeFolderPath: string;
activeFilePath?: string | null;
visibleLoadingPaths: Set<string>;
creatingInPath: string | null;
fileStatuses: Map<string, GitFileStatus>;
tree: FileTreeNode | null;
onToggleExpand: (node: FileTreeNode) => void;
onOpenFile: (path: string) => void;
onDeleteFile?: (path: string) => Promise<boolean>;
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>;
onCreateFileSubmit: (parentPath: string, name: string) => void;
onCancelCreate: () => void;
setTree: React.Dispatch<React.SetStateAction<FileTreeNode | null>>;
isSelectedFn?: (path: string) => boolean;
onSelect?: (path: string, e: React.MouseEvent) => boolean;
isDragging?: boolean;
dragOverPath?: string | null;
onDragStart?: (path: string, e: React.DragEvent) => void;
onDragEnd?: () => void;
onDragOver?: (path: string, e: React.DragEvent) => void;
onDragLeave?: (e: React.DragEvent) => void;
onDrop?: (targetPath: string, e: React.DragEvent) => void;
selectedCount?: number;
selectedPaths?: Set<string>;
};
function treeNodePaddingLeft(depth: number, isDir: boolean): string {
return `${depth * 12 + 8 + (isDir ? 0 : 20)}px`;
}
function handleTreeNodeClick(
node: FileTreeNode,
onToggleExpand: (node: FileTreeNode) => void,
onOpenFile: (path: string) => void,
) {
if (node.is_dir) {
onToggleExpand(node);
return;
}
onOpenFile(node.path);
}
/** Expand/collapse chevron for directory nodes. */
function TreeNodeExpandChevron({
isLoading,
isExpanded,
}: {
isLoading: boolean;
isExpanded: boolean;
}) {
if (isLoading)
return <IconRefresh className="h-4 w-4 animate-spin text-muted-foreground shrink-0" />;
if (isExpanded) return <IconChevronDown className="h-3 w-3 text-muted-foreground/60" />;
return <IconChevronRight className="h-3 w-3 text-muted-foreground/60" />;
}
/** Directory or file icon for a tree node. */
function TreeNodeFileIcon({
node,
isExpanded,
isActive,
}: {
node: FileTreeNode;
isExpanded: boolean;
isActive: boolean;
}) {
if (node.is_dir) {
return isExpanded ? (
<IconFolderOpen className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
) : (
<IconFolder className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
);
}
return (
<FileIcon
fileName={node.name}
filePath={node.path}
className="flex-shrink-0"
style={{ width: "14px", height: "14px", opacity: isActive ? 1 : 0.7 }}
/>
);
}
/** Expanded directory children */
function TreeNodeChildren({ props, depth }: { props: TreeNodeItemProps; depth: number }) {
const { node, creatingInPath, onCreateFileSubmit, onCancelCreate } = props;
return (
<div>
{creatingInPath === node.path && (
<InlineFileInput
depth={depth + 1}
onSubmit={(name) => onCreateFileSubmit(node.path, name)}
onCancel={onCancelCreate}
/>
)}
{node.children &&
[...node.children]
.sort(compareTreeNodes)
.map((child) => (
<TreeNodeItem key={child.path} {...props} node={child} depth={depth + 1} />
))}
</div>
);
}
function getTreeNodeRowClass(
isActive: boolean,
isActiveFolder: boolean,
isSelected: boolean,
isDragging: boolean | undefined,
isDropTarget: boolean,
) {
return cn(
"group flex w-full items-center gap-1 px-2 py-0.5 text-left text-sm cursor-pointer",
isSelected
? "bg-accent text-accent-foreground hover:bg-accent/80 [&_span]:text-accent-foreground"
: "hover:bg-muted",
isActive && !isSelected && "bg-muted",
isActiveFolder && !isSelected && "bg-muted/50",
isDragging && isSelected && "opacity-50",
isDropTarget && "bg-accent/40 ring-1 ring-accent",
);
}
export function TreeNodeItem(props: TreeNodeItemProps) {
const { node, depth, expandedPaths, activeFolderPath, activeFilePath, visibleLoadingPaths } =
props;
const { fileStatuses, tree, onToggleExpand, onOpenFile, onDeleteFile, onRenameFile, setTree } =
props;
const isExpanded = expandedPaths.has(node.path);
const isActive = !node.is_dir && activeFilePath === node.path;
const isActiveFolder = node.is_dir && activeFolderPath === node.path;
const gitStatus = node.is_dir ? undefined : fileStatuses.get(node.path);
const rename = useFileRename(node, tree, setTree, onRenameFile);
const isSelected = props.isSelectedFn?.(node.path) ?? false;
const isDropTarget = node.is_dir && props.dragOverPath === node.path;
const handleClick = (e: React.MouseEvent) => {
if (e.button === 2) return;
const consumed = props.onSelect?.(node.path, e);
if (!consumed) {
handleTreeNodeClick(node, onToggleExpand, onOpenFile);
}
};
// Inline the row JSX so ContextMenuTrigger asChild can attach directly to the DOM div
const rowContent = (
<div
data-testid="file-tree-node"
data-path={node.path}
data-is-dir={node.is_dir ? "true" : "false"}
data-selected={isSelected ? "true" : "false"}
aria-selected={isSelected}
role="treeitem"
className={getTreeNodeRowClass(
isActive,
isActiveFolder,
isSelected,
props.isDragging,
isDropTarget,
)}
style={{ paddingLeft: treeNodePaddingLeft(depth, node.is_dir) }}
onClick={handleClick}
draggable={!!props.onDragStart}
onDragStart={(e) => props.onDragStart?.(node.path, e)}
onDragEnd={() => props.onDragEnd?.()}
onDragOver={(e) => {
if (node.is_dir) props.onDragOver?.(node.path, e);
}}
onDragLeave={(e) => props.onDragLeave?.(e)}
onDrop={(e) => {
if (node.is_dir) props.onDrop?.(node.path, e);
}}
>
{node.is_dir && (
<span className="flex-shrink-0">
<TreeNodeExpandChevron
isLoading={visibleLoadingPaths.has(node.path)}
isExpanded={isExpanded}
/>
</span>
)}
<TreeNodeFileIcon node={node} isExpanded={isExpanded} isActive={isActive} />
<TreeNodeName node={node} isActive={isActive} gitStatus={gitStatus} rename={rename} />
</div>
);
return (
<div>
<FileContextMenu
node={node}
tree={tree}
setTree={setTree}
onDeleteFile={onDeleteFile}
onRenameFile={onRenameFile}
onStartRename={rename.handleStartRename}
selectedCount={props.selectedCount}
selectedPaths={props.selectedPaths}
>
{rowContent}
</FileContextMenu>
{node.is_dir && isExpanded && <TreeNodeChildren props={props} depth={depth} />}
</div>
);
}
type SearchResultsListProps = {
searchResults: string[] | null;
fileStatuses: Map<string, GitFileStatus>;
onOpenFile: (path: string) => void;
};
export function SearchResultsList({
searchResults,
fileStatuses,
onOpenFile,
}: SearchResultsListProps) {
if (!searchResults) return null;
if (searchResults.length === 0) {
return <div className="p-4 text-sm text-muted-foreground text-center">No files found</div>;
}
return (
<div className="pb-2">
{searchResults.map((path) => {
const name = path.split("/").pop() || path;
const folder = path.includes("/") ? path.substring(0, path.lastIndexOf("/")) : "";
const gitStatus = fileStatuses.get(path);
return (
<div
key={path}
className={cn(
"group flex w-full items-center gap-1 px-2 py-0.5 text-left text-sm cursor-pointer",
"hover:bg-muted",
)}
onClick={() => onOpenFile(path)}
>
<FileIcon
fileName={name}
filePath={path}
className="flex-shrink-0"
style={{ width: "14px", height: "14px" }}
/>
<span
className={cn(
"truncate group-hover:text-foreground",
getGitStatusTextClass(gitStatus) || "text-muted-foreground",
)}
>
{folder && <span>{folder}/</span>}
<span>{name}</span>
</span>
</div>
);
})}
</div>
);
}
export { FileBrowserToolbar } from "./file-browser-toolbar";
type FileBrowserContentAreaProps = {
isSearchActive: boolean;
searchResults: string[] | null;
isSessionFailed: boolean;
sessionError?: string | null;
loadState: string;
isLoadingTree: boolean;
tree: FileTreeNode | null;
loadError: string | null;
creatingInPath: string | null;
fileStatuses: Map<string, GitFileStatus>;
expandedPaths: Set<string>;
activeFolderPath: string;
activeFilePath?: string | null;
visibleLoadingPaths: Set<string>;
onOpenFile: (path: string) => void;
onToggleExpand: (node: FileTreeNode) => void;
onDeleteFile?: (path: string) => Promise<boolean>;
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>;
onCreateFileSubmit: (parentPath: string, name: string) => void;
onCancelCreate: () => void;
onRetry: () => void;
setTree: React.Dispatch<React.SetStateAction<FileTreeNode | null>>;
isSelectedFn?: (path: string) => boolean;
onSelect?: (path: string, e: React.MouseEvent) => boolean;
isDragging?: boolean;
dragOverPath?: string | null;
onDragStart?: (path: string, e: React.DragEvent) => void;
onDragEnd?: () => void;
onDragOver?: (path: string, e: React.DragEvent) => void;
onDragLeave?: (e: React.DragEvent) => void;
onDrop?: (targetPath: string, e: React.DragEvent) => void;
selectedCount?: number;
selectedPaths?: Set<string>;
};
function FileTreeView(props: FileBrowserContentAreaProps) {
const { tree, creatingInPath, onCreateFileSubmit, onCancelCreate } = props;
if (!tree) return null;
return (
<div className="pb-2">
{creatingInPath === "" && (
<InlineFileInput
depth={0}
onSubmit={(name) => onCreateFileSubmit("", name)}
onCancel={onCancelCreate}
/>
)}
{tree.children &&
[...tree.children]
.sort(compareTreeNodes)
.map((child) => (
<TreeNodeItem
key={child.path}
node={child}
depth={0}
expandedPaths={props.expandedPaths}
activeFolderPath={props.activeFolderPath}
activeFilePath={props.activeFilePath}
visibleLoadingPaths={props.visibleLoadingPaths}
creatingInPath={creatingInPath}
fileStatuses={props.fileStatuses}
tree={tree}
onToggleExpand={props.onToggleExpand}
onOpenFile={props.onOpenFile}
onDeleteFile={props.onDeleteFile}
onRenameFile={props.onRenameFile}
onCreateFileSubmit={onCreateFileSubmit}
onCancelCreate={onCancelCreate}
setTree={props.setTree}
isSelectedFn={props.isSelectedFn}
onSelect={props.onSelect}
isDragging={props.isDragging}
dragOverPath={props.dragOverPath}
onDragStart={props.onDragStart}
onDragEnd={props.onDragEnd}
onDragOver={props.onDragOver}
onDragLeave={props.onDragLeave}
onDrop={props.onDrop}
selectedCount={props.selectedCount}
selectedPaths={props.selectedPaths}
/>
))}
</div>
);
}
export function FileBrowserContentArea(props: FileBrowserContentAreaProps) {
if (props.isSearchActive && props.searchResults !== null) {
return (
<SearchResultsList
searchResults={props.searchResults}
fileStatuses={props.fileStatuses}
onOpenFile={props.onOpenFile}
/>
);
}
const loadStateResult = renderSessionOrLoadState({
isSessionFailed: props.isSessionFailed,
sessionError: props.sessionError,
loadState: props.loadState,
isLoadingTree: props.isLoadingTree,
tree: props.tree,
loadError: props.loadError,
onRetry: props.onRetry,
});
if (loadStateResult) return loadStateResult;
if (props.tree) return <FileTreeView {...props} />;
return <div className="p-4 text-sm text-muted-foreground">No files found</div>;
}