Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(file-manager): add subtree selection, open gesture, and parent-dir drop forwarding

Sergey Kozyrenko268732f6108c
diff --git a/frontend/src/components/file-manager/file-manager-row.tsx b/frontend/src/components/file-manager/file-manager-row.tsx
index d6fda748..2a08ebb5 100644
--- a/frontend/src/components/file-manager/file-manager-row.tsx
+++ b/frontend/src/components/file-manager/file-manager-row.tsx
@@ -19,7 +19,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
-import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';
+import type { FileManagerAction, FileManagerInternalNode, FileNode } from './file-manager-types';
import type { FileManagerNodeDndHandlers } from './use-file-manager-dnd';
import { FileManagerHighlightedName } from './file-manager-highlighted-name';
@@ -27,41 +27,87 @@ import { getFileTypeIcon } from './file-manager-icons';
import { formatModified as defaultFormatModified, formatFileSize } from './file-manager-utils';
/**
- * Marker on every interactive child of the row that should NOT bubble into a row click.
- * Detected via `closest()` in the row's click handler — descendants don't need to call
- * `event.stopPropagation()` themselves.
+ * Marker on every interactive child of the row that should NOT bubble into a row
+ * click or double-click. Detected via `closest()` in the row's handlers — descendants
+ * don't need to call `event.stopPropagation()` themselves.
*/
const SKIP_ROW_CLICK_ATTR = 'data-fm-skip-row-click';
const skipRowClickProps = { [SKIP_ROW_CLICK_ATTR]: '' };
-interface FileManagerRowProps {
- actions: readonly FileManagerAction[];
- activeRowPath: null | string;
- /** Drag/drop handlers for this row. `null` when intra-tree DnD is disabled. */
- dnd: FileManagerNodeDndHandlers | null;
- file: FileManagerInternalNode;
+/**
+ * Layout/visibility/i18n props that are identical for every row in the tree.
+ * `FileManager` builds this object once with `useMemo` so memoized rows do not
+ * have to compare seven separate primitives on every parent re-render — a single
+ * reference check is enough.
+ */
+export interface FileManagerRowDisplay {
formatModified?: (modifiedAt: Date | string | undefined) => string;
gridTemplate: string;
hasActions: boolean;
isCheckboxVisible: boolean;
- isExpanded: boolean;
isModifiedVisible: boolean;
- isSelected: boolean;
isSizeVisible: boolean;
- onClick: (event: ReactMouseEvent, path: string) => void;
+ searchQuery?: string;
+}
+
+/**
+ * Stable callback bundle shared by every row. All handlers are produced by
+ * hooks that go through the latest-ref pattern, so this object is built once
+ * and never invalidates the row memo.
+ */
+export interface FileManagerRowHandlers {
+ onClick: (event: ReactMouseEvent, path: string, subtreePaths?: readonly string[]) => void;
onFocusRow: (path: string) => void;
- onToggleCheckbox: (path: string) => void;
+ onOpen?: (file: FileNode) => void;
onToggleExpand: (path: string, wasExpanded: boolean) => void;
+ /**
+ * Polymorphic selection toggle: file rows pass just `path`, directory rows
+ * pass the precomputed subtree so the whole branch flips in one gesture.
+ */
+ onToggleSelection: (path: string, subtreePaths?: readonly string[]) => void;
+}
+
+interface FileManagerRowProps {
+ actions: readonly FileManagerAction[];
+ activeRowPath: null | string;
+ /**
+ * Tri-state checkbox value for directory rows (`true`, `false`, `'indeterminate'`).
+ * `undefined` for file rows — files fall back to `isSelected`.
+ */
+ dirCheckboxState?: 'indeterminate' | boolean;
+ /**
+ * Pre-computed list of every selectable path in the directory's subtree
+ * (the directory itself plus all descendants). `undefined` for files.
+ * Captured by the directory-checkbox click handler so a single gesture
+ * flips the entire branch.
+ */
+ dirSubtreePaths?: readonly string[];
+ /** Per-tree shared layout / i18n bundle (one stable reference). */
+ display: FileManagerRowDisplay;
+ /** Drag/drop handlers for this row. `null` when intra-tree DnD is disabled. */
+ dnd: FileManagerNodeDndHandlers | null;
+ file: FileManagerInternalNode;
+ /** Per-tree shared callback bundle (one stable reference). */
+ handlers: FileManagerRowHandlers;
+ isExpanded: boolean;
+ isSelected: boolean;
/** 1-based position of the row inside its parent's child list (for `aria-posinset`). */
posInSet: number;
- searchQuery?: string;
/** Total number of siblings the row is part of (for `aria-setsize`). */
setSize: number;
}
-/** Returns `true` when the click originated from an element opted-out of row activation. */
+/**
+ * Returns `true` when the click originated from an element opted-out of row activation.
+ *
+ * `Element` (not `HTMLElement`) is the correct guard: `<svg>` and its children
+ * (`<path>` etc.) are `SVGElement`s, which do NOT extend `HTMLElement` even
+ * though they share the `Element.closest()` API. Using `HTMLElement` here would
+ * make a click on the actual painted pixels of an icon (chevron, action button
+ * icon, …) bypass the skip-marker check and re-trigger row selection.
+ */
const isClickInsideSkipZone = (target: EventTarget | null): boolean =>
- target instanceof HTMLElement && !!target.closest(`[${SKIP_ROW_CLICK_ATTR}]`);
+ target instanceof Element && !!target.closest(`[${SKIP_ROW_CLICK_ATTR}]`);
const buildVisibleActions = (
actions: readonly FileManagerAction[],
@@ -71,24 +117,28 @@ const buildVisibleActions = (
const FileManagerRowImpl = ({
actions,
activeRowPath,
+ dirCheckboxState,
+ dirSubtreePaths,
+ display,
dnd,
file,
- formatModified = defaultFormatModified,
- gridTemplate,
- hasActions,
- isCheckboxVisible,
+ handlers,
isExpanded,
- isModifiedVisible,
isSelected,
- isSizeVisible,
- onClick,
- onFocusRow,
- onToggleCheckbox,
- onToggleExpand,
posInSet,
- searchQuery,
setSize,
}: FileManagerRowProps) => {
+ const {
+ formatModified = defaultFormatModified,
+ gridTemplate,
+ hasActions,
+ isCheckboxVisible,
+ isModifiedVisible,
+ isSizeVisible,
+ searchQuery,
+ } = display;
+ const { onClick, onFocusRow, onOpen, onToggleExpand, onToggleSelection } = handlers;
+
const { icon: Icon, tone } = useMemo(
() =>
file.groupIcon
@@ -104,11 +154,34 @@ const FileManagerRowImpl = ({
return;
}
+ // Hand the precomputed subtree paths to the selection hook for directory
+ // rows: a plain or `Cmd`/`Ctrl`+click on a folder then operates on the
+ // entire branch — including descendants of a collapsed folder — instead
+ // of just the folder's own path.
+ onClick(event, file.path, file.isDir ? dirSubtreePaths : undefined);
+ };
+
+ // Double-click is the row's "open" gesture. For directories it expands or
+ // collapses (decoupling expansion from the single click keeps `Shift`/`Cmd`+click
+ // pure selection gestures and matches Finder/Explorer). For files it forwards
+ // to `onOpen` — typically wired to download / preview / open-in-tab. The
+ // chevron icon and arrow keys remain alternative ways to expand without selecting.
+ const handleRowDoubleClick = (event: ReactMouseEvent) => {
+ if (isClickInsideSkipZone(event.target)) {
+ return;
+ }
+
if (file.isDir) {
+ event.preventDefault();
onToggleExpand(file.path, isExpanded);
+
+ return;
}
- onClick(event, file.path);
+ if (onOpen) {
+ event.preventDefault();
+ onOpen(file);
+ }
};
const renderActionItem = (
@@ -189,6 +262,9 @@ const FileManagerRowImpl = ({
className={cn(
'group hover:bg-accent grid cursor-pointer items-center gap-3 px-3 py-1.5 transition-colors outline-none',
'focus-visible:bg-muted/70 focus-visible:ring-ring focus-visible:ring-1',
+ // `select-none` keeps double-click reserved for expand/collapse
+ // — without it the browser would highlight the row's text on dblclick.
+ 'select-none',
isSelected && 'bg-muted',
isDropTarget && 'bg-primary/10 ring-primary/40 ring-1 ring-inset',
// Ghost every row that's part of the in-flight drag (the grabbed row
@@ -205,6 +281,7 @@ const FileManagerRowImpl = ({
data-path={file.path}
draggable={isDraggable}
onClick={handleRowClick}
+ onDoubleClick={handleRowDoubleClick}
onDragEnd={dnd?.onDragEnd}
onDragEnter={dnd?.onDragEnter}
onDragLeave={dnd?.onDragLeave}
@@ -223,8 +300,15 @@ const FileManagerRowImpl = ({
>
<Checkbox
aria-label={`Select ${file.name}`}
- checked={isSelected}
- onCheckedChange={() => onToggleCheckbox(file.path)}
+ // Directories surface a tri-state value derived from their
+ // descendants; files (and edge cases without a precomputed
+ // value) fall back to the row's own selection flag.
+ checked={file.isDir ? (dirCheckboxState ?? isSelected) : isSelected}
+ // For folders we hand the precomputed subtree to the
+ // selection hook so one gesture flips the entire branch
+ // (the directory itself + every descendant); files just
+ // toggle their own path.
+ onCheckedChange={() => onToggleSelection(file.path, file.isDir ? dirSubtreePaths : undefined)}
/>
</span>
) : (
@@ -238,7 +322,7 @@ const FileManagerRowImpl = ({
{Array.from({ length: file.depth }, (_, i) => (
<span
aria-hidden="true"
- className="bg-border pointer-events-none absolute -inset-y-1.5 w-px"
+ className="bg-border pointer-events-none absolute -inset-y-1.75 w-px"
key={i}
style={{ left: `${i * 16 + 6}px` }}
/>
diff --git a/frontend/src/components/file-manager/file-manager-tree-node.tsx b/frontend/src/components/file-manager/file-manager-tree-node.tsx
index bb745521..b38a9435 100644
--- a/frontend/src/components/file-manager/file-manager-tree-node.tsx
+++ b/frontend/src/components/file-manager/file-manager-tree-node.tsx
@@ -1,5 +1,6 @@
-import { Fragment, type MouseEvent as ReactMouseEvent } from 'react';
+import { Fragment } from 'react';
+import type { FileManagerRowDisplay, FileManagerRowHandlers } from './file-manager-row';
import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';
import type { FileManagerNodeDndHandlers } from './use-file-manager-dnd';
@@ -10,22 +11,19 @@ interface FileManagerTreeNodeProps {
activeRowPath: null | string;
/** Returns drag/drop handlers for a node, or `null` when DnD is disabled. */
bindNodeDnd: (node: FileManagerInternalNode) => FileManagerNodeDndHandlers | null;
+ /** Pre-computed tri-state value per directory path; missing entries default to `false`. */
+ dirSelectionStates: ReadonlyMap<string, 'indeterminate' | boolean>;
+ /** Pre-computed subtree paths per directory path (the dir itself + descendants). */
+ dirSubtreePaths: ReadonlyMap<string, readonly string[]>;
+ /** Per-tree shared layout / i18n bundle. Forwarded as-is to every row. */
+ display: FileManagerRowDisplay;
expandedPaths: Set<string>;
- formatModified?: (modifiedAt: Date | string | undefined) => string;
- gridTemplate: string;
- hasActions: boolean;
- isCheckboxVisible: boolean;
- isModifiedVisible: boolean;
- isSizeVisible: boolean;
+ /** Per-tree shared callback bundle. Forwarded as-is to every row. */
+ handlers: FileManagerRowHandlers;
node: FileManagerInternalNode;
- onClick: (event: ReactMouseEvent, path: string) => void;
- onFocusRow: (path: string) => void;
- onToggleCheckbox: (path: string) => void;
- onToggleExpand: (path: string, wasExpanded: boolean) => void;
/** 1-based position of the node inside its parent's child list (for `aria-posinset`). */
posInSet: number;
- searchQuery?: string;
- selectedPaths: Set<string>;
+ selectedPaths: ReadonlySet<string>;
/** Total number of siblings the node is part of (for `aria-setsize`). */
setSize: number;
}
@@ -40,20 +38,13 @@ export const FileManagerTreeNode = ({
actions,
activeRowPath,
bindNodeDnd,
+ dirSelectionStates,
+ dirSubtreePaths,
+ display,
expandedPaths,
- formatModified,
- gridTemplate,
- hasActions,
- isCheckboxVisible,
- isModifiedVisible,
- isSizeVisible,
+ handlers,
node,
- onClick,
- onFocusRow,
- onToggleCheckbox,
- onToggleExpand,
posInSet,
- searchQuery,
selectedPaths,
setSize,
}: FileManagerTreeNodeProps) => {
@@ -62,27 +53,28 @@ export const FileManagerTreeNode = ({
const renderChildren = node.isDir && isExpanded && node.children.length > 0;
const dnd = bindNodeDnd(node);
+ // Pre-resolve tri-state + subtree paths per row: keeping the lookup outside
+ // the memoized `FileManagerRow` lets each row receive primitive/stable props
+ // (`'indeterminate' | true | false | undefined` plus a `Map`-stored array
+ // reference) so a selection change only re-renders the rows whose computed
+ // state actually flipped.
+ const dirCheckboxState = node.isDir ? (dirSelectionStates.get(node.path) ?? false) : undefined;
+ const subtreePaths = node.isDir ? dirSubtreePaths.get(node.path) : undefined;
+
return (
<Fragment>
<FileManagerRow
actions={actions}
activeRowPath={activeRowPath}
+ dirCheckboxState={dirCheckboxState}
+ dirSubtreePaths={subtreePaths}
+ display={display}
dnd={dnd}
file={node}
- formatModified={formatModified}
- gridTemplate={gridTemplate}
- hasActions={hasActions}
- isCheckboxVisible={isCheckboxVisible && !node.isGroupRoot}
+ handlers={handlers}
isExpanded={isExpanded}
- isModifiedVisible={isModifiedVisible}
isSelected={isSelected}
- isSizeVisible={isSizeVisible}
- onClick={onClick}
- onFocusRow={onFocusRow}
- onToggleCheckbox={onToggleCheckbox}
- onToggleExpand={onToggleExpand}
posInSet={posInSet}
- searchQuery={searchQuery}
setSize={setSize}
/>
{renderChildren &&
@@ -91,21 +83,14 @@ export const FileManagerTreeNode = ({
actions={actions}
activeRowPath={activeRowPath}
bindNodeDnd={bindNodeDnd}
+ dirSelectionStates={dirSelectionStates}
+ dirSubtreePaths={dirSubtreePaths}
+ display={display}
expandedPaths={expandedPaths}
- formatModified={formatModified}
- gridTemplate={gridTemplate}
- hasActions={hasActions}
- isCheckboxVisible={isCheckboxVisible}
- isModifiedVisible={isModifiedVisible}
- isSizeVisible={isSizeVisible}
+ handlers={handlers}
key={child.id}
node={child}
- onClick={onClick}
- onFocusRow={onFocusRow}
- onToggleCheckbox={onToggleCheckbox}
- onToggleExpand={onToggleExpand}
posInSet={index + 1}
- searchQuery={searchQuery}
selectedPaths={selectedPaths}
setSize={node.children.length}
/>
diff --git a/frontend/src/components/file-manager/file-manager-types.ts b/frontend/src/components/file-manager/file-manager-types.ts
index 0bc884ba..e51330ae 100644
--- a/frontend/src/components/file-manager/file-manager-types.ts
+++ b/frontend/src/components/file-manager/file-manager-types.ts
@@ -100,6 +100,14 @@ export interface FileManagerProps {
* the data (or rely on subscriptions) so the new positions become visible.
*/
onMoveItems?: (sources: FileNode[], destinationDir: string) => Promise<void> | void;
+ /**
+ * Fired when the user "opens" a *file* row via double-click or `Enter`. Directories
+ * are not passed through this callback; they always toggle expand/collapse on
+ * activation, mirroring Finder/Explorer semantics.
+ *
+ * Use it to wire downloads, in-app previews, or open-in-tab behavior.
+ */
+ onOpen?: (file: FileNode) => void;
/**
* Fires whenever the multi-selection changes. Use it from selection-only
* flows (e.g. resource pickers) where the parent owns its own confirm button
@@ -107,8 +115,11 @@ export interface FileManagerProps {
*
* The supplied callback is read through a ref, so it does not need to be
* memoized — only meaningful selection changes will trigger it.
+ *
+ * The Set is owned by the manager and must be treated as read-only —
+ * mutating it will desync the manager's internal state.
*/
- onSelectionChange?: (selectedPaths: Set<string>) => void;
+ onSelectionChange?: (selectedPaths: ReadonlySet<string>) => void;
/** Synthetic top-level groups (e.g. Uploads / Container). When omitted, root is flat. */
rootGroups?: FileManagerRootGroup[];
/** Search query and matching empty state. Provide `query` to enable filtering. */
diff --git a/frontend/src/components/file-manager/file-manager-utils.test.ts b/frontend/src/components/file-manager/file-manager-utils.test.ts
index 79cb1d4c..c251208b 100644
--- a/frontend/src/components/file-manager/file-manager-utils.test.ts
+++ b/frontend/src/components/file-manager/file-manager-utils.test.ts
@@ -3,22 +3,31 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { FileManagerInternalNode, FileManagerRootGroup, FileNode } from './file-manager-types';
import {
+ addAllToSet,
buildFileManagerGridTemplate,
buildFileManagerTree,
clamp,
collectAllFilePaths,
collectAllNodePaths,
collectDirectoryPaths,
+ collectSubtreePaths,
collectVisibleFlat,
+ computeDirSelectionState,
+ computeRowClickSelection,
+ computeToggleSelectAll,
+ computeToggleSelection,
dedupeOverlappingPaths,
filterFileManagerTree,
findNodeByPath,
formatFileSize,
formatModified,
getCheckboxState,
+ isEverySelected,
normalizeRootGroups,
pluralizeItemsEnglish,
+ removeAllFromSet,
resolveSelectionModifier,
+ toggleSubtreeOnSet,
walkTree,
} from './file-manager-utils';
@@ -383,6 +392,32 @@ describe('getCheckboxState', () => {
});
});
+describe('collectSubtreePaths', () => {
+ it('returns the directory itself plus every descendant', () => {
+ const tree = buildFileManagerTree([file('a/b/c.txt'), file('a/d.txt')]);
+ const root = tree[0]!; // 'a'
+
+ expect(collectSubtreePaths(root).sort()).toEqual(['a', 'a/b', 'a/b/c.txt', 'a/d.txt'].sort());
+ });
+
+ it('returns just the leaf path for a single file node', () => {
+ const tree = buildFileManagerTree([file('lonely.txt')]);
+
+ expect(collectSubtreePaths(tree[0]!)).toEqual(['lonely.txt']);
+ });
+
+ it('omits synthetic group roots but keeps their descendants', () => {
+ const tree = buildFileManagerTree(
+ [file('uploads/a.txt'), file('uploads/sub/b.txt')],
+ [{ id: 'u', label: 'Uploads', pathPrefix: 'uploads' }],
+ );
+ const groupRoot = tree[0]!;
+
+ expect(groupRoot.isGroupRoot).toBe(true);
+ expect(collectSubtreePaths(groupRoot).sort()).toEqual(['uploads/a.txt', 'uploads/sub', 'uploads/sub/b.txt']);
+ });
+});
+
describe('pluralizeItemsEnglish', () => {
it('uses singular for 1', () => {
expect(pluralizeItemsEnglish(1)).toBe('1 item');
@@ -393,3 +428,705 @@ describe('pluralizeItemsEnglish', () => {
expect(pluralizeItemsEnglish(5)).toBe('5 items');
});
});
+
+describe('addAllToSet', () => {
+ it('adds every path from the iterable into the set', () => {
+ const set = new Set(['a']);
+
+ addAllToSet(set, ['b', 'c']);
+
+ expect([...set].sort()).toEqual(['a', 'b', 'c']);
+ });
+
+ it('is a no-op for an empty iterable', () => {
+ const set = new Set(['a']);
+
+ addAllToSet(set, []);
+
+ expect([...set]).toEqual(['a']);
+ });
+
+ it('accepts another Set as the source', () => {
+ const set = new Set<string>();
+
+ addAllToSet(set, new Set(['x', 'y']));
+
+ expect([...set].sort()).toEqual(['x', 'y']);
+ });
+});
+
+describe('removeAllFromSet', () => {
+ it('removes every present path and ignores missing ones', () => {
+ const set = new Set(['a', 'b', 'c']);
+
+ removeAllFromSet(set, ['b', 'missing']);
+
+ expect([...set].sort()).toEqual(['a', 'c']);
+ });
+
+ it('is a no-op for an empty iterable', () => {
+ const set = new Set(['a']);
+
+ removeAllFromSet(set, []);
+
+ expect([...set]).toEqual(['a']);
+ });
+});
+
+describe('isEverySelected', () => {
+ it('returns true when every path is in the selected set', () => {
+ expect(isEverySelected(['a', 'b'], new Set(['a', 'b', 'c']))).toBe(true);
+ });
+
+ it('returns false when at least one path is missing', () => {
+ expect(isEverySelected(['a', 'b'], new Set(['a']))).toBe(false);
+ });
+
+ it('returns true (vacuously) for an empty iterable', () => {
+ expect(isEverySelected([], new Set())).toBe(true);
+ expect(isEverySelected([], new Set(['x']))).toBe(true);
+ });
+});
+
+describe('toggleSubtreeOnSet', () => {
+ it('adds every path when the subtree is fully unselected', () => {
+ expect([...toggleSubtreeOnSet(new Set(), ['a', 'a/b', 'a/c'])].sort()).toEqual(['a', 'a/b', 'a/c']);
+ });
+
+ it('adds the missing paths when the subtree is partially selected', () => {
+ expect([...toggleSubtreeOnSet(new Set(['a/b']), ['a', 'a/b', 'a/c'])].sort()).toEqual(['a', 'a/b', 'a/c']);
+ });
+
+ it('removes every path when the subtree is fully selected', () => {
+ expect([...toggleSubtreeOnSet(new Set(['a', 'a/b', 'a/c']), ['a', 'a/b', 'a/c'])]).toEqual([]);
+ });
+
+ it('preserves unrelated entries on both add and remove', () => {
+ expect([...toggleSubtreeOnSet(new Set(['x']), ['a', 'a/b'])].sort()).toEqual(['a', 'a/b', 'x']);
+ expect([...toggleSubtreeOnSet(new Set(['a', 'a/b', 'x']), ['a', 'a/b'])]).toEqual(['x']);
+ });
+
+ it('returns a freshly cloned Set (does not mutate input)', () => {
+ const prev = new Set(['x']);
+ const next = toggleSubtreeOnSet(prev, ['a']);
+
+ expect(next).not.toBe(prev);
+ expect([...prev]).toEqual(['x']);
+ });
+});
+
+describe('computeRowClickSelection — single modifier', () => {
+ it('replaces selection with [path] for a file row', () => {
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible: ['a', 'b', 'c'],
+ modifier: 'single',
+ path: 'b',
+ prev: new Set(['a', 'c']),
+ });
+
+ expect([...result.next]).toEqual(['b']);
+ expect(result.nextAnchor).toBe('b');
+ });
+
+ it('replaces selection with the whole subtree for a directory row', () => {
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible: ['dir', 'dir/a', 'dir/b'],
+ modifier: 'single',
+ path: 'dir',
+ prev: new Set(['unrelated']),
+ subtreePaths: ['dir', 'dir/a', 'dir/b'],
+ });
+
+ expect([...result.next].sort()).toEqual(['dir', 'dir/a', 'dir/b']);
+ expect(result.nextAnchor).toBe('dir');
+ });
+
+ it('treats an empty subtreePaths array as "no subtree" (defensive — never happens for real folders)', () => {
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible: ['p'],
+ modifier: 'single',
+ path: 'p',
+ prev: new Set(),
+ subtreePaths: [],
+ });
+
+ expect([...result.next]).toEqual(['p']);
+ expect(result.nextAnchor).toBe('p');
+ });
+});
+
+describe('computeRowClickSelection — toggle modifier', () => {
+ it('flips a file path on when not selected', () => {
+ const result = computeRowClickSelection({
+ anchor: 'a',
+ flatVisible: ['a', 'b', 'c'],
+ modifier: 'toggle',
+ path: 'b',
+ prev: new Set(['a']),
+ });
+
+ expect([...result.next].sort()).toEqual(['a', 'b']);
+ expect(result.nextAnchor).toBe('b');
+ });
+
+ it('flips a file path off when already selected', () => {
+ const result = computeRowClickSelection({
+ anchor: 'a',
+ flatVisible: ['a', 'b', 'c'],
+ modifier: 'toggle',
+ path: 'b',
+ prev: new Set(['a', 'b']),
+ });
+
+ expect([...result.next]).toEqual(['a']);
+ expect(result.nextAnchor).toBe('b');
+ });
+
+ it('all-or-nothing adds the whole branch for a partially selected directory', () => {
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible: ['dir', 'dir/a', 'dir/b'],
+ modifier: 'toggle',
+ path: 'dir',
+ prev: new Set(['dir/a', 'unrelated']),
+ subtreePaths: ['dir', 'dir/a', 'dir/b'],
+ });
+
+ expect([...result.next].sort()).toEqual(['dir', 'dir/a', 'dir/b', 'unrelated']);
+ expect(result.nextAnchor).toBe('dir');
+ });
+
+ it('all-or-nothing strips the whole branch for a fully selected directory', () => {
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible: ['dir', 'dir/a', 'dir/b'],
+ modifier: 'toggle',
+ path: 'dir',
+ prev: new Set(['dir', 'dir/a', 'dir/b', 'unrelated']),
+ subtreePaths: ['dir', 'dir/a', 'dir/b'],
+ });
+
+ expect([...result.next]).toEqual(['unrelated']);
+ expect(result.nextAnchor).toBe('dir');
+ });
+});
+
+describe('computeRowClickSelection — range modifier', () => {
+ const flatVisible = ['a', 'b', 'c', 'd', 'e'];
+
+ it('selects from anchor to target (forward)', () => {
+ const result = computeRowClickSelection({
+ anchor: 'b',
+ flatVisible,
+ modifier: 'range',
+ path: 'd',
+ prev: new Set(['a', 'b']),
+ });
+
+ expect([...result.next]).toEqual(['b', 'c', 'd']);
+ expect(result.nextAnchor).toBe('b');
+ });
+
+ it('selects from anchor to target (backward)', () => {
+ const result = computeRowClickSelection({
+ anchor: 'd',
+ flatVisible,
+ modifier: 'range',
+ path: 'b',
+ prev: new Set(['d']),
+ });
+
+ expect([...result.next]).toEqual(['b', 'c', 'd']);
+ expect(result.nextAnchor).toBe('d');
+ });
+
+ it('replaces previous selection (does not extend it)', () => {
+ const result = computeRowClickSelection({
+ anchor: 'c',
+ flatVisible,
+ modifier: 'range',
+ path: 'e',
+ prev: new Set(['a']),
+ });
+
+ expect([...result.next]).toEqual(['c', 'd', 'e']);
+ expect(result.nextAnchor).toBe('c');
+ });
+
+ it('reduces to a single-row selection when anchor === target', () => {
+ const result = computeRowClickSelection({
+ anchor: 'c',
+ flatVisible,
+ modifier: 'range',
+ path: 'c',
+ prev: new Set(),
+ });
+
+ expect([...result.next]).toEqual(['c']);
+ expect(result.nextAnchor).toBe('c');
+ });
+
+ it('falls back to "single" when no anchor is set yet (and moves the anchor)', () => {
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible,
+ modifier: 'range',
+ path: 'c',
+ prev: new Set(['a']),
+ });
+
+ expect([...result.next]).toEqual(['c']);
+ expect(result.nextAnchor).toBe('c');
+ });
+
+ it('falls back to "single" when the anchor is no longer visible (and PRESERVES the anchor)', () => {
+ // Scenario: user cmd-clicked `dir/a`, then collapsed `dir`. The anchor
+ // is now off-screen but should not be silently overwritten — a follow-up
+ // shift-click after re-expanding the dir should still extend from there.
+ const result = computeRowClickSelection({
+ anchor: 'dir/a',
+ flatVisible: ['dir', 'other'],
+ modifier: 'range',
+ path: 'other',
+ prev: new Set(['dir/a']),
+ });
+
+ expect([...result.next]).toEqual(['other']);
+ expect(result.nextAnchor).toBe('dir/a');
+ });
+
+ it('falls back to "single" when the target is not in flatVisible (defensive)', () => {
+ const result = computeRowClickSelection({
+ anchor: 'a',
+ flatVisible,
+ modifier: 'range',
+ path: 'ghost',
+ prev: new Set(['a']),
+ });
+
+ expect([...result.next]).toEqual(['ghost']);
+ expect(result.nextAnchor).toBe('a');
+ });
+
+ it('range click on a directory uses flatVisible (not subtreePaths) when anchor is valid', () => {
+ // The directory's own subtree is irrelevant for range clicks — only the
+ // visible-order span matters, mirroring Finder/Explorer.
+ const result = computeRowClickSelection({
+ anchor: 'a',
+ flatVisible: ['a', 'b', 'dir', 'e'],
+ modifier: 'range',
+ path: 'dir',
+ prev: new Set(['a']),
+ subtreePaths: ['dir', 'dir/x', 'dir/y'],
+ });
+
+ expect([...result.next]).toEqual(['a', 'b', 'dir']);
+ expect(result.nextAnchor).toBe('a');
+ });
+});
+
+describe('computeRowClickSelection — anchor stability across chained clicks', () => {
+ const flatVisible = ['a', 'b', 'c', 'd', 'e'];
+
+ it('chained shift-click extends from the same anchor (anchor is preserved)', () => {
+ // Step 1: single click on 'b' → anchor = 'b'
+ const step1 = computeRowClickSelection({
+ anchor: null,
+ flatVisible,
+ modifier: 'single',
+ path: 'b',
+ prev: new Set(),
+ });
+
+ expect(step1.nextAnchor).toBe('b');
+
+ // Step 2: shift-click on 'd' → range b..d, anchor still 'b'
+ const step2 = computeRowClickSelection({
+ anchor: step1.nextAnchor,
+ flatVisible,
+ modifier: 'range',
+ path: 'd',
+ prev: step1.next,
+ });
+
+ expect([...step2.next]).toEqual(['b', 'c', 'd']);
+ expect(step2.nextAnchor).toBe('b');
+
+ // Step 3: shift-click on 'e' → range b..e, anchor still 'b'
+ const step3 = computeRowClickSelection({
+ anchor: step2.nextAnchor,
+ flatVisible,
+ modifier: 'range',
+ path: 'e',
+ prev: step2.next,
+ });
+
+ expect([...step3.next]).toEqual(['b', 'c', 'd', 'e']);
+ expect(step3.nextAnchor).toBe('b');
+ });
+
+ it('toggle click moves the anchor (so subsequent shift-click extends from the new origin)', () => {
+ // single 'a' → anchor 'a'; toggle 'c' → anchor 'c'; shift 'd' → c..d
+ const s1 = computeRowClickSelection({
+ anchor: null,
+ flatVisible,
+ modifier: 'single',
+ path: 'a',
+ prev: new Set(),
+ });
+ const s2 = computeRowClickSelection({
+ anchor: s1.nextAnchor,
+ flatVisible,
+ modifier: 'toggle',
+ path: 'c',
+ prev: s1.next,
+ });
+ const s3 = computeRowClickSelection({
+ anchor: s2.nextAnchor,
+ flatVisible,
+ modifier: 'range',
+ path: 'd',
+ prev: s2.next,
+ });
+
+ expect([...s3.next]).toEqual(['c', 'd']);
+ expect(s3.nextAnchor).toBe('c');
+ });
+
+ it('plain (single) click clears any existing multi-selection and resets the anchor', () => {
+ const cmdA = computeRowClickSelection({
+ anchor: null,
+ flatVisible,
+ modifier: 'toggle',
+ path: 'a',
+ prev: new Set(),
+ });
+ const cmdC = computeRowClickSelection({
+ anchor: cmdA.nextAnchor,
+ flatVisible,
+ modifier: 'toggle',
+ path: 'c',
+ prev: cmdA.next,
+ });
+
+ expect([...cmdC.next].sort()).toEqual(['a', 'c']);
+
+ const plainE = computeRowClickSelection({
+ anchor: cmdC.nextAnchor,
+ flatVisible,
+ modifier: 'single',
+ path: 'e',
+ prev: cmdC.next,
+ });
+
+ expect([...plainE.next]).toEqual(['e']);
+ expect(plainE.nextAnchor).toBe('e');
+ });
+});
+
+describe('computeRowClickSelection — purity', () => {
+ it('never mutates the input prev Set', () => {
+ const prev = new Set(['a']);
+ const snapshot = [...prev];
+
+ computeRowClickSelection({
+ anchor: 'a',
+ flatVisible: ['a', 'b'],
+ modifier: 'toggle',
+ path: 'b',
+ prev,
+ });
+
+ expect([...prev]).toEqual(snapshot);
+ });
+
+ it('returns a freshly allocated Set on every call', () => {
+ const prev = new Set(['a']);
+ const result = computeRowClickSelection({
+ anchor: null,
+ flatVisible: ['a', 'b'],
+ modifier: 'single',
+ path: 'b',
+ prev,
+ });
+
+ expect(result.next).not.toBe(prev);
+ });
+});
+
+describe('computeToggleSelection (Space / row checkbox)', () => {
+ it('flips a file path on/off', () => {
+ expect([...computeToggleSelection({ path: 'a', prev: new Set() })]).toEqual(['a']);
+ expect([...computeToggleSelection({ path: 'a', prev: new Set(['a']) })]).toEqual([]);
+ });
+
+ it('all-or-nothing for a directory subtree', () => {
+ // partial → fully selected
+ expect(
+ [
+ ...computeToggleSelection({
+ path: 'dir',
+ prev: new Set(['dir/a']),
+ subtreePaths: ['dir', 'dir/a', 'dir/b'],
+ }),
+ ].sort(),
+ ).toEqual(['dir', 'dir/a', 'dir/b']);
+
+ // fully selected → cleared
+ expect(
+ [
+ ...computeToggleSelection({
+ path: 'dir',
+ prev: new Set(['dir', 'dir/a', 'dir/b']),
+ subtreePaths: ['dir', 'dir/a', 'dir/b'],
+ }),
+ ],
+ ).toEqual([]);
+ });
+
+ it('preserves unrelated paths on subtree toggle', () => {
+ expect(
+ [
+ ...computeToggleSelection({
+ path: 'dir',
+ prev: new Set(['dir', 'dir/a', 'dir/b', 'x']),
+ subtreePaths: ['dir', 'dir/a', 'dir/b'],
+ }),
+ ],
+ ).toEqual(['x']);
+ });
+
+ it('treats empty subtreePaths as "single path" (defensive)', () => {
+ expect([...computeToggleSelection({ path: 'a', prev: new Set(), subtreePaths: [] })]).toEqual(['a']);
+ });
+});
+
+describe('computeToggleSelectAll', () => {
+ it('selects every path when nothing is selected', () => {
+ expect([...computeToggleSelectAll({ allSelectablePaths: ['a', 'b', 'c'], prev: new Set() })].sort()).toEqual([
+ 'a',
+ 'b',
+ 'c',
+ ]);
+ });
+
+ it('selects every path when the selection is partial (some-selected state)', () => {
+ expect(
+ [...computeToggleSelectAll({ allSelectablePaths: ['a', 'b', 'c'], prev: new Set(['a']) })].sort(),
+ ).toEqual(['a', 'b', 'c']);
+ });
+
+ it('clears the selection when everything is already selected', () => {
+ expect([
+ ...computeToggleSelectAll({ allSelectablePaths: ['a', 'b'], prev: new Set(['a', 'b']) }),
+ ]).toEqual([]);
+ });
+
+ it('returns an empty Set when the universe is empty (no selectable paths)', () => {
+ expect([...computeToggleSelectAll({ allSelectablePaths: [], prev: new Set() })]).toEqual([]);
+ expect([...computeToggleSelectAll({ allSelectablePaths: [], prev: new Set(['stale']) })]).toEqual([]);
+ });
+
+ it('returns a freshly allocated Set (never mutates prev)', () => {
+ const prev = new Set(['a']);
+ const result = computeToggleSelectAll({ allSelectablePaths: ['a', 'b'], prev });
+
+ expect(result).not.toBe(prev);
+ expect([...prev]).toEqual(['a']);
+ });
+});
+
+describe('computeDirSelectionState — non-empty directory', () => {
+ // Subtree paths convention: the directory's own path always comes first,
+ // descendants follow. `dirSubtreePaths` in `FileManager` builds it via
+ // `collectSubtreePaths(node)` — same shape.
+ const paths = ['dir', 'dir/a', 'dir/b'];
+
+ it('returns false when nothing inside is selected', () => {
+ expect(computeDirSelectionState({ path: 'dir', paths, selectedPaths: new Set() })).toBe(false);
+ });
+
+ it('returns true when every descendant is selected (and the dir itself happens to be too)', () => {
+ expect(
+ computeDirSelectionState({
+ path: 'dir',
+ paths,
+ selectedPaths: new Set(['dir', 'dir/a', 'dir/b']),
+ }),
+ ).toBe(true);
+ });
+
+ it('returns true when every descendant is selected even WITHOUT the dir in selectedPaths', () => {
+ // Confirms the count is purely descendant-based.
+ expect(
+ computeDirSelectionState({
+ path: 'dir',
+ paths,
+ selectedPaths: new Set(['dir/a', 'dir/b']),
+ }),
+ ).toBe(true);
+ });
+
+ it('returns indeterminate when only some descendants are selected', () => {
+ expect(
+ computeDirSelectionState({
+ path: 'dir',
+ paths,
+ selectedPaths: new Set(['dir/a']),
+ }),
+ ).toBe('indeterminate');
+ });
+
+ it('returns indeterminate when the dir itself + some descendants are selected', () => {
+ expect(
+ computeDirSelectionState({
+ path: 'dir',
+ paths,
+ selectedPaths: new Set(['dir', 'dir/a']),
+ }),
+ ).toBe('indeterminate');
+ });
+
+ it('REGRESSION: returns false when ONLY the directory itself is selected (no descendants)', () => {
+ // Reproduces the bug where the user single-clicked a folder
+ // (selecting `{dir, dir/a, dir/b}`), then cmd-clicked away every child
+ // one by one — leaving just `{dir}` in the selection. Previously the
+ // checkbox stuck at "indeterminate" even though the folder's content
+ // was empty in the selection.
+ expect(
+ computeDirSelectionState({
+ path: 'dir',
+ paths,
+ selectedPaths: new Set(['dir']),
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('computeDirSelectionState — empty directory (no real descendants)', () => {
+ // For an empty folder the "subtree" is just the folder's own path.
+ const paths = ['empty'];
+
+ it('returns false when the empty folder is not selected', () => {
+ expect(computeDirSelectionState({ path: 'empty', paths, selectedPaths: new Set() })).toBe(false);
+ });
+
+ it('returns true when the empty folder is itself selected', () => {
+ expect(
+ computeDirSelectionState({
+ path: 'empty',
+ paths,
+ selectedPaths: new Set(['empty']),
+ }),
+ ).toBe(true);
+ });
+
+ it('never returns indeterminate for empty folders', () => {
+ // Edge case: `selectedPaths` contains an unrelated entry — empty folder
+ // must still resolve to a binary state.
+ expect(
+ computeDirSelectionState({
+ path: 'empty',
+ paths,
+ selectedPaths: new Set(['unrelated']),
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('computeDirSelectionState — nested hierarchy', () => {
+ // Real-world shape: outer/sub/file.txt
+ const outerPaths = ['outer', 'outer/sub', 'outer/sub/file.txt'];
+ const subPaths = ['outer/sub', 'outer/sub/file.txt'];
+
+ it('inner folder reflects only its own descendants (file)', () => {
+ expect(
+ computeDirSelectionState({
+ path: 'outer/sub',
+ paths: subPaths,
+ selectedPaths: new Set(['outer/sub/file.txt']),
+ }),
+ ).toBe(true);
+
+ expect(
+ computeDirSelectionState({
+ path: 'outer/sub',
+ paths: subPaths,
+ selectedPaths: new Set(),
+ }),
+ ).toBe(false);
+
+ // Inner folder itself selected, but file inside isn't → reflects content only.
+ expect(
+ computeDirSelectionState({
+ path: 'outer/sub',
+ paths: subPaths,
+ selectedPaths: new Set(['outer/sub']),
+ }),
+ ).toBe(false);
+ });
+
+ it('outer folder treats the inner folder + file as separate descendants', () => {
+ // Only the inner folder is selected (no file inside) → outer is indeterminate
+ // because something within outer (= the sub-dir) IS in the selection.
+ expect(
+ computeDirSelectionState({
+ path: 'outer',
+ paths: outerPaths,
+ selectedPaths: new Set(['outer/sub']),
+ }),
+ ).toBe('indeterminate');
+
+ // Both inner and file selected → outer becomes fully selected.
+ expect(
+ computeDirSelectionState({
+ path: 'outer',
+ paths: outerPaths,
+ selectedPaths: new Set(['outer/sub', 'outer/sub/file.txt']),
+ }),
+ ).toBe(true);
+ });
+
+ it('outer folder ignores its OWN path when counting (regression)', () => {
+ expect(
+ computeDirSelectionState({
+ path: 'outer',
+ paths: outerPaths,
+ selectedPaths: new Set(['outer']),
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('computeDirSelectionState — synthetic group root (path === "")', () => {
+ // Top-level group root has an empty path; children carry full paths.
+ // The reducer must treat the empty `path` correctly as "the group root".
+ const paths = ['', 'uploads/a.txt', 'uploads/b.txt'];
+
+ it('returns false when nothing inside the group is selected', () => {
+ expect(computeDirSelectionState({ path: '', paths, selectedPaths: new Set() })).toBe(false);
+ });
+
+ it('returns true when every child is selected', () => {
+ expect(
+ computeDirSelectionState({
+ path: '',
+ paths,
+ selectedPaths: new Set(['uploads/a.txt', 'uploads/b.txt']),
+ }),
+ ).toBe(true);
+ });
+
+ it('returns indeterminate when only some children are selected', () => {
+ expect(
+ computeDirSelectionState({
+ path: '',
+ paths,
+ selectedPaths: new Set(['uploads/a.txt']),
+ }),
+ ).toBe('indeterminate');
+ });
+});
diff --git a/frontend/src/components/file-manager/file-manager-utils.ts b/frontend/src/components/file-manager/file-manager-utils.ts
index df225fec..79f50ec6 100644
--- a/frontend/src/components/file-manager/file-manager-utils.ts
+++ b/frontend/src/components/file-manager/file-manager-utils.ts
@@ -389,5 +389,299 @@ export const getCheckboxState = (isAllSelected: boolean, isSomeSelected: boolean
return false;
};
+/**
+ * Collect the absolute paths of every selectable node in the subtree rooted at `node`,
+ * including `node` itself. Synthetic group roots are skipped (they aren't real files
+ * and have no usable path of their own — only their descendants count).
+ *
+ * Used by directory checkboxes to flip every nested item in one gesture and to
+ * derive the parent's tri-state value from the descendants' selection.
+ */
+export const collectSubtreePaths = (node: FileManagerInternalNode): string[] => {
+ const result: string[] = [];
+
+ const visit = (current: FileManagerInternalNode): void => {
+ if (!current.isGroupRoot) {
+ result.push(current.path);
+ }
+
+ for (const child of current.children) {
+ visit(child);
+ }
+ };
+
+ visit(node);
+
+ return result;
+};
+
/** Default English pluralization for "N item" / "N items". Override via `labels.pluralizeItems`. */
export const pluralizeItemsEnglish = (count: number): string => `${count} ${count === 1 ? 'item' : 'items'}`;
+
+/**
+ * Mutates `set` in place by adding every path from `paths`. Designed for "build a
+ * fresh `next` from `prev`, then add a batch" patterns inside `setState` updaters
+ * — never call on a state-owned Set directly.
+ */
+export const addAllToSet = (set: Set<string>, paths: Iterable<string>): void => {
+ for (const path of paths) {
+ set.add(path);
+ }
+};
+
+/**
+ * Mutates `set` in place by removing every path from `paths`. Same locality
+ * contract as `addAllToSet`: only meaningful on a freshly cloned Set.
+ */
+export const removeAllFromSet = (set: Set<string>, paths: Iterable<string>): void => {
+ for (const path of paths) {
+ set.delete(path);
+ }
+};
+
+/**
+ * Returns `true` when every path in `paths` is present in `selected`. Empty
+ * `paths` short-circuits to `true` (vacuous truth) — callers that want
+ * "non-empty AND all selected" must guard explicitly.
+ */
+export const isEverySelected = (paths: Iterable<string>, selected: ReadonlySet<string>): boolean => {
+ for (const path of paths) {
+ if (!selected.has(path)) {
+ return false;
+ }
+ }
+
+ return true;
+};
+
+/**
+ * Flip the membership of every path in `paths` against `prev` in lock-step:
+ * if every path is already selected, the whole batch is removed; otherwise
+ * the missing ones are added. Mirrors the directory-checkbox semantics.
+ *
+ * Always returns a freshly cloned Set so React's reference-equality bail-out
+ * still works for downstream memoized consumers.
+ */
+export const toggleSubtreeOnSet = (prev: ReadonlySet<string>, paths: readonly string[]): Set<string> => {
+ const next = new Set(prev);
+
+ if (isEverySelected(paths, next)) {
+ removeAllFromSet(next, paths);
+ } else {
+ addAllToSet(next, paths);
+ }
+
+ return next;
+};
+
+interface ComputeRowClickSelectionArgs {
+ /** Last-clicked path used as the range anchor. `null` when nothing has been clicked yet. */
+ anchor: null | string;
+ /** Visible nodes in DFS order; range modifier resolves anchor/target indices against this list. */
+ flatVisible: readonly string[];
+ modifier: 'range' | 'single' | 'toggle';
+ /** Path of the row that was clicked. */
+ path: string;
+ /** Current selection. Pure reducer — never mutated. */
+ prev: ReadonlySet<string>;
+ /**
+ * For directory rows: the directory's own path plus every descendant. Single
+ * and toggle modifiers operate on the whole branch; range modifier still
+ * defers to the visible-order anchor and uses `subtreePaths` only as the
+ * fallback payload when the range cannot be resolved.
+ */
+ subtreePaths?: readonly string[];
+}
+
+interface ComputeRowClickSelectionResult {
+ /** New selection Set (always freshly allocated). */
+ next: Set<string>;
+ /**
+ * Anchor to store for the next interaction. Returns the same `anchor` on
+ * a successful range click (so chained Shift+clicks keep extending from the
+ * same origin) and on a fallback range click (so the user's intent isn't
+ * accidentally overwritten when the original anchor scrolled off-screen).
+ */
+ nextAnchor: null | string;
+}
+
+/**
+ * Pure reducer that computes the new selection + anchor for a row-click
+ * gesture. Encapsulates the full single / toggle / range matrix so the React
+ * hook can stay a thin wrapper that just stores state. Tested directly without
+ * a React renderer.
+ *
+ * Behaviour summary:
+ * - **single**: replaces selection with `subtreePaths` (folders) or `[path]`
+ * (files). Anchor moves to `path`.
+ * - **toggle**: all-or-nothing flip of `subtreePaths` (folders) or single
+ * `path` (files). Anchor moves to `path`.
+ * - **range**: replaces selection with the slice of `flatVisible` between
+ * `anchor` and `path` (inclusive, direction-agnostic). Anchor is preserved.
+ * If `anchor` is `null` → behaves like `single` and moves the anchor.
+ * If either anchor or target is missing from `flatVisible` → falls back to
+ * a `single`-style replacement but preserves the anchor (the original
+ * reference point may still be valid once it scrolls back into view).
+ */
+export const computeRowClickSelection = ({
+ anchor,
+ flatVisible,
+ modifier,
+ path,
+ prev,
+ subtreePaths,
+}: ComputeRowClickSelectionArgs): ComputeRowClickSelectionResult => {
+ const hasSubtree = !!subtreePaths && subtreePaths.length > 0;
+ const buildReplacement = (): Set<string> =>
+ hasSubtree && subtreePaths ? new Set(subtreePaths) : new Set([path]);
+
+ if (modifier === 'single') {
+ return { next: buildReplacement(), nextAnchor: path };
+ }
+
+ if (modifier === 'toggle') {
+ if (hasSubtree && subtreePaths) {
+ return { next: toggleSubtreeOnSet(prev, subtreePaths), nextAnchor: path };
+ }
+
+ const next = new Set(prev);
+
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ }
+
+ return { next, nextAnchor: path };
+ }
+
+ if (!anchor) {
+ return { next: buildReplacement(), nextAnchor: path };
+ }
+
+ const fromIndex = flatVisible.indexOf(anchor);
+ const toIndex = flatVisible.indexOf(path);
+
+ if (fromIndex < 0 || toIndex < 0) {
+ return { next: buildReplacement(), nextAnchor: anchor };
+ }
+
+ const [startIndex, endIndex] = fromIndex <= toIndex ? [fromIndex, toIndex] : [toIndex, fromIndex];
+
+ return { next: new Set(flatVisible.slice(startIndex, endIndex + 1)), nextAnchor: anchor };
+};
+
+interface ComputeToggleSelectionArgs {
+ path: string;
+ prev: ReadonlySet<string>;
+ subtreePaths?: readonly string[];
+}
+
+/**
+ * Pure reducer behind `onToggleSelection` (row checkbox + Space key):
+ * - When `subtreePaths` is provided and non-empty → all-or-nothing flip of
+ * the whole branch (matches the directory checkbox semantics).
+ * - Otherwise → flip just `path`.
+ *
+ * The hook layer is responsible for updating the anchor — it always moves to
+ * `path` after a toggle, regardless of whether anything was added or removed.
+ */
+export const computeToggleSelection = ({ path, prev, subtreePaths }: ComputeToggleSelectionArgs): Set<string> => {
+ if (subtreePaths && subtreePaths.length > 0) {
+ return toggleSubtreeOnSet(prev, subtreePaths);
+ }
+
+ const next = new Set(prev);
+
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ }
+
+ return next;
+};
+
+interface ComputeToggleSelectAllArgs {
+ /** Universe of every selectable path in the current visible tree. */
+ allSelectablePaths: readonly string[];
+ prev: ReadonlySet<string>;
+}
+
+/**
+ * Pure reducer behind the header "select all" checkbox and Ctrl/Cmd+A:
+ * clears the selection when everything is currently selected, otherwise
+ * replaces it with the full universe. Empty universe yields an empty Set.
+ */
+export const computeToggleSelectAll = ({ allSelectablePaths, prev }: ComputeToggleSelectAllArgs): Set<string> => {
+ const isCurrentlyAllSelected = allSelectablePaths.length > 0 && prev.size === allSelectablePaths.length;
+
+ return isCurrentlyAllSelected ? new Set() : new Set(allSelectablePaths);
+};
+
+interface ComputeDirSelectionStateArgs {
+ /**
+ * Path of the directory itself. Excluded from the tri-state count — the
+ * checkbox should reflect *content* selection, not whether the directory
+ * itself happens to be in `selectedPaths` (which can legitimately be the
+ * case after the user toggled descendants off one by one).
+ */
+ path: string;
+ /**
+ * Pre-computed list of every selectable path in the directory's subtree —
+ * the directory's own path PLUS all descendants. Same array that powers
+ * the "toggle whole subtree" gesture; reusing it avoids re-walking the tree.
+ */
+ paths: readonly string[];
+ selectedPaths: ReadonlySet<string>;
+}
+
+/**
+ * Pure reducer for the directory checkbox tri-state. Treats the *content* as
+ * the source of truth:
+ *
+ * - **false** → no descendant is selected (regardless of whether the
+ * directory's own path is in `selectedPaths` — the row's hover/selected
+ * background still reflects that via `isSelected` on the row).
+ * - **'indeterminate'** → some, but not all, descendants are selected.
+ * - **true** → every descendant is selected.
+ *
+ * For an empty directory (no real descendants — e.g. an empty folder or a
+ * synthetic group root with no children), the tri-state mirrors the folder's
+ * own selection as a binary value, so an empty folder still shows checked
+ * when explicitly picked.
+ */
+export const computeDirSelectionState = ({
+ path,
+ paths,
+ selectedPaths,
+}: ComputeDirSelectionStateArgs): 'indeterminate' | boolean => {
+ let descendantsTotal = 0;
+ let descendantsSelected = 0;
+
+ for (const p of paths) {
+ if (p === path) {
+ continue;
+ }
+
+ descendantsTotal += 1;
+
+ if (selectedPaths.has(p)) {
+ descendantsSelected += 1;
+ }
+ }
+
+ if (descendantsTotal === 0) {
+ return selectedPaths.has(path);
+ }
+
+ if (descendantsSelected === 0) {
+ return false;
+ }
+
+ if (descendantsSelected === descendantsTotal) {
+ return true;
+ }
+
+ return 'indeterminate';
+};
diff --git a/frontend/src/components/file-manager/file-manager.tsx b/frontend/src/components/file-manager/file-manager.tsx
index 63be3e10..4b0cd0bf 100644
--- a/frontend/src/components/file-manager/file-manager.tsx
+++ b/frontend/src/components/file-manager/file-manager.tsx
@@ -3,21 +3,14 @@ import { type MouseEvent as ReactMouseEvent, useCallback, useEffect, useMemo, us
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
-import type { FileManagerAction, FileManagerProps } from './file-manager-types';
+import type { FileManagerRowDisplay, FileManagerRowHandlers } from './file-manager-row';
+import type { FileManagerAction, FileManagerProps, FileNode } from './file-manager-types';
import { FileManagerBulkActionsBar } from './file-manager-bulk-actions-bar';
import { FileManagerSkeleton } from './file-manager-skeleton';
import { FileManagerTreeNode } from './file-manager-tree-node';
-import {
- buildFileManagerGridTemplate,
- buildFileManagerTree,
- collectAllNodePaths,
- collectVisibleFlat,
- filterFileManagerTree,
- findNodeByPath,
- getCheckboxState,
- normalizeRootGroups,
-} from './file-manager-utils';
+import { collectVisibleFlat, computeDirSelectionState, findNodeByPath, getCheckboxState } from './file-manager-utils';
+import { useFileManagerData } from './use-file-manager-data';
import { useFileManagerDnd } from './use-file-manager-dnd';
import { useFileManagerExpansion } from './use-file-manager-expansion';
import { useFileManagerKeyboardNavigation } from './use-file-manager-keyboard';
@@ -36,26 +29,32 @@ export const FileManager = ({
labels,
onBulkDelete,
onMoveItems,
+ onOpen,
onSelectionChange,
rootGroups,
search,
}: FileManagerProps) => {
- const isSizeVisible = columns?.isSizeVisible ?? true;
- const isModifiedVisible = columns?.isModifiedVisible ?? true;
-
- const normalizedRootGroups = useMemo(() => normalizeRootGroups(rootGroups), [rootGroups]);
-
- const fullTree = useMemo(() => buildFileManagerTree(files, normalizedRootGroups), [files, normalizedRootGroups]);
-
- const trimmedSearch = search?.query?.trim() ?? '';
- const isFiltering = trimmedSearch.length > 0;
-
- const visibleTree = useMemo(
- () => (isFiltering ? filterFileManagerTree(fullTree, trimmedSearch) : fullTree),
- [fullTree, isFiltering, trimmedSearch],
- );
+ const isCheckboxVisible = enableSelection ?? !!onBulkDelete;
+ const hasActions = !!actions?.length;
- const allSelectablePaths = useMemo(() => collectAllNodePaths(visibleTree), [visibleTree]);
+ const {
+ allSelectablePaths,
+ dirSubtreePaths,
+ fullTree,
+ gridTemplate,
+ isFiltering,
+ isModifiedVisible,
+ isSizeVisible,
+ normalizedRootGroups,
+ trimmedSearch,
+ visibleTree,
+ } = useFileManagerData({
+ columns,
+ files,
+ hasActions,
+ rootGroups,
+ searchQuery: search?.query,
+ });
const { expandedPaths, toggleExpand } = useFileManagerExpansion({
isFiltering,
@@ -63,6 +62,9 @@ export const FileManager = ({
visibleTree,
});
+ // Owned by the host (not the data hook) because it depends on `expandedPaths`,
+ // which in turn depends on `visibleTree` from the data hook — moving it inside
+ // would form a circular hook dependency.
const flatVisible = useMemo(() => collectVisibleFlat(visibleTree, expandedPaths), [visibleTree, expandedPaths]);
const {
@@ -70,14 +72,29 @@ export const FileManager = ({
isAllSelected,
isSomeSelected,
onRowClick,
- onToggleCheckbox,
+ onToggleSelection,
selectedPaths,
setSelection,
toggleSelectAll,
} = useFileManagerSelection({ allSelectablePaths, flatVisible });
- const isCheckboxVisible = enableSelection ?? !!onBulkDelete;
- const hasActions = !!actions?.length;
+ // Tri-state checkbox values per directory: derived from `selectedPaths` so a
+ // single state change updates every parent checkbox in lock-step. The map is
+ // re-built whenever the selection or the tree shape changes; rows pull only
+ // their own value out of it (see `FileManagerTreeNode`) which keeps the
+ // memoized `FileManagerRow` from re-rendering for unrelated paths.
+ //
+ // Counting logic lives in `computeDirSelectionState` — see its JSDoc for
+ // why the directory's own path is excluded from the count.
+ const dirSelectionStates = useMemo(() => {
+ const map = new Map<string, 'indeterminate' | boolean>();
+
+ for (const [path, paths] of dirSubtreePaths) {
+ map.set(path, computeDirSelectionState({ path, paths, selectedPaths }));
+ }
+
+ return map;
+ }, [dirSubtreePaths, selectedPaths]);
// Report selection changes upstream without forcing parents to memoize the
// callback — stash it in a ref so the effect only re-fires when the actual
@@ -91,10 +108,19 @@ export const FileManager = ({
useEffect(() => {
onSelectionChangeRef.current?.(selectedPaths);
}, [selectedPaths]);
- const gridTemplate = useMemo(
- () => buildFileManagerGridTemplate(isSizeVisible, isModifiedVisible, hasActions),
- [hasActions, isModifiedVisible, isSizeVisible],
- );
+
+ // Same latest-ref pattern for `onOpen`: it bleeds into the keyboard handler's
+ // deps and through `TreeNode` → `Row`, so a non-memoized parent callback would
+ // otherwise invalidate the memo on every row whenever the parent re-renders.
+ const onOpenRef = useRef(onOpen);
+
+ useEffect(() => {
+ onOpenRef.current = onOpen;
+ }, [onOpen]);
+
+ const handleOpen = useCallback((file: FileNode) => {
+ onOpenRef.current?.(file);
+ }, []);
// ── roving tabindex / keyboard navigation ────────────────────────────────
const [activeRowPath, setActiveRowPath] = useState<null | string>(null);
@@ -130,10 +156,11 @@ export const FileManager = ({
focusRow,
isCheckboxVisible,
onClearSelection: clearSelection,
+ onOpen: handleOpen,
onSelectAll: toggleSelectAll,
onSetActiveRow: setActiveRowPath,
- onToggleCheckbox,
onToggleExpand: toggleExpand,
+ onToggleSelection,
resolvedActiveRow,
visibleTree,
});
@@ -154,6 +181,46 @@ export const FileManager = ({
[clearSelection],
);
+ // Pull labels resolution and search-query trim up to render-top so they can
+ // feed into `display` below. Both must be computed unconditionally — the
+ // memoization that follows is guarded by `Object.is` on each dep, so a
+ // missing `labels` prop ({} on every render) only invalidates `formatModified`
+ // when the inner reference actually changes.
+ const effectiveLabels = labels ?? {};
+ const formatModified = effectiveLabels.formatModified;
+ const effectiveActions = actions ?? EMPTY_ACTIONS;
+ const searchQuery = trimmedSearch || undefined;
+
+ // Bundle all per-tree-shared layout / i18n props into a single object so the
+ // memoized `FileManagerRow` only does one reference check (instead of seven
+ // primitive comparisons) on every parent re-render.
+ const display = useMemo<FileManagerRowDisplay>(
+ () => ({
+ formatModified,
+ gridTemplate,
+ hasActions,
+ isCheckboxVisible,
+ isModifiedVisible,
+ isSizeVisible,
+ searchQuery,
+ }),
+ [formatModified, gridTemplate, hasActions, isCheckboxVisible, isModifiedVisible, isSizeVisible, searchQuery],
+ );
+
+ // Same trick for callbacks. Every dep here is already stabilized through
+ // a ref or empty deps inside its source hook, so `handlers` is constructed
+ // exactly once per `FileManager` instance and never invalidates row memo.
+ const handlers = useMemo<FileManagerRowHandlers>(
+ () => ({
+ onClick: onRowClick,
+ onFocusRow: handleRowFocus,
+ onOpen: handleOpen,
+ onToggleExpand: toggleExpand,
+ onToggleSelection,
+ }),
+ [handleOpen, handleRowFocus, onRowClick, onToggleSelection, toggleExpand],
+ );
+
if (isLoading) {
return (
<div className={className}>
@@ -174,10 +241,6 @@ export const FileManager = ({
return <div className={className}>{search?.emptyState ?? emptyState}</div>;
}
- const effectiveActions = actions ?? EMPTY_ACTIONS;
- const effectiveLabels = labels ?? {};
- const formatModified = effectiveLabels.formatModified;
-
return (
<div
className={cn('bg-card flex flex-col overflow-hidden rounded-lg border', className)}
@@ -236,21 +299,14 @@ export const FileManager = ({
actions={effectiveActions}
activeRowPath={resolvedActiveRow}
bindNodeDnd={dnd.bindNodeDnd}
+ dirSelectionStates={dirSelectionStates}
+ dirSubtreePaths={dirSubtreePaths}
+ display={display}
expandedPaths={expandedPaths}
- formatModified={formatModified}
- gridTemplate={gridTemplate}
- hasActions={hasActions}
- isCheckboxVisible={isCheckboxVisible}
- isModifiedVisible={isModifiedVisible}
- isSizeVisible={isSizeVisible}
+ handlers={handlers}
key={node.id}
node={node}
- onClick={onRowClick}
- onFocusRow={handleRowFocus}
- onToggleCheckbox={onToggleCheckbox}
- onToggleExpand={toggleExpand}
posInSet={index + 1}
- searchQuery={trimmedSearch || undefined}
selectedPaths={selectedPaths}
setSize={visibleTree.length}
/>
diff --git a/frontend/src/components/file-manager/use-file-manager-data.ts b/frontend/src/components/file-manager/use-file-manager-data.ts
new file mode 100644
index 00000000..dbaffb8b
--- /dev/null
+++ b/frontend/src/components/file-manager/use-file-manager-data.ts
@@ -0,0 +1,150 @@
+import { useMemo } from 'react';
+
+import type {
+ FileManagerColumnsConfig,
+ FileManagerInternalNode,
+ FileManagerRootGroup,
+ FileNode,
+} from './file-manager-types';
+
+import {
+ buildFileManagerGridTemplate,
+ buildFileManagerTree,
+ collectAllNodePaths,
+ collectSubtreePaths,
+ filterFileManagerTree,
+ normalizeRootGroups,
+} from './file-manager-utils';
+
+interface UseFileManagerDataArgs {
+ columns: FileManagerColumnsConfig | undefined;
+ files: FileNode[];
+ /**
+ * Whether the manager will render an actions column. Pulled from props by
+ * the caller so the column-template stays in lock-step with the row layout
+ * — `FileManager` and the row component must agree on the same `gridTemplate`.
+ */
+ hasActions: boolean;
+ rootGroups: FileManagerRootGroup[] | undefined;
+ /** Raw `search.query` from props; trimming and emptiness checks live inside the hook. */
+ searchQuery: string | undefined;
+}
+
+interface UseFileManagerDataResult {
+ /**
+ * Universe of selectable paths (files + real directories) in the *visible*
+ * tree, in DFS order. Used as the source of truth for "select all" and for
+ * pruning stale selection entries when the file list changes.
+ */
+ allSelectablePaths: string[];
+ /**
+ * Pre-computed list of every selectable path in each directory's subtree
+ * (the directory itself plus all descendants). Keyed by directory path.
+ * Powers both the tri-state checkbox value and the "toggle whole subtree"
+ * gesture without re-walking the tree on every render.
+ */
+ dirSubtreePaths: Map<string, readonly string[]>;
+ /**
+ * Full tree built from the input files (groups expanded, parent placeholders
+ * filled). Required by drag-and-drop's `findNode` which needs every node,
+ * including those filtered out of the visible tree by the search query.
+ */
+ fullTree: FileManagerInternalNode[];
+ /** CSS `grid-template-columns` value shared by the header and every row. */
+ gridTemplate: string;
+ /** True when a non-empty search query is active. Drives auto-expand-on-search. */
+ isFiltering: boolean;
+ isModifiedVisible: boolean;
+ isSizeVisible: boolean;
+ /**
+ * Normalized version of `rootGroups` (trailing slashes stripped). Returned
+ * even when the result is reference-equal to the input, so consumers can
+ * treat the value as the canonical group list.
+ */
+ normalizedRootGroups: FileManagerRootGroup[] | undefined;
+ /** Trimmed search query (`''` when missing or whitespace-only). */
+ trimmedSearch: string;
+ /**
+ * The tree as the user actually sees it — same shape as `fullTree` when no
+ * filter is active, otherwise narrowed to nodes matching the search query
+ * (with their ancestors and descendants kept).
+ */
+ visibleTree: FileManagerInternalNode[];
+}
+
+/**
+ * Pure, memoized data layer for `FileManager`. Owns the full chain
+ * `files → tree → visibleTree → derived collections (paths, subtree map, grid template)`
+ * so the host component is free to focus on wiring (selection / expansion /
+ * keyboard / DnD hooks) and rendering.
+ *
+ * `flatVisible` is intentionally NOT returned here — it depends on
+ * `expandedPaths`, which depends on `visibleTree`, which depends on this hook.
+ * Computing it inside would force a circular dependency between the data hook
+ * and the expansion hook. The host derives it with a single `useMemo`.
+ */
+export const useFileManagerData = ({
+ columns,
+ files,
+ hasActions,
+ rootGroups,
+ searchQuery,
+}: UseFileManagerDataArgs): UseFileManagerDataResult => {
+ const isSizeVisible = columns?.isSizeVisible ?? true;
+ const isModifiedVisible = columns?.isModifiedVisible ?? true;
+
+ const normalizedRootGroups = useMemo(() => normalizeRootGroups(rootGroups), [rootGroups]);
+
+ const fullTree = useMemo(() => buildFileManagerTree(files, normalizedRootGroups), [files, normalizedRootGroups]);
+
+ const trimmedSearch = searchQuery?.trim() ?? '';
+ const isFiltering = trimmedSearch.length > 0;
+
+ const visibleTree = useMemo(
+ () => (isFiltering ? filterFileManagerTree(fullTree, trimmedSearch) : fullTree),
+ [fullTree, isFiltering, trimmedSearch],
+ );
+
+ const allSelectablePaths = useMemo(() => collectAllNodePaths(visibleTree), [visibleTree]);
+
+ // Pre-compute the subtree path list for every directory (and group root) once
+ // per tree shape: this powers both the tri-state checkbox value and the
+ // "toggle whole subtree" gesture without re-walking the tree on every render.
+ const dirSubtreePaths = useMemo(() => {
+ const map = new Map<string, readonly string[]>();
+
+ const visit = (nodes: FileManagerInternalNode[]): void => {
+ for (const node of nodes) {
+ if (node.isDir || node.isGroupRoot) {
+ map.set(node.path, collectSubtreePaths(node));
+ }
+
+ if (node.children.length > 0) {
+ visit(node.children);
+ }
+ }
+ };
+
+ visit(visibleTree);
+
+ return map;
+ }, [visibleTree]);
+
+ const gridTemplate = useMemo(
+ () => buildFileManagerGridTemplate(isSizeVisible, isModifiedVisible, hasActions),
+ [hasActions, isModifiedVisible, isSizeVisible],
+ );
+
+ return {
+ allSelectablePaths,
+ dirSubtreePaths,
+ fullTree,
+ gridTemplate,
+ isFiltering,
+ isModifiedVisible,
+ isSizeVisible,
+ normalizedRootGroups,
+ trimmedSearch,
+ visibleTree,
+ };
+};
diff --git a/frontend/src/components/file-manager/use-file-manager-dnd.ts b/frontend/src/components/file-manager/use-file-manager-dnd.ts
index b5b9b684..38d8e4a6 100644
--- a/frontend/src/components/file-manager/use-file-manager-dnd.ts
+++ b/frontend/src/components/file-manager/use-file-manager-dnd.ts
@@ -116,6 +116,49 @@ const isFmDragEvent = (event: ReactDragEvent<HTMLDivElement>): boolean =>
const isRootPassthrough = (node: FileManagerInternalNode): boolean =>
!node.isDir && !node.isGroupRoot && getParentDir(node.path) === '';
+/**
+ * Resolves the *effective* destination directory a drop on this row should land in:
+ *
+ * - real directory → the directory itself
+ * - file inside a real dir → the file's parent directory (so the entire folder
+ * feels like one drop zone, matching Finder/Explorer:
+ * anywhere you release inside a folder, the items
+ * land in that folder regardless of the row under
+ * the cursor)
+ *
+ * Returns `null` for synthetic group roots and for files whose parent isn't a
+ * real, non-group directory (e.g. files sitting directly under a group header) —
+ * those rows stay inert. Top-level loose files are excluded earlier via
+ * `isRootPassthrough`, so this function never returns `''`; an empty parent
+ * just means "no findable real parent" and resolves to `null`.
+ */
+const resolveDropTargetDir = (
+ node: FileManagerInternalNode,
+ findNode: (path: string) => FileManagerInternalNode | undefined,
+): null | string => {
+ if (node.isGroupRoot) {
+ return null;
+ }
+
+ if (node.isDir) {
+ return node.path;
+ }
+
+ const parentDir = getParentDir(node.path);
+
+ if (parentDir === '') {
+ return null;
+ }
+
+ const parent = findNode(parentDir);
+
+ if (!parent || !parent.isDir || parent.isGroupRoot) {
+ return null;
+ }
+
+ return parentDir;
+};
+
/**
* Encapsulates the drag-counter pattern + path-set tracking used by `FileManager` for
* intra-tree move-via-drag. Scoped to a single `FileManager` instance — all intra-instance
@@ -124,6 +167,12 @@ const isRootPassthrough = (node: FileManagerInternalNode): boolean =>
* Row handlers stop event propagation so the container only sees drags over the empty
* (root) area. Counters live on `enter`/`leave` (per the W3C drag-counter pattern); drop
* targets are resolved on `over` only via `preventDefault`.
+ *
+ * File rows inside a folder transparently forward to the parent dir via
+ * `resolveDropTargetDir`, so dropping anywhere inside a folder (on its rows OR on
+ * the folder header) feels identical — matching Finder/Explorer. The parent's
+ * `dragenter` / a child file's `dragenter` write to the same counter, so moving
+ * the cursor between them keeps the highlight stable.
*/
export const useFileManagerDnd = ({
findNode,
@@ -263,10 +312,15 @@ export const useFileManagerDnd = ({
// as a drop into the empty (root) area and call the move API on release.
event.stopPropagation();
- const isValidDirTarget =
- node.isDir && !node.isGroupRoot && isValidMove(dragSourcesRef.current, node.path);
+ // Files inside a folder forward their drop logic to the parent dir
+ // (returned here by `resolveDropTargetDir`), so the user can release
+ // anywhere inside the folder and the items land in that folder —
+ // matching Finder/Explorer. The parent's row picks up the highlight
+ // automatically because every row compares `dropTargetPath` to its own
+ // `node.path`, and we set the parent's path here.
+ const targetDir = resolveDropTargetDir(node, findNode);
- if (!isValidDirTarget) {
+ if (targetDir === null || !isValidMove(dragSourcesRef.current, targetDir)) {
// Cursor is now over a non-droppable row — make sure the previously
// shown root highlight (if any) gets cleared. Container `dragleave`
// gates clearing on `relatedTarget` to avoid flicker, so the row
@@ -276,15 +330,18 @@ export const useFileManagerDnd = ({
return;
}
+ // Counter is keyed by `targetDir` so a folder row and any of its child
+ // file rows feed the SAME counter: moving the cursor between them keeps
+ // the highlight stable (W3C drag-counter pattern across siblings).
const counters = nodeCounterRef.current;
- const next = (counters.get(node.path) ?? 0) + 1;
- counters.set(node.path, next);
+ const next = (counters.get(targetDir) ?? 0) + 1;
+ counters.set(targetDir, next);
if (next === 1) {
- setDropTargetPath(node.path);
+ setDropTargetPath(targetDir);
}
},
- [isEnabled],
+ [findNode, isEnabled],
);
const handleNodeDragLeave = useCallback(
@@ -301,17 +358,31 @@ export const useFileManagerDnd = ({
event.stopPropagation();
+ // Decrement the same counter `dragenter` incremented — the resolved
+ // parent dir for file rows, the dir's own path for folder rows.
+ const targetDir = resolveDropTargetDir(node, findNode);
+
+ if (targetDir === null) {
+ return;
+ }
+
const counters = nodeCounterRef.current;
- const current = counters.get(node.path) ?? 0;
+ const current = counters.get(targetDir) ?? 0;
+
+ // Enter may have skipped incrementing (invalid move, pre-cleared root
+ // highlight branch) — nothing to undo in that case.
+ if (current === 0) {
+ return;
+ }
if (current <= 1) {
- counters.delete(node.path);
- setDropTargetPath((value) => (value === node.path ? null : value));
+ counters.delete(targetDir);
+ setDropTargetPath((value) => (value === targetDir ? null : value));
} else {
- counters.set(node.path, current - 1);
+ counters.set(targetDir, current - 1);
}
},
- [isEnabled],
+ [findNode, isEnabled],
);
const handleNodeDragOver = useCallback(
@@ -330,18 +401,16 @@ export const useFileManagerDnd = ({
// `preventDefault` on top of us and accept any row position as a root drop.
event.stopPropagation();
- if (!node.isDir || node.isGroupRoot) {
- return;
- }
+ const targetDir = resolveDropTargetDir(node, findNode);
- if (!isValidMove(dragSourcesRef.current, node.path)) {
+ if (targetDir === null || !isValidMove(dragSourcesRef.current, targetDir)) {
return;
}
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
},
- [isEnabled],
+ [findNode, isEnabled],
);
const handleNodeDrop = useCallback(
@@ -360,15 +429,10 @@ export const useFileManagerDnd = ({
// bug behind "drag a file, return it back" → unintended API call).
event.stopPropagation();
- if (!node.isDir || node.isGroupRoot) {
- resetDragState();
-
- return;
- }
-
const sources = dragSourcesRef.current;
+ const targetDir = resolveDropTargetDir(node, findNode);
- if (!isValidMove(sources, node.path)) {
+ if (targetDir === null || !isValidMove(sources, targetDir)) {
resetDragState();
return;
@@ -380,9 +444,9 @@ export const useFileManagerDnd = ({
// about to invalidate. Clear them so the bulk-actions bar / "select-all"
// checkbox don't show stale state.
onClearSelection?.();
- void onMoveItems?.(sources, node.path);
+ void onMoveItems?.(sources, targetDir);
},
- [isEnabled, onClearSelection, onMoveItems, resetDragState],
+ [findNode, isEnabled, onClearSelection, onMoveItems, resetDragState],
);
const bindNodeDnd = useCallback(
diff --git a/frontend/src/components/file-manager/use-file-manager-keyboard.ts b/frontend/src/components/file-manager/use-file-manager-keyboard.ts
index 66c42a15..7d23f2ea 100644
--- a/frontend/src/components/file-manager/use-file-manager-keyboard.ts
+++ b/frontend/src/components/file-manager/use-file-manager-keyboard.ts
@@ -1,8 +1,8 @@
import { type KeyboardEvent as ReactKeyboardEvent, useCallback } from 'react';
-import type { FileManagerInternalNode } from './file-manager-types';
+import type { FileManagerInternalNode, FileNode } from './file-manager-types';
-import { clamp, findNodeByPath } from './file-manager-utils';
+import { clamp, collectSubtreePaths, findNodeByPath } from './file-manager-utils';
interface UseFileManagerKeyboardNavigationArgs {
expandedPaths: Set<string>;
@@ -11,10 +11,13 @@ interface UseFileManagerKeyboardNavigationArgs {
focusRow: (path: null | string) => void;
isCheckboxVisible: boolean;
onClearSelection: () => void;
+ /** Open handler for file rows (Enter). Directories always toggle expand. */
+ onOpen?: (file: FileNode) => void;
onSelectAll: () => void;
onSetActiveRow: (path: null | string) => void;
- onToggleCheckbox: (path: string) => void;
onToggleExpand: (path: string, wasExpanded: boolean) => void;
+ /** Polymorphic selection toggle — same shape as the row checkbox handler. */
+ onToggleSelection: (path: string, subtreePaths?: readonly string[]) => void;
/** Currently focused row, or `null` if nothing is focused. */
resolvedActiveRow: null | string;
visibleTree: FileManagerInternalNode[];
@@ -23,7 +26,8 @@ interface UseFileManagerKeyboardNavigationArgs {
/**
* Keyboard handler implementing the WAI-ARIA Tree pattern:
* Arrow Up/Down → move focus, Home/End → jump to ends, Arrow Left/Right → collapse/expand
- * directories, Space → toggle the row's checkbox (only when checkboxes are shown),
+ * directories, Enter → expand/collapse a directory or fire `onOpen` for a file,
+ * Space → toggle the row's checkbox (only when checkboxes are shown),
* Ctrl/Cmd+A → select all, Escape → clear selection.
*/
export const useFileManagerKeyboardNavigation = ({
@@ -32,10 +36,11 @@ export const useFileManagerKeyboardNavigation = ({
focusRow,
isCheckboxVisible,
onClearSelection,
+ onOpen,
onSelectAll,
onSetActiveRow,
- onToggleCheckbox,
onToggleExpand,
+ onToggleSelection,
resolvedActiveRow,
visibleTree,
}: UseFileManagerKeyboardNavigationArgs) =>
@@ -62,14 +67,25 @@ export const useFileManagerKeyboardNavigation = ({
switch (event.key) {
case ' ':
- case 'Spacebar':
+ case 'Spacebar': {
event.preventDefault();
- if (isCheckboxVisible) {
- onToggleCheckbox(resolvedActiveRow);
+ if (!isCheckboxVisible) {
+ return;
}
+ // Mirror the click semantics of the row checkbox: pressing
+ // Space on a directory flips its whole subtree (the dir +
+ // every descendant), on a file it toggles just that path.
+ const node = findNodeByPath(visibleTree, resolvedActiveRow);
+ const subtreePaths =
+ node && (node.isDir || node.isGroupRoot) ? collectSubtreePaths(node) : undefined;
+
+ onToggleSelection(resolvedActiveRow, subtreePaths);
+
return;
+ }
+
case 'A':
case 'a':
if (event.ctrlKey || event.metaKey) {
@@ -112,6 +128,29 @@ export const useFileManagerKeyboardNavigation = ({
moveTo(flatVisible.length - 1);
return;
+ case 'Enter': {
+ const node = findNodeByPath(visibleTree, resolvedActiveRow);
+
+ if (!node) {
+ return;
+ }
+
+ // Always swallow Enter on a focused row so an enclosing form
+ // doesn't accidentally submit when the user just wanted to
+ // open a file or toggle a folder.
+ event.preventDefault();
+
+ if (node.isDir) {
+ onToggleExpand(node.path, expandedPaths.has(node.path));
+
+ return;
+ }
+
+ onOpen?.(node);
+
+ return;
+ }
+
case 'Home':
event.preventDefault();
moveTo(0);
@@ -127,10 +166,11 @@ export const useFileManagerKeyboardNavigation = ({
focusRow,
isCheckboxVisible,
onClearSelection,
+ onOpen,
onSelectAll,
onSetActiveRow,
- onToggleCheckbox,
onToggleExpand,
+ onToggleSelection,
resolvedActiveRow,
visibleTree,
],
diff --git a/frontend/src/components/file-manager/use-file-manager-selection.ts b/frontend/src/components/file-manager/use-file-manager-selection.ts
index 9133f64f..674ee4ab 100644
--- a/frontend/src/components/file-manager/use-file-manager-selection.ts
+++ b/frontend/src/components/file-manager/use-file-manager-selection.ts
@@ -1,6 +1,11 @@
-import { type MouseEvent as ReactMouseEvent, useCallback, useMemo, useRef, useState } from 'react';
+import { type MouseEvent as ReactMouseEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { resolveSelectionModifier } from './file-manager-utils';
+import {
+ computeRowClickSelection,
+ computeToggleSelectAll,
+ computeToggleSelection,
+ resolveSelectionModifier,
+} from './file-manager-utils';
interface UseFileManagerSelection {
clearSelection: () => void;
@@ -11,10 +16,28 @@ interface UseFileManagerSelection {
/**
* Click handler honoring single / toggle / range semantics.
* Range computed against the supplied `flatVisible` order.
+ *
+ * When `subtreePaths` is provided (always for directory rows — the directory's
+ * own path plus every descendant), the single / toggle modifiers operate on
+ * the whole branch instead of just the row's path. This means a plain click
+ * on a folder row replaces the selection with the entire subtree (matching
+ * what the folder's tri-state checkbox would do), even when the folder is
+ * collapsed and its descendants aren't currently rendered. Shift+click still
+ * defines a visible range — the anchor is reset to the folder itself.
*/
- onRowClick: (event: ReactMouseEvent, path: string) => void;
- /** Toggle a single path — used by checkboxes. */
- onToggleCheckbox: (path: string) => void;
+ onRowClick: (event: ReactMouseEvent, path: string, subtreePaths?: readonly string[]) => void;
+ /**
+ * Polymorphic toggle used by row checkboxes and the Space keyboard shortcut.
+ *
+ * - File rows / no `subtreePaths` → flip just `path`.
+ * - Directory rows pass the precomputed subtree (the directory itself plus
+ * every descendant) → all-or-nothing toggle of the whole branch: if every
+ * path is already selected the branch is cleared, otherwise the missing
+ * ones are added.
+ *
+ * `path` is also treated as the anchor for subsequent shift-range clicks.
+ */
+ onToggleSelection: (path: string, subtreePaths?: readonly string[]) => void;
selectedPaths: Set<string>;
/** Replace entire selection. */
setSelection: (paths: Set<string>) => void;
@@ -34,6 +57,12 @@ interface UseFileManagerSelectionArgs {
* after files change; we derive a pruned `selectedPaths` during render. The pruned
* Set keeps reference identity when nothing was stripped, so memoized consumers
* downstream don't re-render needlessly.
+ *
+ * All real selection logic lives in pure reducers inside `file-manager-utils`
+ * (`computeRowClickSelection`, `computeToggleSelection`, `computeToggleSelectAll`).
+ * The hook is a thin wrapper that owns the state Set, the anchor ref, and a few
+ * latest-ref pointers needed to keep the callbacks reference-stable across
+ * expand/collapse and tree-shape changes.
*/
export const useFileManagerSelection = ({
allSelectablePaths,
@@ -42,6 +71,24 @@ export const useFileManagerSelection = ({
const [rawSelectedPaths, setRawSelectedPaths] = useState<Set<string>>(() => new Set());
const lastClickedRef = useRef<null | string>(null);
+ // Stash the visible-order list and the universe of selectable paths in refs
+ // so the click and select-all callbacks can stay reference-stable across
+ // expand/collapse and tree-shape changes. Without this, `onRowClick` would
+ // be re-created on every expansion (its deps include `flatVisible`) and
+ // invalidate the `onClick` prop on every memoized row — kicking the entire
+ // tree into a re-render on the most common user gesture. Same pattern is
+ // already used in `use-file-manager-dnd` for `selectionRef`.
+ const flatVisibleRef = useRef(flatVisible);
+ const allSelectablePathsRef = useRef(allSelectablePaths);
+
+ useEffect(() => {
+ flatVisibleRef.current = flatVisible;
+ }, [flatVisible]);
+
+ useEffect(() => {
+ allSelectablePathsRef.current = allSelectablePaths;
+ }, [allSelectablePaths]);
+
const allSelectablePathsSet = useMemo(() => new Set(allSelectablePaths), [allSelectablePaths]);
const selectedPaths = useMemo(() => {
@@ -63,80 +110,50 @@ export const useFileManagerSelection = ({
return allValid ? rawSelectedPaths : valid;
}, [allSelectablePathsSet, rawSelectedPaths]);
- const onRowClick = useCallback(
- (event: ReactMouseEvent, path: string) => {
- const modifier = resolveSelectionModifier(event);
-
- if (modifier === 'single') {
- lastClickedRef.current = path;
- setRawSelectedPaths(new Set([path]));
-
- return;
- }
-
- if (modifier === 'toggle') {
- lastClickedRef.current = path;
- setRawSelectedPaths((prev) => {
- const next = new Set(prev);
-
- if (next.has(path)) {
- next.delete(path);
- } else {
- next.add(path);
- }
-
- return next;
- });
-
- return;
- }
-
- const anchor = lastClickedRef.current;
-
- if (!anchor) {
- lastClickedRef.current = path;
- setRawSelectedPaths(new Set([path]));
-
- return;
- }
-
- const fromIndex = flatVisible.indexOf(anchor);
- const toIndex = flatVisible.indexOf(path);
-
- if (fromIndex < 0 || toIndex < 0) {
- setRawSelectedPaths(new Set([path]));
-
- return;
- }
-
- const [startIndex, endIndex] = fromIndex <= toIndex ? [fromIndex, toIndex] : [toIndex, fromIndex];
+ const onRowClick = useCallback((event: ReactMouseEvent, path: string, subtreePaths?: readonly string[]) => {
+ const modifier = resolveSelectionModifier(event);
- setRawSelectedPaths(new Set(flatVisible.slice(startIndex, endIndex + 1)));
- },
- [flatVisible],
- );
-
- const onToggleCheckbox = useCallback((path: string) => {
- lastClickedRef.current = path;
setRawSelectedPaths((prev) => {
- const next = new Set(prev);
-
- if (next.has(path)) {
- next.delete(path);
- } else {
- next.add(path);
- }
+ const { next, nextAnchor } = computeRowClickSelection({
+ anchor: lastClickedRef.current,
+ flatVisible: flatVisibleRef.current,
+ modifier,
+ path,
+ prev,
+ subtreePaths,
+ });
+
+ // Storing into the ref from inside the updater is safe here: the
+ // updater is called with a fresh `prev` on each invocation but the
+ // anchor it produces depends only on `modifier`, `path`, the current
+ // ref values and the supplied `subtreePaths` — so even if React
+ // re-runs us in strict mode, every run computes the same `nextAnchor`.
+ lastClickedRef.current = nextAnchor;
return next;
});
}, []);
+ const onToggleSelection = useCallback((path: string, subtreePaths?: readonly string[]) => {
+ // Anchor follow-up shift-range clicks at the directory itself (or the
+ // file's own path), not at the deepest leaf — matches what users expect
+ // from Finder/Explorer.
+ lastClickedRef.current = path;
+
+ setRawSelectedPaths((prev) => computeToggleSelection({ path, prev, subtreePaths }));
+ }, []);
+
const isAllSelected = allSelectablePaths.length > 0 && selectedPaths.size === allSelectablePaths.length;
const isSomeSelected = selectedPaths.size > 0 && !isAllSelected;
+ // Functional setState reads the current selectable universe through the ref
+ // declared above, so the callback identity stays stable regardless of how
+ // many times the file list or selection changes.
const toggleSelectAll = useCallback(() => {
- setRawSelectedPaths(() => (isAllSelected ? new Set() : new Set(allSelectablePaths)));
- }, [allSelectablePaths, isAllSelected]);
+ setRawSelectedPaths((prev) =>
+ computeToggleSelectAll({ allSelectablePaths: allSelectablePathsRef.current, prev }),
+ );
+ }, []);
const clearSelection = useCallback(() => {
setRawSelectedPaths((prev) => (prev.size === 0 ? prev : new Set()));
@@ -151,7 +168,7 @@ export const useFileManagerSelection = ({
isAllSelected,
isSomeSelected,
onRowClick,
- onToggleCheckbox,
+ onToggleSelection,
selectedPaths,
setSelection,
toggleSelectAll,
diff --git a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
index b85979f2..6b786404 100644
--- a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
+++ b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
@@ -57,7 +57,7 @@ const FlowFilesAttachResourcesDialogBody = ({
return map;
}, [resources]);
- const handleSelectionChange = useCallback((next: Set<string>) => {
+ const handleSelectionChange = useCallback((next: ReadonlySet<string>) => {
setSelectedPaths(next);
}, []);
diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsx
index 9d021367..a8a751c3 100644
--- a/frontend/src/pages/resources/resources.tsx
+++ b/frontend/src/pages/resources/resources.tsx
@@ -83,6 +83,24 @@ const Resources = () => {
toast.error('Failed to copy path');
}, []);
+ /**
+ * "Open" gesture — fires on double-click or Enter for a file row.
+ * Triggers the same download the dropdown's Download action would, by clicking
+ * a transient `<a download>` element. We can't just `window.open()` here because
+ * we want the browser's `download` attribute hint (preserves the original
+ * filename even when the server sends `Content-Disposition: inline`).
+ */
+ const handleOpenFile = useCallback((file: FileNode) => {
+ const anchor = document.createElement('a');
+
+ anchor.href = buildResourceDownloadHref(file);
+ anchor.download = file.name;
+ anchor.rel = 'noopener';
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+ }, []);
+
const fileManagerActions = useMemo<FileManagerAction[]>(
() => [
downloadAction(buildResourceDownloadHref),
@@ -265,6 +283,7 @@ const Resources = () => {
isLoading={isInitialLoading}
onBulkDelete={deletion.deleteBulk}
onMoveItems={handleMoveItems}
+ onOpen={handleOpenFile}
search={{ emptyState: noMatchesState, query: search.debouncedQuery }}
/>