Files
kandev/apps/web/components/task/changes-panel-file-row.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

302 lines
8.3 KiB
TypeScript

"use client";
import {
IconArrowBackUp,
IconPlus,
IconMinus,
IconCheck,
IconLoader2,
IconPencil,
} from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { cn } from "@/lib/utils";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { LineStat } from "@/components/diff-stat";
import type { FileInfo } from "@/lib/state/store";
import { FileStatusIcon } from "./file-status-icon";
const splitPath = (path: string) => {
const lastSlash = path.lastIndexOf("/");
if (lastSlash === -1) return { folder: "", file: path };
return {
folder: path.slice(0, lastSlash),
file: path.slice(lastSlash + 1),
};
};
type ChangedFile = {
path: string;
status: FileInfo["status"];
staged: boolean;
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
};
type FileRowProps = {
file: ChangedFile;
isPending: boolean;
isSelected?: boolean;
onSelect?: (path: string, e: React.MouseEvent) => boolean;
onOpenDiff: (path: string) => void;
onStage: (path: string) => void;
onUnstage: (path: string) => void;
onDiscard: (path: string) => void;
onEditFile: (path: string) => void;
};
export function FileRow({
file,
isPending,
isSelected,
onSelect,
onOpenDiff,
onStage,
onUnstage,
onDiscard,
onEditFile,
}: FileRowProps) {
const { folder, file: name } = splitPath(file.path);
const handleClick = (e: React.MouseEvent) => {
if (e.button === 2) return;
const consumed = onSelect?.(file.path, e);
if (!consumed) {
onOpenDiff(file.path);
}
};
return (
<li
data-testid={`file-row-${file.path.replace(/[/\\]/g, "-")}`}
data-changes-file={file.path}
data-selected={isSelected ? "true" : "false"}
className={cn(
"group flex items-center justify-between gap-2 text-sm rounded-md px-1 py-0.5 -mx-1 cursor-pointer",
isSelected ? "bg-accent/60 text-accent-foreground hover:bg-accent/50" : "hover:bg-muted/60",
)}
onClick={handleClick}
>
<div className="flex items-center gap-2 min-w-0">
<StageButton
isPending={isPending}
staged={file.staged}
path={file.path}
onStage={onStage}
onUnstage={onUnstage}
/>
<button type="button" className="min-w-0 text-left cursor-pointer" title={file.path}>
<p className="flex text-foreground text-xs min-w-0">
{folder && <span className="text-foreground/60 truncate shrink">{folder}/</span>}
<span className="font-medium text-foreground whitespace-nowrap shrink-0">{name}</span>
</p>
</button>
</div>
<div className="flex items-center gap-2">
<FileRowActions path={file.path} onDiscard={onDiscard} onEditFile={onEditFile} />
<LineStat added={file.plus} removed={file.minus} />
<FileStatusIcon status={file.status} />
</div>
</li>
);
}
function StageButton({
isPending,
staged,
path,
onStage,
onUnstage,
}: {
isPending: boolean;
staged: boolean;
path: string;
onStage: (path: string) => void;
onUnstage: (path: string) => void;
}) {
if (isPending) {
return (
<div className="flex-shrink-0 flex items-center justify-center size-4">
<IconLoader2 className="h-3 w-3 animate-spin text-muted-foreground" />
</div>
);
}
if (staged) {
return (
<button
type="button"
title="Unstage file"
className="group/unstage flex-shrink-0 flex items-center justify-center size-4 rounded bg-emerald-500/20 text-emerald-600 hover:bg-rose-500/20 hover:text-rose-600 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onUnstage(path);
}}
>
<IconCheck className="h-3 w-3 group-hover/unstage:hidden" />
<IconMinus className="h-2.5 w-2.5 hidden group-hover/unstage:block" />
</button>
);
}
return (
<button
type="button"
title="Stage file"
className="flex-shrink-0 flex items-center justify-center size-4 rounded border border-dashed border-muted-foreground/50 text-muted-foreground hover:border-emerald-500 hover:text-emerald-500 hover:bg-emerald-500/10 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onStage(path);
}}
>
<IconPlus className="h-2.5 w-2.5" />
</button>
);
}
function FileRowActions({
path,
onDiscard,
onEditFile,
}: {
path: string;
onDiscard: (path: string) => void;
onEditFile: (path: string) => void;
}) {
return (
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:text-foreground cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onDiscard(path);
}}
>
<IconArrowBackUp className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>Discard changes</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:text-foreground cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onEditFile(path);
}}
>
<IconPencil className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>Edit</TooltipContent>
</Tooltip>
</div>
);
}
// --- Bulk action components (used by FileListSection) ---
export function DefaultActionButtons({
actionLabel,
isActionLoading,
onAction,
secondaryActionLabel,
isSecondaryActionLoading,
onSecondaryAction,
}: {
actionLabel: string;
isActionLoading?: boolean;
onAction: () => void;
secondaryActionLabel?: string;
isSecondaryActionLoading?: boolean;
onSecondaryAction?: () => void;
}) {
return (
<>
<Button
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer"
onClick={onAction}
disabled={isActionLoading}
>
{isActionLoading && <IconLoader2 className="h-3 w-3 animate-spin" />}
{actionLabel}
</Button>
{onSecondaryAction && secondaryActionLabel && (
<Button
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer"
onClick={onSecondaryAction}
disabled={isSecondaryActionLoading}
>
{isSecondaryActionLoading && <IconLoader2 className="h-3 w-3 animate-spin" />}
{secondaryActionLabel}
</Button>
)}
</>
);
}
export function BulkActionBar({
variant,
selectionCount,
selectedPaths,
onBulkStage,
onBulkUnstage,
onBulkDiscard,
}: {
variant: "unstaged" | "staged";
selectionCount: number;
selectedPaths: Set<string>;
onBulkStage?: (paths: string[]) => void;
onBulkUnstage?: (paths: string[]) => void;
onBulkDiscard?: (paths: string[]) => void;
}) {
const paths = [...selectedPaths];
return (
<div data-testid={`bulk-actions-${variant}`} className="flex items-center gap-1.5">
<span className="text-[11px] text-muted-foreground">{selectionCount} selected</span>
{variant === "unstaged" && onBulkStage && (
<Button
data-testid="bulk-stage"
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer"
onClick={() => onBulkStage(paths)}
>
Stage {selectionCount}
</Button>
)}
{variant === "staged" && onBulkUnstage && (
<Button
data-testid={`bulk-unstage-${variant}`}
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer"
onClick={() => onBulkUnstage(paths)}
>
Unstage {selectionCount}
</Button>
)}
{onBulkDiscard && (
<Button
data-testid={`bulk-discard-${variant}`}
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer text-destructive hover:text-destructive"
onClick={() => onBulkDiscard(paths)}
>
Discard {selectionCount}
</Button>
)}
</div>
);
}