feat: add file actions to file explorer (#235)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
894f1bb6aa
commit
86799b4793
@@ -0,0 +1,228 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const handlers = new Map<string, (_event: unknown, args: unknown) => Promise<unknown>>()
|
||||
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<string, string>) {
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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<void> {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
const oldPath = await resolveAuthorizedPath(args.oldPath, store)
|
||||
const newPath = await resolveAuthorizedPath(args.newPath, store)
|
||||
await assertNotExists(newPath)
|
||||
await rename(oldPath, newPath)
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
|
||||
Vendored
+3
@@ -135,6 +135,9 @@ type FsApi = {
|
||||
filePath: string
|
||||
}) => Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }>
|
||||
writeFile: (args: { filePath: string; content: string }) => Promise<void>
|
||||
createFile: (args: { filePath: string }) => Promise<void>
|
||||
createDir: (args: { dirPath: string }) => Promise<void>
|
||||
rename: (args: { oldPath: string; newPath: string }) => Promise<void>
|
||||
deletePath: (args: { targetPath: string }) => Promise<void>
|
||||
stat: (args: {
|
||||
filePath: string
|
||||
|
||||
@@ -229,6 +229,12 @@ const api = {
|
||||
ipcRenderer.invoke('fs:readFile', args),
|
||||
writeFile: (args: { filePath: string; content: string }): Promise<void> =>
|
||||
ipcRenderer.invoke('fs:writeFile', args),
|
||||
createFile: (args: { filePath: string }): Promise<void> =>
|
||||
ipcRenderer.invoke('fs:createFile', args),
|
||||
createDir: (args: { dirPath: string }): Promise<void> =>
|
||||
ipcRenderer.invoke('fs:createDir', args),
|
||||
rename: (args: { oldPath: string; newPath: string }): Promise<void> =>
|
||||
ipcRenderer.invoke('fs:rename', args),
|
||||
deletePath: (args: { targetPath: string }): Promise<void> =>
|
||||
ipcRenderer.invoke('fs:deletePath', args),
|
||||
stat: (args: {
|
||||
|
||||
@@ -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<Record<string, DirCache>>({})
|
||||
const dirCacheRef = useRef(dirCache)
|
||||
dirCacheRef.current = dirCache
|
||||
const expanded = useMemo(
|
||||
() =>
|
||||
activeWorktreeId ? (expandedDirs[activeWorktreeId] ?? new Set<string>()) : new Set<string>(),
|
||||
[activeWorktreeId, expandedDirs]
|
||||
)
|
||||
|
||||
const {
|
||||
dirCache,
|
||||
flatRows,
|
||||
rowsByPath,
|
||||
rootCache,
|
||||
loadDir,
|
||||
refreshTree,
|
||||
refreshDir,
|
||||
resetAndLoad
|
||||
} = useFileExplorerTree(worktreePath, expanded)
|
||||
|
||||
const [selectedPath, setSelectedPath] = useState<string | null>(null)
|
||||
const [flashingPath, setFlashingPath] = useState<string | null>(null)
|
||||
const [bgMenuOpen, setBgMenuOpen] = useState(false)
|
||||
const [bgMenuPoint, setBgMenuPoint] = useState({ x: 0, y: 0 })
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const flashTimeoutRef = useRef<number | null>(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<string>()) : new Set<string>(),
|
||||
[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<HTMLDivElement>) => {
|
||||
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 (
|
||||
<div className="flex h-full items-center justify-center text-[11px] text-muted-foreground px-4 text-center">
|
||||
@@ -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 (
|
||||
<div className="flex items-center justify-center h-full text-[11px] text-muted-foreground">
|
||||
@@ -334,7 +255,6 @@ export default function FileExplorer(): React.JSX.Element {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-[11px] text-muted-foreground px-4 text-center">
|
||||
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)
|
||||
}}
|
||||
>
|
||||
<div className="relative w-full" style={{ height: `${virtualizer.getTotalSize()}px` }}>
|
||||
{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 (
|
||||
<div
|
||||
key={vItem.key}
|
||||
data-index={vItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute left-0 right-0"
|
||||
style={{ transform: `translateY(${vItem.start}px)` }}
|
||||
>
|
||||
<InlineInputRow
|
||||
depth={inlineDepth}
|
||||
inlineInput={inlineInput!}
|
||||
onSubmit={handleInlineSubmit}
|
||||
onCancel={dismissInlineInput}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
data-index={virtualItem.index}
|
||||
key={vItem.key}
|
||||
data-index={vItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute left-0 right-0"
|
||||
style={{ transform: `translateY(${virtualItem.start}px)` }}
|
||||
style={{ transform: `translateY(${vItem.start}px)` }}
|
||||
>
|
||||
<FileExplorerRow
|
||||
node={node}
|
||||
isExpanded={expanded.has(node.path)}
|
||||
isLoading={node.isDirectory && Boolean(dirCache[node.path]?.loading)}
|
||||
isSelected={selectedPath === node.path || activeFileId === node.path}
|
||||
isFlashing={flashingPath === node.path}
|
||||
node={n}
|
||||
isExpanded={expanded.has(n.path)}
|
||||
isLoading={n.isDirectory && Boolean(dirCache[n.path]?.loading)}
|
||||
isSelected={selectedPath === n.path || activeFileId === n.path}
|
||||
isFlashing={flashingPath === n.path}
|
||||
nodeStatus={nodeStatus}
|
||||
statusColor={nodeStatus ? STATUS_COLORS[nodeStatus] : null}
|
||||
deleteShortcutLabel={deleteShortcutLabel}
|
||||
onClick={() => 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)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -387,6 +354,32 @@ export default function FileExplorer(): React.JSX.Element {
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DropdownMenu open={bgMenuOpen} onOpenChange={setBgMenuOpen} modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
aria-hidden
|
||||
tabIndex={-1}
|
||||
className="pointer-events-none fixed size-px opacity-0"
|
||||
style={{ left: bgMenuPoint.x, top: bgMenuPoint.y }}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-48"
|
||||
sideOffset={0}
|
||||
align="start"
|
||||
onCloseAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<DropdownMenuItem onSelect={() => startNew('file', worktreePath, 0)}>
|
||||
<FilePlus />
|
||||
New File
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => startNew('folder', worktreePath, 0)}>
|
||||
<FolderPlus />
|
||||
New Folder
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<FileDeleteDialog
|
||||
pendingDelete={pendingDelete}
|
||||
isDeleting={isDeleting}
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import React from 'react'
|
||||
import { ChevronRight, File, Folder, FolderOpen, Loader2, Trash2 } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef } from 'react'
|
||||
import {
|
||||
ChevronRight,
|
||||
Copy,
|
||||
File,
|
||||
FilePlus,
|
||||
Folder,
|
||||
FolderOpen,
|
||||
FolderPlus,
|
||||
Loader2,
|
||||
Pencil,
|
||||
Trash2
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuTrigger
|
||||
} from '@/components/ui/context-menu'
|
||||
@@ -12,6 +24,131 @@ import type { GitFileStatus } from '../../../../shared/types'
|
||||
import { STATUS_LABELS } from './status-display'
|
||||
import type { TreeNode } from './file-explorer-types'
|
||||
|
||||
const isMac = navigator.userAgent.includes('Mac')
|
||||
|
||||
export type InlineInput = {
|
||||
parentPath: string
|
||||
type: 'file' | 'folder' | 'rename'
|
||||
depth: number
|
||||
existingName?: string
|
||||
existingPath?: string
|
||||
}
|
||||
|
||||
// ─── Inline Input Row ────────────────────────────────────────────
|
||||
|
||||
export function InlineInputRow({
|
||||
depth,
|
||||
inlineInput,
|
||||
onSubmit,
|
||||
onCancel
|
||||
}: {
|
||||
depth: number
|
||||
inlineInput: InlineInput
|
||||
onSubmit: (value: string) => void
|
||||
onCancel: () => void
|
||||
}): React.JSX.Element {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const blurTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const submitted = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
submitted.current = false
|
||||
|
||||
// Schedule focus after any pending focus-restore from menu close
|
||||
const raf = requestAnimationFrame(() => {
|
||||
const el = inputRef.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
el.focus()
|
||||
if (inlineInput.type === 'rename' && inlineInput.existingName) {
|
||||
const dotIndex = inlineInput.existingName.lastIndexOf('.')
|
||||
if (dotIndex > 0) {
|
||||
el.setSelectionRange(0, dotIndex)
|
||||
} else {
|
||||
el.select()
|
||||
}
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
cancelAnimationFrame(raf)
|
||||
if (blurTimeout.current) {
|
||||
clearTimeout(blurTimeout.current)
|
||||
}
|
||||
}
|
||||
}, [inlineInput])
|
||||
|
||||
const clearBlurTimeout = useCallback(() => {
|
||||
if (blurTimeout.current) {
|
||||
clearTimeout(blurTimeout.current)
|
||||
blurTimeout.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const submit = useCallback(
|
||||
(value: string) => {
|
||||
if (submitted.current) {
|
||||
return
|
||||
}
|
||||
submitted.current = true
|
||||
clearBlurTimeout()
|
||||
onSubmit(value)
|
||||
},
|
||||
[onSubmit, clearBlurTimeout]
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center w-full h-[26px] px-2 gap-1"
|
||||
style={{ paddingLeft: `${depth * 16 + 8}px` }}
|
||||
>
|
||||
<span className="size-3 shrink-0" />
|
||||
{inlineInput.type === 'folder' ? (
|
||||
<Folder className="size-3 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<File className="size-3 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="flex-1 min-w-0 bg-transparent text-xs text-foreground outline-none border border-ring rounded-sm px-1"
|
||||
defaultValue={inlineInput.type === 'rename' ? inlineInput.existingName : ''}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
submit(e.currentTarget.value)
|
||||
} else if (e.key === 'Escape') {
|
||||
clearBlurTimeout()
|
||||
submitted.current = true
|
||||
onCancel()
|
||||
}
|
||||
}}
|
||||
onFocus={clearBlurTimeout}
|
||||
onBlur={(e) => {
|
||||
// When a Radix menu (context or dropdown) closes, it restores focus
|
||||
// to its trigger button, which steals focus from this input before
|
||||
// the user can type. Detect this by checking relatedTarget — if focus
|
||||
// moved to any menu trigger, it's Radix cleanup, not a user action.
|
||||
if (
|
||||
e.relatedTarget instanceof HTMLElement &&
|
||||
(e.relatedTarget.closest('[data-slot="context-menu-trigger"]') ||
|
||||
e.relatedTarget.closest('[data-slot="dropdown-menu-trigger"]'))
|
||||
) {
|
||||
requestAnimationFrame(() => inputRef.current?.focus())
|
||||
return
|
||||
}
|
||||
const value = e.currentTarget.value
|
||||
blurTimeout.current = setTimeout(() => {
|
||||
blurTimeout.current = null
|
||||
submit(value)
|
||||
}, 150)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── File / Folder Row with Context Menu ─────────────────────────
|
||||
|
||||
type FileExplorerRowProps = {
|
||||
node: TreeNode
|
||||
isExpanded: boolean
|
||||
@@ -21,9 +158,13 @@ type FileExplorerRowProps = {
|
||||
nodeStatus: GitFileStatus | null
|
||||
statusColor: string | null
|
||||
deleteShortcutLabel: string
|
||||
targetDir: string
|
||||
targetDepth: number
|
||||
onClick: () => void
|
||||
onDoubleClick: () => void
|
||||
onSelect: () => void
|
||||
onStartNew: (type: 'file' | 'folder', dir: string, depth: number) => void
|
||||
onStartRename: (node: TreeNode) => void
|
||||
onRequestDelete: () => void
|
||||
}
|
||||
|
||||
@@ -36,9 +177,13 @@ export function FileExplorerRow({
|
||||
nodeStatus,
|
||||
statusColor,
|
||||
deleteShortcutLabel,
|
||||
targetDir,
|
||||
targetDepth,
|
||||
onClick,
|
||||
onDoubleClick,
|
||||
onSelect,
|
||||
onStartNew,
|
||||
onStartRename,
|
||||
onRequestDelete
|
||||
}: FileExplorerRowProps): React.JSX.Element {
|
||||
return (
|
||||
@@ -99,9 +244,37 @@ export function FileExplorerRow({
|
||||
)}
|
||||
</button>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent className="w-56">
|
||||
<ContextMenuItem onSelect={onRequestDelete}>
|
||||
<Trash2 className="size-3.5" />
|
||||
<ContextMenuContent
|
||||
className="w-64 bg-[rgba(255,255,255,0.82)] dark:bg-[rgba(0,0,0,0.72)]"
|
||||
onCloseAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<ContextMenuItem onSelect={() => onStartNew('file', targetDir, targetDepth)}>
|
||||
<FilePlus />
|
||||
New File
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onStartNew('folder', targetDir, targetDepth)}>
|
||||
<FolderPlus />
|
||||
New Folder
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => window.api.ui.writeClipboardText(node.path)}>
|
||||
<Copy />
|
||||
Copy Path
|
||||
<ContextMenuShortcut>{isMac ? '⌥⌘C' : 'Shift+Alt+C'}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => window.api.ui.writeClipboardText(node.relativePath)}>
|
||||
<Copy />
|
||||
Copy Relative Path
|
||||
<ContextMenuShortcut>{isMac ? '⌥⇧⌘C' : 'Ctrl+Shift+Alt+C'}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => onStartRename(node)}>
|
||||
<Pencil />
|
||||
Rename
|
||||
<ContextMenuShortcut>{isMac ? '↩' : 'Enter'}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem variant="destructive" onSelect={onRequestDelete}>
|
||||
<Trash2 />
|
||||
Delete
|
||||
<ContextMenuShortcut>{deleteShortcutLabel}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
|
||||
@@ -165,7 +165,7 @@ export default function RightSidebar(): React.JSX.Element {
|
||||
: 0
|
||||
|
||||
const panelContent = (
|
||||
<div className="flex-1 min-h-0 overflow-hidden scrollbar-sleek-parent">
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden scrollbar-sleek-parent">
|
||||
{rightSidebarTab === 'explorer' && <FileExplorer key={activeWorktreeId ?? 'none'} />}
|
||||
{rightSidebarTab === 'search' && <SearchPanel key={activeWorktreeId ?? 'none'} />}
|
||||
{rightSidebarTab === 'source-control' && <SourceControl key={activeWorktreeId ?? 'none'} />}
|
||||
|
||||
@@ -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<string>
|
||||
flatRows: TreeNode[]
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>
|
||||
refreshDir: (dirPath: string) => Promise<void>
|
||||
}
|
||||
|
||||
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<InlineInput | null>(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<void> => {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<HTMLDivElement | null>
|
||||
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<HTMLElement>('[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])
|
||||
}
|
||||
@@ -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<string, DirCache>
|
||||
flatRows: TreeNode[]
|
||||
rowsByPath: Map<string, TreeNode>
|
||||
rootCache: DirCache | undefined
|
||||
loadDir: (dirPath: string, depth: number, options?: { force?: boolean }) => Promise<void>
|
||||
refreshTree: () => Promise<void>
|
||||
refreshDir: (dirPath: string) => Promise<void>
|
||||
resetAndLoad: () => void
|
||||
}
|
||||
|
||||
export function useFileExplorerTree(
|
||||
worktreePath: string | null,
|
||||
expanded: Set<string>
|
||||
): UseFileExplorerTreeResult {
|
||||
const [dirCache, setDirCache] = useState<Record<string, DirCache>>({})
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user