From 86799b479331eae64729d3522e877807addaf865 Mon Sep 17 00:00:00 2001 From: Colin Chambachan Date: Wed, 1 Apr 2026 12:36:52 -0400 Subject: [PATCH] feat: add file actions to file explorer (#235) Co-authored-by: Claude Opus 4.6 --- src/main/ipc/filesystem-mutations.test.ts | 228 ++++++++++++ src/main/ipc/filesystem-mutations.ts | 56 +++ src/main/ipc/filesystem.ts | 3 + src/preload/index.d.ts | 3 + src/preload/index.ts | 6 + .../components/right-sidebar/FileExplorer.tsx | 337 +++++++++--------- .../right-sidebar/FileExplorerRow.tsx | 183 +++++++++- .../src/components/right-sidebar/index.tsx | 2 +- .../useFileExplorerInlineInput.ts | 157 ++++++++ .../right-sidebar/useFileExplorerKeys.ts | 117 ++++++ .../right-sidebar/useFileExplorerTree.ts | 129 +++++++ 11 files changed, 1043 insertions(+), 178 deletions(-) create mode 100644 src/main/ipc/filesystem-mutations.test.ts create mode 100644 src/main/ipc/filesystem-mutations.ts create mode 100644 src/renderer/src/components/right-sidebar/useFileExplorerInlineInput.ts create mode 100644 src/renderer/src/components/right-sidebar/useFileExplorerKeys.ts create mode 100644 src/renderer/src/components/right-sidebar/useFileExplorerTree.ts diff --git a/src/main/ipc/filesystem-mutations.test.ts b/src/main/ipc/filesystem-mutations.test.ts new file mode 100644 index 000000000..1d8b8f371 --- /dev/null +++ b/src/main/ipc/filesystem-mutations.test.ts @@ -0,0 +1,228 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const handlers = new Map Promise>() +const { handleMock, lstatMock, mkdirMock, renameMock, writeFileMock, realpathMock } = vi.hoisted( + () => ({ + handleMock: vi.fn(), + lstatMock: vi.fn(), + mkdirMock: vi.fn(), + renameMock: vi.fn(), + writeFileMock: vi.fn(), + realpathMock: vi.fn() + }) +) + +vi.mock('electron', () => ({ + ipcMain: { handle: handleMock } +})) + +vi.mock('fs/promises', () => ({ + lstat: lstatMock, + mkdir: mkdirMock, + rename: renameMock, + writeFile: writeFileMock, + realpath: realpathMock +})) + +import { registerFilesystemMutationHandlers } from './filesystem-mutations' + +const store = { + getRepos: () => [ + { id: 'repo-1', path: '/workspace/repo', displayName: 'repo', badgeColor: '#000', addedAt: 0 } + ], + getSettings: () => ({ workspaceDir: '/workspace' }) +} + +function enoent(): Error { + return Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) +} + +function mockRealpath(mapping: Record) { + realpathMock.mockImplementation(async (p: string) => { + if (mapping[p]) { + return mapping[p] + } + return p + }) +} + +describe('registerFilesystemMutationHandlers', () => { + beforeEach(() => { + handlers.clear() + handleMock.mockReset() + lstatMock.mockReset() + mkdirMock.mockReset() + renameMock.mockReset() + writeFileMock.mockReset() + realpathMock.mockReset() + + handleMock.mockImplementation((channel: string, handler: never) => { + handlers.set(channel, handler) + }) + + // By default, paths resolve to themselves and targets don't exist yet + realpathMock.mockImplementation(async (p: string) => p) + lstatMock.mockRejectedValue(enoent()) + mkdirMock.mockResolvedValue(undefined) + writeFileMock.mockResolvedValue(undefined) + renameMock.mockResolvedValue(undefined) + + registerFilesystemMutationHandlers(store as never) + }) + + // ── fs:createFile ────────────────────────────────────────────── + + it('creates an empty file and its parent directories', async () => { + await handlers.get('fs:createFile')!(null, { filePath: '/workspace/repo/src/new.ts' }) + + expect(mkdirMock).toHaveBeenCalledWith('/workspace/repo/src', { recursive: true }) + expect(writeFileMock).toHaveBeenCalledWith('/workspace/repo/src/new.ts', '', { + encoding: 'utf-8', + flag: 'wx' + }) + }) + + it('rejects file creation when path already exists (wx flag)', async () => { + // The wx flag causes writeFile to throw EEXIST atomically, without a + // separate lstat check — no TOCTOU race. + writeFileMock.mockRejectedValue(Object.assign(new Error('EEXIST'), { code: 'EEXIST' })) + + await expect( + handlers.get('fs:createFile')!(null, { filePath: '/workspace/repo/existing.ts' }) + ).rejects.toThrow('EEXIST') + }) + + it('rejects file creation outside allowed roots', async () => { + mockRealpath({ + '/workspace/repo/link.ts': '/private/secret.ts' + }) + + await expect( + handlers.get('fs:createFile')!(null, { filePath: '/workspace/repo/link.ts' }) + ).rejects.toThrow('Access denied') + + expect(writeFileMock).not.toHaveBeenCalled() + }) + + // ── fs:createDir ─────────────────────────────────────────────── + + it('creates a directory recursively', async () => { + await handlers.get('fs:createDir')!(null, { dirPath: '/workspace/repo/src/components' }) + + expect(mkdirMock).toHaveBeenCalledWith('/workspace/repo/src/components', { recursive: true }) + }) + + it('rejects directory creation when path already exists', async () => { + lstatMock.mockResolvedValue({ isDirectory: () => true }) + + await expect( + handlers.get('fs:createDir')!(null, { dirPath: '/workspace/repo/src' }) + ).rejects.toThrow('A file or folder already exists at this path') + + expect(mkdirMock).not.toHaveBeenCalled() + }) + + it('rejects directory creation outside allowed roots', async () => { + mockRealpath({ + '/workspace/repo/escape': '/etc/evil' + }) + + await expect( + handlers.get('fs:createDir')!(null, { dirPath: '/workspace/repo/escape' }) + ).rejects.toThrow('Access denied') + + expect(mkdirMock).not.toHaveBeenCalled() + }) + + // ── fs:rename ────────────────────────────────────────────────── + + it('renames a file within the same directory', async () => { + await handlers.get('fs:rename')!(null, { + oldPath: '/workspace/repo/old.ts', + newPath: '/workspace/repo/new.ts' + }) + + expect(renameMock).toHaveBeenCalledWith('/workspace/repo/old.ts', '/workspace/repo/new.ts') + }) + + it('rejects rename when destination already exists', async () => { + lstatMock.mockImplementation(async (p: string) => { + if (p === '/workspace/repo/new.ts') { + return { isDirectory: () => false } + } + throw enoent() + }) + + await expect( + handlers.get('fs:rename')!(null, { + oldPath: '/workspace/repo/old.ts', + newPath: '/workspace/repo/new.ts' + }) + ).rejects.toThrow('A file or folder already exists at this path') + + expect(renameMock).not.toHaveBeenCalled() + }) + + it('rejects rename when new path escapes allowed roots', async () => { + mockRealpath({ + '/workspace/repo/escape.ts': '/private/escape.ts' + }) + + await expect( + handlers.get('fs:rename')!(null, { + oldPath: '/workspace/repo/old.ts', + newPath: '/workspace/repo/escape.ts' + }) + ).rejects.toThrow('Access denied') + + expect(renameMock).not.toHaveBeenCalled() + }) + + it('rejects rename when old path escapes allowed roots', async () => { + mockRealpath({ + '/workspace/repo/symlink.ts': '/private/secret.ts' + }) + + await expect( + handlers.get('fs:rename')!(null, { + oldPath: '/workspace/repo/symlink.ts', + newPath: '/workspace/repo/new.ts' + }) + ).rejects.toThrow('Access denied') + + expect(renameMock).not.toHaveBeenCalled() + }) + + // ── Edge cases ───────────────────────────────────────────────── + + it('propagates non-ENOENT lstat errors in assertNotExists', async () => { + lstatMock.mockRejectedValue(new Error('EPERM: operation not permitted')) + + await expect( + handlers.get('fs:createDir')!(null, { dirPath: '/workspace/repo/locked' }) + ).rejects.toThrow('EPERM') + + expect(mkdirMock).not.toHaveBeenCalled() + }) + + it('propagates mkdir permission errors for createFile', async () => { + mkdirMock.mockRejectedValue(new Error('EACCES: permission denied')) + + await expect( + handlers.get('fs:createFile')!(null, { filePath: '/workspace/repo/nowrite/file.ts' }) + ).rejects.toThrow('EACCES') + + expect(writeFileMock).not.toHaveBeenCalled() + }) + + it('propagates fs.rename errors (e.g. ENOENT when source missing)', async () => { + renameMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) + + await expect( + handlers.get('fs:rename')!(null, { + oldPath: '/workspace/repo/gone.ts', + newPath: '/workspace/repo/new.ts' + }) + ).rejects.toThrow('ENOENT') + }) +}) diff --git a/src/main/ipc/filesystem-mutations.ts b/src/main/ipc/filesystem-mutations.ts new file mode 100644 index 000000000..ce4ce1328 --- /dev/null +++ b/src/main/ipc/filesystem-mutations.ts @@ -0,0 +1,56 @@ +import { ipcMain } from 'electron' +import { lstat, mkdir, rename, writeFile } from 'fs/promises' +import { dirname } from 'path' +import type { Store } from '../persistence' +import { resolveAuthorizedPath, isENOENT } from './filesystem-auth' + +/** + * Ensure `targetPath` does not already exist. Throws if it does. + * + * Note: this is a non-atomic check — a concurrent operation could create the + * path between `lstat` and the caller's next action. Acceptable for a desktop + * app with low concurrency; `createFile` uses the `wx` flag for an atomic + * alternative where possible. + */ +async function assertNotExists(targetPath: string): Promise { + try { + await lstat(targetPath) + throw new Error('A file or folder already exists at this path') + } catch (error) { + if (!isENOENT(error)) { + throw error + } + } +} + +/** + * IPC handlers for file/folder creation and renaming. + * Deletion is handled separately via `fs:deletePath` (shell.trashItem). + */ +export function registerFilesystemMutationHandlers(store: Store): void { + ipcMain.handle('fs:createFile', async (_event, args: { filePath: string }): Promise => { + const filePath = await resolveAuthorizedPath(args.filePath, store) + await mkdir(dirname(filePath), { recursive: true }) + // Use the 'wx' flag for atomic create-if-not-exists, avoiding TOCTOU races + await writeFile(filePath, '', { encoding: 'utf-8', flag: 'wx' }) + }) + + ipcMain.handle('fs:createDir', async (_event, args: { dirPath: string }): Promise => { + const dirPath = await resolveAuthorizedPath(args.dirPath, store) + await assertNotExists(dirPath) + await mkdir(dirPath, { recursive: true }) + }) + + // Note: fs.rename throws EXDEV if old and new paths are on different + // filesystems/volumes. This is unlikely since both paths are under the same + // workspace root, but a cross-drive rename would surface as an IPC error. + ipcMain.handle( + 'fs:rename', + async (_event, args: { oldPath: string; newPath: string }): Promise => { + const oldPath = await resolveAuthorizedPath(args.oldPath, store) + const newPath = await resolveAuthorizedPath(args.newPath, store) + await assertNotExists(newPath) + await rename(oldPath, newPath) + } + ) +} diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 3bdd4a39c..36a3affad 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -33,6 +33,7 @@ import { isENOENT } from './filesystem-auth' import { listQuickOpenFiles } from './filesystem-list-files' +import { registerFilesystemMutationHandlers } from './filesystem-mutations' const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB const DEFAULT_SEARCH_MAX_RESULTS = 2000 @@ -147,6 +148,8 @@ export function registerFilesystemHandlers(store: Store): void { await shell.trashItem(targetPath) }) + registerFilesystemMutationHandlers(store) + ipcMain.handle( 'fs:stat', async ( diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 5276106a4..95f4dd15f 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -135,6 +135,9 @@ type FsApi = { filePath: string }) => Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }> writeFile: (args: { filePath: string; content: string }) => Promise + createFile: (args: { filePath: string }) => Promise + createDir: (args: { dirPath: string }) => Promise + rename: (args: { oldPath: string; newPath: string }) => Promise deletePath: (args: { targetPath: string }) => Promise stat: (args: { filePath: string diff --git a/src/preload/index.ts b/src/preload/index.ts index 56640ba74..a0c6b097b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -229,6 +229,12 @@ const api = { ipcRenderer.invoke('fs:readFile', args), writeFile: (args: { filePath: string; content: string }): Promise => ipcRenderer.invoke('fs:writeFile', args), + createFile: (args: { filePath: string }): Promise => + ipcRenderer.invoke('fs:createFile', args), + createDir: (args: { dirPath: string }): Promise => + ipcRenderer.invoke('fs:createDir', args), + rename: (args: { oldPath: string; newPath: string }): Promise => + ipcRenderer.invoke('fs:rename', args), deletePath: (args: { targetPath: string }): Promise => ipcRenderer.invoke('fs:deletePath', args), stat: (args: { diff --git a/src/renderer/src/components/right-sidebar/FileExplorer.tsx b/src/renderer/src/components/right-sidebar/FileExplorer.tsx index 059eb0945..20f5abb2d 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorer.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorer.tsx @@ -1,18 +1,26 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useVirtualizer } from '@tanstack/react-virtual' -import { Loader2 } from 'lucide-react' +import { FilePlus, FolderPlus, Loader2 } from 'lucide-react' import { useAppStore } from '@/store' import { detectLanguage } from '@/lib/language-detect' -import { joinPath, normalizeRelativePath } from '@/lib/path' +import { dirname, normalizeRelativePath } from '@/lib/path' import { ScrollArea } from '@/components/ui/scroll-area' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' import { FileDeleteDialog } from './FileDeleteDialog' -import { FileExplorerRow } from './FileExplorerRow' -import type { DirCache, TreeNode } from './file-explorer-types' +import { FileExplorerRow, InlineInputRow } from './FileExplorerRow' +import type { TreeNode } from './file-explorer-types' import { splitPathSegments } from './path-tree' -import { shouldIncludeFileExplorerEntry } from './file-explorer-entries' import { buildFolderStatusMap, buildStatusMap, STATUS_COLORS } from './status-display' import { useFileDeletion } from './useFileDeletion' import { useFileExplorerReveal } from './useFileExplorerReveal' +import { useFileExplorerInlineInput } from './useFileExplorerInlineInput' +import { useFileExplorerKeys } from './useFileExplorerKeys' +import { useFileExplorerTree } from './useFileExplorerTree' export default function FileExplorer(): React.JSX.Element { const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) @@ -32,22 +40,36 @@ export default function FileExplorer(): React.JSX.Element { if (!activeWorktreeId) { return null } - for (const worktrees of Object.values(worktreesByRepo)) { - const worktree = worktrees.find((candidate) => candidate.id === activeWorktreeId) - if (worktree) { - return worktree.path + const wt = worktrees.find((w) => w.id === activeWorktreeId) + if (wt) { + return wt.path } } - return null }, [activeWorktreeId, worktreesByRepo]) - const [dirCache, setDirCache] = useState>({}) - const dirCacheRef = useRef(dirCache) - dirCacheRef.current = dirCache + const expanded = useMemo( + () => + activeWorktreeId ? (expandedDirs[activeWorktreeId] ?? new Set()) : new Set(), + [activeWorktreeId, expandedDirs] + ) + + const { + dirCache, + flatRows, + rowsByPath, + rootCache, + loadDir, + refreshTree, + refreshDir, + resetAndLoad + } = useFileExplorerTree(worktreePath, expanded) + const [selectedPath, setSelectedPath] = useState(null) const [flashingPath, setFlashingPath] = useState(null) + const [bgMenuOpen, setBgMenuOpen] = useState(false) + const [bgMenuPoint, setBgMenuPoint] = useState({ x: 0, y: 0 }) const scrollRef = useRef(null) const flashTimeoutRef = useRef(null) const isMac = useMemo(() => navigator.userAgent.includes('Mac'), []) @@ -64,76 +86,9 @@ export default function FileExplorer(): React.JSX.Element { () => (activeWorktreeId ? (gitStatusByWorktree[activeWorktreeId] ?? []) : []), [activeWorktreeId, gitStatusByWorktree] ) - const statusByRelativePath = useMemo(() => buildStatusMap(entries), [entries]) - const folderStatusByRelativePath = useMemo(() => buildFolderStatusMap(entries), [entries]) - const expanded = useMemo( - () => - activeWorktreeId ? (expandedDirs[activeWorktreeId] ?? new Set()) : new Set(), - [activeWorktreeId, expandedDirs] - ) - - const loadDir = useCallback( - async (dirPath: string, depth: number, options?: { force?: boolean }) => { - const cache = dirCacheRef.current - if (!options?.force && (cache[dirPath]?.children.length > 0 || cache[dirPath]?.loading)) { - return - } - - setDirCache((prev) => ({ - ...prev, - [dirPath]: { - children: options?.force ? [] : (prev[dirPath]?.children ?? []), - loading: true - } - })) - - try { - const entries = await window.api.fs.readDir({ dirPath }) - const children: TreeNode[] = entries - .filter(shouldIncludeFileExplorerEntry) - .map((entry) => ({ - name: entry.name, - path: joinPath(dirPath, entry.name), - relativePath: worktreePath - ? normalizeRelativePath(joinPath(dirPath, entry.name).slice(worktreePath.length + 1)) - : entry.name, - isDirectory: entry.isDirectory, - depth: depth + 1 - })) - - setDirCache((prev) => ({ - ...prev, - [dirPath]: { children, loading: false } - })) - } catch { - setDirCache((prev) => ({ - ...prev, - [dirPath]: { children: [], loading: false } - })) - } - }, - [worktreePath] - ) - - const refreshTree = useCallback(async () => { - if (!worktreePath) { - return - } - - setDirCache({}) - await loadDir(worktreePath, -1, { force: true }) - - await Promise.all( - Array.from(expanded).map(async (dirPath) => { - const depth = splitPathSegments(dirPath.slice(worktreePath.length + 1)).length - 1 - await loadDir(dirPath, depth, { force: true }) - }) - ) - }, [expanded, loadDir, worktreePath]) - const { pendingDelete, isDeleting, @@ -158,15 +113,11 @@ export default function FileExplorer(): React.JSX.Element { if (!worktreePath) { return } - setSelectedPath(null) - setDirCache({}) - void loadDir(worktreePath, -1) + resetAndLoad() }, [worktreePath]) // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { - return clearFlashTimeout - }, [clearFlashTimeout]) + useEffect(() => clearFlashTimeout, [clearFlashTimeout]) useEffect(() => { for (const dirPath of expanded) { @@ -179,40 +130,39 @@ export default function FileExplorer(): React.JSX.Element { } }, [expanded]) // eslint-disable-line react-hooks/exhaustive-deps - const flatRows = useMemo(() => { - if (!worktreePath) { - return [] - } + const { + inlineInput, + inlineInputIndex, + startNew, + startRename, + dismissInlineInput, + handleInlineSubmit + } = useFileExplorerInlineInput({ + activeWorktreeId, + worktreePath, + expanded, + flatRows, + scrollRef, + refreshDir + }) - const result: TreeNode[] = [] - - const addChildren = (parentPath: string): void => { - const cached = dirCache[parentPath] - if (!cached?.children) { - return - } - - for (const child of cached.children) { - result.push(child) - if (child.isDirectory && expanded.has(child.path)) { - addChildren(child.path) - } - } - } - - addChildren(worktreePath) - return result - }, [worktreePath, dirCache, expanded]) - - const rowsByPath = useMemo(() => new Map(flatRows.map((row) => [row.path, row])), [flatRows]) - const rootCache = worktreePath ? dirCache[worktreePath] : undefined + const totalCount = flatRows.length + (inlineInputIndex >= 0 ? 1 : 0) const virtualizer = useVirtualizer({ - count: flatRows.length, + count: totalCount, getScrollElement: () => scrollRef.current, estimateSize: () => 26, overscan: 20, - getItemKey: (index) => flatRows[index].path + getItemKey: (index) => { + if (inlineInputIndex >= 0) { + if (index === inlineInputIndex) { + return '__inline_input__' + } + const rowIndex = index > inlineInputIndex ? index - 1 : index + return flatRows[rowIndex]?.path ?? `__fallback_${index}` + } + return flatRows[index]?.path ?? `__fallback_${index}` + } }) useFileExplorerReveal({ @@ -232,19 +182,26 @@ export default function FileExplorer(): React.JSX.Element { virtualizer }) + const selectedNode = selectedPath ? (rowsByPath.get(selectedPath) ?? null) : null + useFileExplorerKeys({ + containerRef: scrollRef, + flatRows, + inlineInput, + selectedNode, + startRename, + requestDelete + }) + const handleClick = useCallback( (node: TreeNode) => { if (!activeWorktreeId) { return } - setSelectedPath(node.path) - if (node.isDirectory) { toggleDir(activeWorktreeId, node.path) return } - openFile({ filePath: node.path, relativePath: node.relativePath, @@ -261,7 +218,6 @@ export default function FileExplorer(): React.JSX.Element { if (!activeWorktreeId || node.isDirectory) { return } - pinFile(node.path) }, [activeWorktreeId, pinFile] @@ -272,52 +228,17 @@ export default function FileExplorer(): React.JSX.Element { if (!container || Math.abs(e.deltaY) <= Math.abs(e.deltaX)) { return } - const target = e.target if (!(target instanceof Element) || !target.closest('[data-explorer-draggable="true"]')) { return } - if (container.scrollHeight <= container.clientHeight) { return } - e.preventDefault() container.scrollTop += e.deltaY }, []) - const handleExplorerKeyDown = useCallback( - (event: React.KeyboardEvent) => { - const target = event.target - if ( - !(target instanceof HTMLElement) || - target instanceof HTMLInputElement || - target instanceof HTMLTextAreaElement || - target.isContentEditable - ) { - return - } - - const selectedNode = - (selectedPath ? rowsByPath.get(selectedPath) : undefined) ?? - (activeFileId ? rowsByPath.get(activeFileId) : undefined) - if (!selectedNode) { - return - } - - const isDeleteShortcut = - event.key === 'Delete' || (isMac && event.key === 'Backspace' && event.metaKey) - - if (!isDeleteShortcut) { - return - } - - event.preventDefault() - requestDelete(selectedNode) - }, - [activeFileId, isMac, requestDelete, rowsByPath, selectedPath] - ) - if (!worktreePath) { return (
@@ -326,7 +247,7 @@ export default function FileExplorer(): React.JSX.Element { ) } - if (flatRows.length === 0) { + if (flatRows.length === 0 && !inlineInput) { if (rootCache?.loading ?? true) { return (
@@ -334,7 +255,6 @@ export default function FileExplorer(): React.JSX.Element {
) } - return (
No files in this worktree @@ -349,37 +269,84 @@ export default function FileExplorer(): React.JSX.Element { viewportRef={scrollRef} viewportClassName="h-full min-h-0 py-2" onWheelCapture={handleWheelCapture} - onKeyDownCapture={handleExplorerKeyDown} + onContextMenu={(e) => { + const target = e.target as HTMLElement + if (target.closest('[data-slot="context-menu-trigger"]')) { + return + } + e.preventDefault() + setBgMenuPoint({ x: e.clientX, y: e.clientY }) + setBgMenuOpen(true) + }} >
- {virtualizer.getVirtualItems().map((virtualItem) => { - const node = flatRows[virtualItem.index] - const normalizedRelativePath = normalizeRelativePath(node.relativePath) - const nodeStatus = node.isDirectory + {virtualizer.getVirtualItems().map((vItem) => { + const isInlineRow = inlineInputIndex >= 0 && vItem.index === inlineInputIndex + const rowIndex = + !isInlineRow && inlineInputIndex >= 0 && vItem.index > inlineInputIndex + ? vItem.index - 1 + : vItem.index + const node = isInlineRow ? null : flatRows[rowIndex] + if (!isInlineRow && !node) { + return null + } + + const showInline = + isInlineRow || + (inlineInput?.type === 'rename' && node && inlineInput.existingPath === node.path) + const inlineDepth = isInlineRow ? inlineInput!.depth : (node?.depth ?? 0) + + if (showInline) { + return ( +
+ +
+ ) + } + + // Safe: the isInlineRow/showInline guards above ensure node is non-null here + const n = node! + const normalizedRelativePath = normalizeRelativePath(n.relativePath) + const nodeStatus = n.isDirectory ? (folderStatusByRelativePath.get(normalizedRelativePath) ?? null) : (statusByRelativePath.get(normalizedRelativePath) ?? null) return (
handleClick(node)} - onDoubleClick={() => handleDoubleClick(node)} - onSelect={() => setSelectedPath(node.path)} - onRequestDelete={() => requestDelete(node)} + targetDir={n.isDirectory ? n.path : dirname(n.path)} + targetDepth={n.isDirectory ? n.depth + 1 : n.depth} + onClick={() => handleClick(n)} + onDoubleClick={() => handleDoubleClick(n)} + onSelect={() => setSelectedPath(n.path)} + onStartNew={startNew} + onStartRename={startRename} + onRequestDelete={() => requestDelete(n)} />
) @@ -387,6 +354,32 @@ export default function FileExplorer(): React.JSX.Element {
+ + + - - - + e.preventDefault()} + > + onStartNew('file', targetDir, targetDepth)}> + + New File + + onStartNew('folder', targetDir, targetDepth)}> + + New Folder + + + window.api.ui.writeClipboardText(node.path)}> + + Copy Path + {isMac ? '⌥⌘C' : 'Shift+Alt+C'} + + window.api.ui.writeClipboardText(node.relativePath)}> + + Copy Relative Path + {isMac ? '⌥⇧⌘C' : 'Ctrl+Shift+Alt+C'} + + + onStartRename(node)}> + + Rename + {isMac ? '↩' : 'Enter'} + + + Delete {deleteShortcutLabel} diff --git a/src/renderer/src/components/right-sidebar/index.tsx b/src/renderer/src/components/right-sidebar/index.tsx index ba9af3d46..2c93c3637 100644 --- a/src/renderer/src/components/right-sidebar/index.tsx +++ b/src/renderer/src/components/right-sidebar/index.tsx @@ -165,7 +165,7 @@ export default function RightSidebar(): React.JSX.Element { : 0 const panelContent = ( -
+
{rightSidebarTab === 'explorer' && } {rightSidebarTab === 'search' && } {rightSidebarTab === 'source-control' && } diff --git a/src/renderer/src/components/right-sidebar/useFileExplorerInlineInput.ts b/src/renderer/src/components/right-sidebar/useFileExplorerInlineInput.ts new file mode 100644 index 000000000..bf6c24e50 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/useFileExplorerInlineInput.ts @@ -0,0 +1,157 @@ +import { useCallback, useMemo, useState } from 'react' +import type React from 'react' +import { useAppStore } from '@/store' +import { detectLanguage } from '@/lib/language-detect' +import { dirname, joinPath } from '@/lib/path' +import type { InlineInput } from './FileExplorerRow' +import type { TreeNode } from './file-explorer-types' + +type UseFileExplorerInlineInputParams = { + activeWorktreeId: string | null + worktreePath: string | null + expanded: Set + flatRows: TreeNode[] + scrollRef: React.RefObject + refreshDir: (dirPath: string) => Promise +} + +type UseFileExplorerInlineInputResult = { + inlineInput: InlineInput | null + inlineInputIndex: number + startNew: (type: 'file' | 'folder', parentPath: string, depth: number) => void + startRename: (node: TreeNode) => void + dismissInlineInput: () => void + handleInlineSubmit: (value: string) => void +} + +export function useFileExplorerInlineInput({ + activeWorktreeId, + worktreePath, + expanded, + flatRows, + scrollRef, + refreshDir +}: UseFileExplorerInlineInputParams): UseFileExplorerInlineInputResult { + const toggleDir = useAppStore((s) => s.toggleDir) + const openFile = useAppStore((s) => s.openFile) + const [inlineInput, setInlineInput] = useState(null) + + const inlineInputIndex = useMemo(() => { + if (!inlineInput || inlineInput.type === 'rename') { + return -1 + } + const parentPath = inlineInput.parentPath + let last = -1 + for (let i = 0; i < flatRows.length; i++) { + const rowPath = flatRows[i].path + // Match the parent itself and any descendants (handle both / and \ separators) + if ( + rowPath === parentPath || + rowPath.startsWith(`${parentPath}/`) || + rowPath.startsWith(`${parentPath}\\`) + ) { + last = i + } + } + if (last >= 0) { + return last + 1 + } + // Empty root directory — place at the top + if (parentPath === worktreePath) { + return 0 + } + // Collapsed non-root parent — place right after the parent row + const parentIndex = flatRows.findIndex((row) => row.path === parentPath) + return parentIndex >= 0 ? parentIndex + 1 : 0 + }, [inlineInput, flatRows, worktreePath]) + + const startNew = useCallback( + (type: 'file' | 'folder', parentPath: string, depth: number) => { + if (activeWorktreeId && parentPath !== worktreePath && !expanded.has(parentPath)) { + toggleDir(activeWorktreeId, parentPath) + } + setInlineInput({ parentPath, type, depth }) + }, + [activeWorktreeId, worktreePath, expanded, toggleDir] + ) + + const startRename = useCallback( + (node: TreeNode) => + setInlineInput({ + parentPath: dirname(node.path), + type: 'rename', + depth: node.depth, + existingName: node.name, + existingPath: node.path + }), + [] + ) + + const dismissInlineInput = useCallback(() => { + setInlineInput(null) + requestAnimationFrame(() => scrollRef.current?.focus()) + }, [scrollRef]) + + const handleInlineSubmit = useCallback( + (value: string) => { + if (!inlineInput || !value.trim() || !activeWorktreeId || !worktreePath) { + setInlineInput(null) + return + } + const name = value.trim() + // No-op if the user submitted the same name (e.g. blur without editing) + if (inlineInput.type === 'rename' && name === inlineInput.existingName) { + setInlineInput(null) + return + } + const run = async (): Promise => { + if (inlineInput.type === 'rename' && inlineInput.existingPath) { + const parentDir = dirname(inlineInput.existingPath) + try { + await window.api.fs.rename({ + oldPath: inlineInput.existingPath, + newPath: joinPath(parentDir, name) + }) + } catch (err) { + console.error('Rename failed:', err) + } + await refreshDir(parentDir) + } else { + const fullPath = joinPath(inlineInput.parentPath, name) + try { + await (inlineInput.type === 'folder' + ? window.api.fs.createDir({ dirPath: fullPath }) + : window.api.fs.createFile({ filePath: fullPath })) + await refreshDir(inlineInput.parentPath) + if (inlineInput.type === 'file') { + openFile({ + filePath: fullPath, + relativePath: worktreePath ? fullPath.slice(worktreePath.length + 1) : name, + worktreeId: activeWorktreeId, + language: detectLanguage(name), + mode: 'edit' + }) + } + } catch (err) { + // Refresh the directory even on failure so the tree stays consistent + await refreshDir(inlineInput.parentPath) + console.error('Create failed:', err) + } + } + } + void run() + setInlineInput(null) + requestAnimationFrame(() => scrollRef.current?.focus()) + }, + [inlineInput, activeWorktreeId, worktreePath, refreshDir, openFile, scrollRef] + ) + + return { + inlineInput, + inlineInputIndex, + startNew, + startRename, + dismissInlineInput, + handleInlineSubmit + } +} diff --git a/src/renderer/src/components/right-sidebar/useFileExplorerKeys.ts b/src/renderer/src/components/right-sidebar/useFileExplorerKeys.ts new file mode 100644 index 000000000..871f27c8a --- /dev/null +++ b/src/renderer/src/components/right-sidebar/useFileExplorerKeys.ts @@ -0,0 +1,117 @@ +import { useEffect, useRef } from 'react' +import type React from 'react' +import { useAppStore } from '@/store' +import type { InlineInput } from './FileExplorerRow' +import type { TreeNode } from './file-explorer-types' + +const isMac = navigator.userAgent.includes('Mac') + +/** + * Keyboard shortcuts for the file explorer. + * + * All shortcuts (bare-key and modifier) only fire when focus is inside + * the explorer container — they must never intercept the editor or terminal. + */ +export function useFileExplorerKeys(opts: { + containerRef: React.RefObject + flatRows: TreeNode[] + inlineInput: InlineInput | null + selectedNode: TreeNode | null + startRename: (node: TreeNode) => void + requestDelete: (node: TreeNode) => void +}): void { + const rightSidebarOpen = useAppStore((s) => s.rightSidebarOpen) + const rightSidebarTab = useAppStore((s) => s.rightSidebarTab) + + const flatRowsRef = useRef(opts.flatRows) + flatRowsRef.current = opts.flatRows + const inlineInputRef = useRef(opts.inlineInput) + inlineInputRef.current = opts.inlineInput + const selectedNodeRef = useRef(opts.selectedNode) + selectedNodeRef.current = opts.selectedNode + const startRenameRef = useRef(opts.startRename) + startRenameRef.current = opts.startRename + const requestDeleteRef = useRef(opts.requestDelete) + requestDeleteRef.current = opts.requestDelete + + useEffect(() => { + // Find the node that the focused button represents (for bare-key shortcuts). + // Each row button's closest [data-index] gives us the virtualizer index. + const findFocusedNode = (): TreeNode | null => { + const el = document.activeElement as HTMLElement | null + if (!el || !opts.containerRef.current?.contains(el)) { + return null + } + const wrapper = el.closest('[data-index]') + if (!wrapper) { + return null + } + const idx = Number(wrapper.dataset.index) + return flatRowsRef.current[idx] ?? null + } + + const focusInExplorer = (): boolean => { + const el = document.activeElement + return !!el && !!opts.containerRef.current?.contains(el) + } + + const onKeyDown = (e: KeyboardEvent): void => { + if (!rightSidebarOpen || rightSidebarTab !== 'explorer') { + return + } + if (inlineInputRef.current) { + return + } + + // ── Bare-key shortcuts: only when explorer has focus ── + if (focusInExplorer()) { + const node = findFocusedNode() + if (node) { + // Enter — Rename + if (e.key === 'Enter' && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey) { + e.preventDefault() + startRenameRef.current(node) + return + } + // ⌘⌫ (Mac) / Delete (Win) — Delete + if ( + (isMac && e.key === 'Backspace' && e.metaKey) || + (!isMac && e.key === 'Delete' && !e.metaKey && !e.ctrlKey) + ) { + e.preventDefault() + requestDeleteRef.current(node) + return + } + } + } + + // ── Modifier shortcuts: only when focus is inside the explorer ── + // Scoped to explorer focus to avoid intercepting editor/terminal shortcuts + if (!focusInExplorer()) { + return + } + const node = selectedNodeRef.current + if (!node) { + return + } + // ⌥⇧⌘C (Mac) / Ctrl+Shift+Alt+C (Win) — Copy Relative Path + if (e.code === 'KeyC' && e.altKey && e.shiftKey && (isMac ? e.metaKey : e.ctrlKey)) { + e.preventDefault() + window.api.ui.writeClipboardText(node.relativePath) + return + } + // ⌥⌘C (Mac) / Shift+Alt+C (Win) — Copy Path + if ( + e.code === 'KeyC' && + e.altKey && + ((isMac && e.metaKey && !e.shiftKey) || (!isMac && e.shiftKey && !e.ctrlKey)) + ) { + e.preventDefault() + window.api.ui.writeClipboardText(node.path) + } + } + + window.addEventListener('keydown', onKeyDown) + return () => window.removeEventListener('keydown', onKeyDown) + }, [rightSidebarOpen, rightSidebarTab, opts.containerRef]) +} diff --git a/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts b/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts new file mode 100644 index 000000000..41628b050 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts @@ -0,0 +1,129 @@ +import { useCallback, useMemo, useRef, useState } from 'react' +import { joinPath, normalizeRelativePath } from '@/lib/path' +import type { DirCache, TreeNode } from './file-explorer-types' +import { splitPathSegments } from './path-tree' +import { shouldIncludeFileExplorerEntry } from './file-explorer-entries' + +type UseFileExplorerTreeResult = { + dirCache: Record + flatRows: TreeNode[] + rowsByPath: Map + rootCache: DirCache | undefined + loadDir: (dirPath: string, depth: number, options?: { force?: boolean }) => Promise + refreshTree: () => Promise + refreshDir: (dirPath: string) => Promise + resetAndLoad: () => void +} + +export function useFileExplorerTree( + worktreePath: string | null, + expanded: Set +): UseFileExplorerTreeResult { + const [dirCache, setDirCache] = useState>({}) + const dirCacheRef = useRef(dirCache) + dirCacheRef.current = dirCache + + const loadDir = useCallback( + async (dirPath: string, depth: number, options?: { force?: boolean }) => { + const cache = dirCacheRef.current + if (!options?.force && (cache[dirPath]?.children.length > 0 || cache[dirPath]?.loading)) { + return + } + setDirCache((prev) => ({ + ...prev, + [dirPath]: { + children: options?.force ? [] : (prev[dirPath]?.children ?? []), + loading: true + } + })) + try { + const entries = await window.api.fs.readDir({ dirPath }) + const children: TreeNode[] = entries + .filter(shouldIncludeFileExplorerEntry) + .map((entry) => ({ + name: entry.name, + path: joinPath(dirPath, entry.name), + relativePath: worktreePath + ? normalizeRelativePath(joinPath(dirPath, entry.name).slice(worktreePath.length + 1)) + : entry.name, + isDirectory: entry.isDirectory, + depth: depth + 1 + })) + setDirCache((prev) => ({ ...prev, [dirPath]: { children, loading: false } })) + } catch { + setDirCache((prev) => ({ ...prev, [dirPath]: { children: [], loading: false } })) + } + }, + [worktreePath] + ) + + const refreshTree = useCallback(async () => { + if (!worktreePath) { + return + } + setDirCache({}) + await loadDir(worktreePath, -1, { force: true }) + await Promise.all( + Array.from(expanded).map(async (dirPath) => { + const depth = splitPathSegments(dirPath.slice(worktreePath.length + 1)).length - 1 + await loadDir(dirPath, depth, { force: true }) + }) + ) + }, [expanded, loadDir, worktreePath]) + + const refreshDir = useCallback( + async (dirPath: string) => { + if (!worktreePath) { + return + } + const depth = + dirPath === worktreePath + ? -1 + : splitPathSegments(dirPath.slice(worktreePath.length + 1)).length - 1 + await loadDir(dirPath, depth, { force: true }) + }, + [worktreePath, loadDir] + ) + + const flatRows = useMemo(() => { + if (!worktreePath) { + return [] + } + const result: TreeNode[] = [] + const addChildren = (parentPath: string): void => { + const cached = dirCache[parentPath] + if (!cached?.children) { + return + } + for (const child of cached.children) { + result.push(child) + if (child.isDirectory && expanded.has(child.path)) { + addChildren(child.path) + } + } + } + addChildren(worktreePath) + return result + }, [worktreePath, dirCache, expanded]) + + const rowsByPath = useMemo(() => new Map(flatRows.map((row) => [row.path, row])), [flatRows]) + const rootCache = worktreePath ? dirCache[worktreePath] : undefined + + const resetAndLoad = useCallback(() => { + setDirCache({}) + if (worktreePath) { + void loadDir(worktreePath, -1, { force: true }) + } + }, [worktreePath, loadDir]) + + return { + dirCache, + flatRows, + rowsByPath, + rootCache, + loadDir, + refreshTree, + refreshDir, + resetAndLoad + } +}