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

352 lines
9.9 KiB
TypeScript

"use client";
import React, { useState, useCallback, useRef, useEffect } from "react";
import { Input } from "@kandev/ui/input";
import { IconPencil, IconTrash } from "@tabler/icons-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@kandev/ui/alert-dialog";
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
ContextMenuSeparator,
} from "@kandev/ui/context-menu";
import { cn } from "@/lib/utils";
import { useToast } from "@/components/toast-provider";
import type { FileTreeNode } from "@/lib/types/backend";
import type { FileInfo } from "@/lib/state/store";
import {
removeNodeFromTree,
renameNodeInTree,
treeContainsPath,
countFilesInTree,
} from "./file-tree-utils";
type GitFileStatus = FileInfo["status"] | undefined;
function deleteNodeOptimistically(
tree: FileTreeNode | null,
setTree: React.Dispatch<React.SetStateAction<FileTreeNode | null>>,
path: string,
onDeleteFile: (path: string) => Promise<boolean>,
) {
const snapshot = tree;
setTree((prev) => (prev ? removeNodeFromTree(prev, path) : prev));
onDeleteFile(path)
.then((ok) => {
if (!ok) setTree(snapshot);
})
.catch(() => setTree(snapshot));
}
function DeleteConfirmDialog({
isBulk,
selectedCount,
node,
fileCount,
onConfirm,
}: {
isBulk: boolean;
selectedCount: number;
node: FileTreeNode;
fileCount: number;
onConfirm: () => void;
}) {
const title = isBulk ? `Delete ${selectedCount} items?` : "Delete folder?";
return (
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription>
{isBulk ? (
`This will permanently delete ${selectedCount} selected items. This action cannot be undone.`
) : (
<>
This will permanently delete <span className="font-semibold">{node.name}</span>
{fileCount > 0 && (
<>
{" "}
and <span className="font-semibold">{fileCount}</span>{" "}
{fileCount === 1 ? "file" : "files"} inside it
</>
)}
. This action cannot be undone.
</>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel className="cursor-pointer">Cancel</AlertDialogCancel>
<AlertDialogAction onClick={onConfirm} variant="destructive" className="cursor-pointer">
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
);
}
/** Context menu for file nodes with Rename and Delete options */
export function FileContextMenu({
children,
node,
tree,
setTree,
onDeleteFile,
onRenameFile,
onStartRename,
selectedCount = 0,
selectedPaths,
}: {
children: React.ReactNode;
node: FileTreeNode;
tree: FileTreeNode | null;
setTree: React.Dispatch<React.SetStateAction<FileTreeNode | null>>;
onDeleteFile?: (path: string) => Promise<boolean>;
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>;
onStartRename: () => void;
selectedCount?: number;
selectedPaths?: Set<string>;
}) {
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const isBulk = selectedCount > 1;
const needsConfirmation = node.is_dir || isBulk;
const handleConfirmDelete = useCallback(() => {
setDeleteDialogOpen(false);
if (!onDeleteFile) return;
if (isBulk && selectedPaths) {
// Remove all nodes optimistically, then call APIs.
// Rollback entire tree only if any individual delete fails.
const snapshot = tree;
const paths = [...selectedPaths];
setTree((prev) => {
let t = prev;
for (const p of paths) t = t ? removeNodeFromTree(t, p) : t;
return t;
});
Promise.all(paths.map((p) => onDeleteFile(p)))
.then((results) => {
if (results.some((ok) => !ok)) setTree(snapshot);
})
.catch(() => setTree(snapshot));
} else {
deleteNodeOptimistically(tree, setTree, node.path, onDeleteFile);
}
}, [tree, setTree, node.path, onDeleteFile, isBulk, selectedPaths]);
const handleDelete = useCallback(() => {
if (!onDeleteFile) return;
if (needsConfirmation) {
setDeleteDialogOpen(true);
} else {
deleteNodeOptimistically(tree, setTree, node.path, onDeleteFile);
}
}, [tree, setTree, node.path, onDeleteFile, needsConfirmation]);
if (!onDeleteFile && !onRenameFile) return <>{children}</>;
const deleteLabel = isBulk ? `Delete ${selectedCount} items` : "Delete";
return (
<>
<ContextMenu>
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
<ContextMenuContent>
{onDeleteFile && (
<ContextMenuItem variant="destructive" onSelect={handleDelete}>
<IconTrash className="h-3.5 w-3.5" />
{deleteLabel}
</ContextMenuItem>
)}
{onRenameFile && onDeleteFile && !isBulk && <ContextMenuSeparator />}
{onRenameFile && !isBulk && (
<ContextMenuItem onSelect={onStartRename}>
<IconPencil className="h-3.5 w-3.5" />
Rename
</ContextMenuItem>
)}
</ContextMenuContent>
</ContextMenu>
{needsConfirmation && (
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DeleteConfirmDialog
isBulk={isBulk}
selectedCount={selectedCount}
node={node}
fileCount={countFilesInTree(node)}
onConfirm={handleConfirmDelete}
/>
</AlertDialog>
)}
</>
);
}
/** Hook for managing inline file rename state */
export function useFileRename(
node: FileTreeNode,
tree: FileTreeNode | null,
setTree: React.Dispatch<React.SetStateAction<FileTreeNode | null>>,
onRenameFile?: (oldPath: string, newPath: string) => Promise<boolean>,
) {
const { toast } = useToast();
const [isRenaming, setIsRenaming] = useState(false);
const [renameValue, setRenameValue] = useState(node.name);
const handleStartRename = useCallback(() => {
setRenameValue(node.name);
setIsRenaming(true);
}, [node.name]);
const handleCancelRename = useCallback(() => {
setIsRenaming(false);
setRenameValue(node.name);
}, [node.name]);
const handleConfirmRename = useCallback(() => {
const newName = renameValue.trim();
if (!newName || newName === node.name || !onRenameFile) {
handleCancelRename();
return;
}
if (newName.includes("/") || newName.includes("\\")) {
toast({
title: "Invalid name",
description: "File names cannot contain path separators",
variant: "error",
});
handleCancelRename();
return;
}
const parentPath = node.path.includes("/")
? node.path.substring(0, node.path.lastIndexOf("/"))
: "";
const newPath = parentPath ? `${parentPath}/${newName}` : newName;
const snapshot = tree;
setIsRenaming(false);
if (tree && treeContainsPath(tree, newPath)) {
toast({
title: "Failed to rename item",
description: `Target already exists: ${newPath}`,
variant: "error",
});
handleCancelRename();
return;
}
setTree((prev) => (prev ? renameNodeInTree(prev, node.path, newPath) : prev));
onRenameFile(node.path, newPath)
.then((ok) => {
if (!ok) setTree(snapshot);
})
.catch(() => {
setTree(snapshot);
});
}, [renameValue, node.name, node.path, onRenameFile, tree, setTree, handleCancelRename, toast]);
const handleRenameKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
handleConfirmRename();
} else if (e.key === "Escape") {
handleCancelRename();
}
},
[handleConfirmRename, handleCancelRename],
);
return {
isRenaming,
renameValue,
setRenameValue,
handleStartRename,
handleConfirmRename,
handleRenameKeyDown,
};
}
/** Inline rename input or static file name */
export function TreeNodeName({
node,
isActive,
gitStatus,
rename,
}: {
node: FileTreeNode;
isActive: boolean;
gitStatus: GitFileStatus;
rename: ReturnType<typeof useFileRename>;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const blurEnabledRef = useRef(false);
useEffect(() => {
if (rename.isRenaming) {
blurEnabledRef.current = false;
const focusTimer = setTimeout(() => {
inputRef.current?.focus();
inputRef.current?.select();
}, 150);
const blurTimer = setTimeout(() => {
blurEnabledRef.current = true;
}, 400);
return () => {
clearTimeout(focusTimer);
clearTimeout(blurTimer);
};
}
}, [rename.isRenaming]);
const handleBlur = useCallback(() => {
if (blurEnabledRef.current) {
rename.handleConfirmRename();
}
}, [rename]);
if (rename.isRenaming) {
return (
<Input
ref={inputRef}
value={rename.renameValue}
onChange={(e) => rename.setRenameValue(e.target.value)}
onKeyDown={rename.handleRenameKeyDown}
onBlur={handleBlur}
onClick={(e) => e.stopPropagation()}
className="h-5 text-xs px-1 py-0 flex-1 min-w-0"
/>
);
}
return (
<span
className={cn(
"flex-1 truncate group-hover:text-foreground",
isActive ? "text-foreground" : "text-muted-foreground",
node.is_dir ? "font-medium" : getGitStatusTextClass(gitStatus),
)}
>
{node.name}
</span>
);
}
export function getGitStatusTextClass(status: GitFileStatus): string {
switch (status) {
case "added":
case "untracked":
return "text-green-700 dark:text-green-600";
case "modified":
return "text-yellow-600";
default:
return "";
}
}