feat(files): tree rename (inline) + delete (confirmed) + submenu visual tether
资源管理器补全:文件树右键菜单新增「重命名」(行内编辑:预填+全选、 Enter/失焦提交、Esc 取消、IME 组合键守卫)与「删除」(Modal 确认,文件/ 目录文案区分,永久删除——宿主无回收站)。根行(工作区根)不提供两项, 服务端 fs.rename/fs.remove 双保险拒绝;目标已存在 409;link-aware—— symlink 行只改/删链接本身(lstat 判定),fence 校验对解析后目标进行。 落定收尾:pruneTree 清旧前缀缓存 + 收起 stale expanded + 单层重载父目录; tab 调解走 service(rename→updateTab 改路径改标题、delete→closeTab 关 受影响 tab,覆盖两侧分栏/底栏/浮动窗口,经 tree-mutations.ts)。 二级菜单视觉关系(layout.css,仍限 data-dsh-sidebar-submenu 作用域): 父行在子菜单打开期间保持高亮(宿主已渲染 aria-expanded="true"), 卡片间距 10px→4px(悬停走廊同步收窄),翻转规则一并 4px。 i18n 新增 7 key × 20 语言文件(locales.spec 的 key-set-parity 门禁)。 测试:fs-operations 追加 12 例(rename/remove 全失败面);新增 file-tree-rename-delete.spec.tsx 8 例(菜单可见性/重命名流/删除流/错误条); menu-flip.spec.tsx 契约扩展覆盖 tether 规则。设计文档 docs/plans/2026-09-04-file-tree-rename-delete-design.md。
This commit is contained in:
1 parent
76b57508f4
commit
e39ea92ade
34 files changed
+1070
-16
No files matched your search
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* FileTree explorer mutations: the context menu's rename (inline row editor)
|
||||
* and delete (confirmation modal) — menu-item visibility (never on the
|
||||
* workspace root row), the commit/cancel flows, the API calls with the row
|
||||
* path, the tab-reconciliation callbacks, and the failure strip.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { beforeAll, afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { FileTree } from '../src/client/FileTree.tsx'
|
||||
import { createSidebarStore } from '../src/client/state.ts'
|
||||
|
||||
// The act() environment flag (React 18.2 reads it before flushing effects).
|
||||
import { setupReactAct } from './test-utils.ts'
|
||||
setupReactAct()
|
||||
|
||||
// vitest 4.1.11+ follows the OS locale; pin en-US so menu copy is English.
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
|
||||
})
|
||||
|
||||
// vi.mock factories are hoisted above every declaration, so the shared
|
||||
// mocks ride vi.hoisted (mockClear in afterEach keeps the implementations).
|
||||
const { fsRename, fsRemove } = vi.hoisted(() => ({
|
||||
fsRename: vi.fn(async () => ({ path: '/tmp/renamed.ts' })),
|
||||
fsRemove: vi.fn(async () => ({ path: '/tmp/a.ts' })),
|
||||
}))
|
||||
|
||||
vi.mock('../src/client/api.ts', () => ({
|
||||
api: {
|
||||
fsTree: async () => ({
|
||||
entries: [
|
||||
{ name: 'a.ts', path: '/tmp/a.ts', isDir: false },
|
||||
{ name: 'sub', path: '/tmp/sub', isDir: true },
|
||||
],
|
||||
}),
|
||||
fsRename,
|
||||
fsRemove,
|
||||
},
|
||||
downloadUrl: () => '/sidebar/file',
|
||||
isOutsideWorkspaceMessage: () => false,
|
||||
}))
|
||||
|
||||
interface Harness {
|
||||
container: HTMLDivElement
|
||||
onPathRenamed: ReturnType<typeof vi.fn>
|
||||
onPathDeleted: ReturnType<typeof vi.fn>
|
||||
unmount: () => void
|
||||
}
|
||||
|
||||
async function mountTree(): Promise<Harness> {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root: Root = createRoot(container)
|
||||
const onPathRenamed = vi.fn()
|
||||
const onPathDeleted = vi.fn()
|
||||
await act(async () => {
|
||||
root.render(createElement(FileTree, {
|
||||
sessionId: 's1',
|
||||
cwd: '/tmp',
|
||||
store: createSidebarStore(),
|
||||
expanded: [],
|
||||
revealed: [],
|
||||
onToggle: () => {},
|
||||
onOpenFile: () => {},
|
||||
onOpenFileNewTab: () => {},
|
||||
onOpenFileSide: () => {},
|
||||
onReferenceFile: () => {},
|
||||
onPathRenamed,
|
||||
onPathDeleted,
|
||||
refreshTick: 0,
|
||||
onUploadRequest: () => {},
|
||||
busy: false,
|
||||
}))
|
||||
})
|
||||
return {
|
||||
container,
|
||||
onPathRenamed,
|
||||
onPathDeleted,
|
||||
unmount: () => { act(() => { root.unmount() }) },
|
||||
}
|
||||
}
|
||||
|
||||
/** One tree row by its displayed name (the root row included; it carries no
|
||||
* role="button", so the query rides the row class). */
|
||||
function rowByName(container: HTMLDivElement, name: string): HTMLElement {
|
||||
const row = [...container.querySelectorAll<HTMLElement>('[class*="explorerRow"]')]
|
||||
.find(el => el.querySelector('[class*="explorerName"]')?.textContent === name)
|
||||
if (row === undefined) throw new Error(`row "${name}" not found`)
|
||||
return row
|
||||
}
|
||||
|
||||
function openMenu(container: HTMLDivElement, name: string): void {
|
||||
const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 })
|
||||
act(() => { rowByName(container, name).dispatchEvent(event) })
|
||||
}
|
||||
|
||||
function menuLabels(): string[] {
|
||||
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].map(item => item.textContent ?? '')
|
||||
}
|
||||
|
||||
function clickMenuitem(label: string): void {
|
||||
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(el => el.textContent === label)
|
||||
if (item === undefined) throw new Error(`menuitem "${label}" not found`)
|
||||
act(() => { item.click() })
|
||||
}
|
||||
|
||||
/** Set a controlled input's value the React way (native setter + input). */
|
||||
function setNativeValue(el: HTMLInputElement, value: string): void {
|
||||
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
|
||||
if (setter === undefined) throw new Error('no native value setter')
|
||||
setter.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
|
||||
function pressKey(el: HTMLElement, key: string): void {
|
||||
el.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))
|
||||
}
|
||||
|
||||
let harness: Harness
|
||||
afterEach(() => {
|
||||
harness.unmount()
|
||||
document.body.innerHTML = ''
|
||||
fsRename.mockClear()
|
||||
fsRemove.mockClear()
|
||||
})
|
||||
|
||||
describe('FileTree rename/delete menu items', () => {
|
||||
it('offers rename and delete on file and directory rows, never on the root', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
expect(menuLabels()).toContain('Rename')
|
||||
expect(menuLabels()).toContain('Delete')
|
||||
openMenu(harness.container, 'sub')
|
||||
expect(menuLabels()).toContain('Rename')
|
||||
// The workspace root row (cwd itself) is the session — no mutations.
|
||||
openMenu(harness.container, 'tmp')
|
||||
expect(menuLabels()).not.toContain('Rename')
|
||||
expect(menuLabels()).not.toContain('Delete')
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileTree inline rename', () => {
|
||||
it('replaces the row with a prefilled editor; Enter commits via fsRename + onPathRenamed', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
clickMenuitem('Rename')
|
||||
const input = harness.container.querySelector<HTMLInputElement>('input[class*="explorerRenameInput"]')
|
||||
expect(input).not.toBeNull()
|
||||
expect(input!.value).toBe('a.ts')
|
||||
setNativeValue(input!, 'b.ts')
|
||||
await act(async () => { pressKey(input!, 'Enter') })
|
||||
expect(fsRename).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, '/tmp/a.ts', 'b.ts')
|
||||
expect(harness.onPathRenamed).toHaveBeenCalledWith('/tmp/a.ts', '/tmp/renamed.ts')
|
||||
// The editor row is gone (the commit closed it).
|
||||
expect(harness.container.querySelector('input[class*="explorerRenameInput"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('Escape cancels without touching the API', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
clickMenuitem('Rename')
|
||||
const input = harness.container.querySelector<HTMLInputElement>('input[class*="explorerRenameInput"]')!
|
||||
setNativeValue(input, 'b.ts')
|
||||
await act(async () => { pressKey(input, 'Escape') })
|
||||
expect(fsRename).not.toHaveBeenCalled()
|
||||
expect(harness.onPathRenamed).not.toHaveBeenCalled()
|
||||
expect(harness.container.querySelector('input[class*="explorerRenameInput"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects separator names client-side with the error strip, no API call', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
clickMenuitem('Rename')
|
||||
const input = harness.container.querySelector<HTMLInputElement>('input[class*="explorerRenameInput"]')!
|
||||
setNativeValue(input, 'a/b.ts')
|
||||
await act(async () => { pressKey(input, 'Enter') })
|
||||
expect(fsRename).not.toHaveBeenCalled()
|
||||
const alert = harness.container.querySelector('[role="alert"]')
|
||||
expect(alert?.textContent).toContain('path separators')
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileTree delete confirmation', () => {
|
||||
it('confirms through the modal, then calls fsRemove + onPathDeleted', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
clickMenuitem('Delete')
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog?.textContent).toContain('Delete "a.ts"?')
|
||||
expect(dialog?.textContent).toContain('permanently deletes the file')
|
||||
const confirm = [...document.querySelectorAll<HTMLElement>('button')].find(el => el.textContent === 'Delete' && el.closest('[role="dialog"]') !== null)!
|
||||
await act(async () => { confirm.click() })
|
||||
expect(fsRemove).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, '/tmp/a.ts')
|
||||
expect(harness.onPathDeleted).toHaveBeenCalledWith('/tmp/a.ts', false)
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('the directory copy names the recursive wipe', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'sub')
|
||||
clickMenuitem('Delete')
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog?.textContent).toContain('everything inside it')
|
||||
})
|
||||
|
||||
it('cancel closes the modal without calling anything', async () => {
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
clickMenuitem('Delete')
|
||||
const cancel = [...document.querySelectorAll<HTMLElement>('button')].find(el => el.textContent === 'Cancel')!
|
||||
act(() => { cancel.click() })
|
||||
expect(fsRemove).not.toHaveBeenCalled()
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('a server failure lands in the dismissable strip', async () => {
|
||||
fsRemove.mockRejectedValueOnce(new Error('boom: refused'))
|
||||
harness = await mountTree()
|
||||
openMenu(harness.container, 'a.ts')
|
||||
clickMenuitem('Delete')
|
||||
const confirm = [...document.querySelectorAll<HTMLElement>('button')].find(el => el.textContent === 'Delete' && el.closest('[role="dialog"]') !== null)!
|
||||
await act(async () => { confirm.click() })
|
||||
const alert = harness.container.querySelector('[role="alert"]')
|
||||
expect(alert?.textContent).toContain('boom: refused')
|
||||
expect(harness.onPathDeleted).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,8 @@
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { writeWorkspaceUpload } from '../src/fs-operations.ts'
|
||||
import { renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceUpload } from '../src/fs-operations.ts'
|
||||
|
||||
/** The test workspace root (each suite gets its own temp tree). */
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-'))
|
||||
@@ -150,3 +150,92 @@ describe('writeWorkspaceUpload', () => {
|
||||
expect(readFileSync(target, 'utf8')).toBe('original')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renameWorkspaceEntry', () => {
|
||||
it('renames a file within its directory', async () => {
|
||||
writeFileSync(join(root, 'old-name.txt'), 'x')
|
||||
const { path } = await renameWorkspaceEntry({ cwd: root, path: join(root, 'old-name.txt'), name: 'new-name.txt' })
|
||||
// The returned path is CANONICAL (realpath-resolved ancestors — on macOS
|
||||
// the tmpdir's /var becomes /private/var), so assert the shape, not the
|
||||
// lexical spelling.
|
||||
expect(path.endsWith('new-name.txt')).toBe(true)
|
||||
expect(existsSync(join(root, 'old-name.txt'))).toBe(false)
|
||||
expect(existsSync(join(root, 'new-name.txt'))).toBe(true)
|
||||
})
|
||||
|
||||
it('renames a directory (recursive content moves with it)', async () => {
|
||||
mkdirSync(join(root, 'olddir/nested'), { recursive: true })
|
||||
writeFileSync(join(root, 'olddir/nested/deep.txt'), 'x')
|
||||
await renameWorkspaceEntry({ cwd: root, path: join(root, 'olddir'), name: 'newdir' })
|
||||
expect(readFileSync(join(root, 'newdir/nested/deep.txt'), 'utf8')).toBe('x')
|
||||
})
|
||||
|
||||
it('is a no-op for the same name (destination-exists refusal must not bite)', async () => {
|
||||
writeFileSync(join(root, 'same.txt'), 'x')
|
||||
await renameWorkspaceEntry({ cwd: root, path: join(root, 'same.txt'), name: 'same.txt' })
|
||||
expect(existsSync(join(root, 'same.txt'))).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses single-segment violations (empty, dot, traversal, separators)', async () => {
|
||||
writeFileSync(join(root, 'r.txt'), 'x')
|
||||
for (const name of ['', '.', '..', 'a/b', 'a\\b']) {
|
||||
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'r.txt'), name }))
|
||||
.rejects.toMatchObject({ code: 'bad-request' })
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses an existing destination instead of clobbering it', async () => {
|
||||
writeFileSync(join(root, 'src.txt'), 'src')
|
||||
writeFileSync(join(root, 'dst.txt'), 'dst')
|
||||
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'src.txt'), name: 'dst.txt' }))
|
||||
.rejects.toMatchObject({ code: 'fs-error', status: 409 })
|
||||
expect(readFileSync(join(root, 'dst.txt'), 'utf8')).toBe('dst')
|
||||
})
|
||||
|
||||
it('refuses the workspace root and missing sources', async () => {
|
||||
await expect(renameWorkspaceEntry({ cwd: root, path: root, name: 'nope' }))
|
||||
.rejects.toMatchObject({ code: 'fs-error' })
|
||||
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'missing.txt'), name: 'x' }))
|
||||
.rejects.toMatchObject({ code: 'fs-error' })
|
||||
})
|
||||
|
||||
it('renames a symlink ROW, not its target', async () => {
|
||||
writeFileSync(join(root, 'target.txt'), 't')
|
||||
symlinkSync(join(root, 'target.txt'), join(root, 'alias.txt'))
|
||||
await renameWorkspaceEntry({ cwd: root, path: join(root, 'alias.txt'), name: 'alias2.txt' })
|
||||
expect(existsSync(join(root, 'alias.txt'))).toBe(false)
|
||||
expect(existsSync(join(root, 'alias2.txt'))).toBe(true)
|
||||
expect(readFileSync(join(root, 'target.txt'), 'utf8')).toBe('t')
|
||||
})
|
||||
})
|
||||
|
||||
describe('removeWorkspaceEntry', () => {
|
||||
it('unlinks a file', async () => {
|
||||
writeFileSync(join(root, 'gone.txt'), 'x')
|
||||
await removeWorkspaceEntry({ cwd: root, path: join(root, 'gone.txt') })
|
||||
expect(existsSync(join(root, 'gone.txt'))).toBe(false)
|
||||
})
|
||||
|
||||
it('removes a directory recursively', async () => {
|
||||
mkdirSync(join(root, 'tree/sub'), { recursive: true })
|
||||
writeFileSync(join(root, 'tree/sub/leaf.txt'), 'x')
|
||||
await removeWorkspaceEntry({ cwd: root, path: join(root, 'tree') })
|
||||
expect(existsSync(join(root, 'tree'))).toBe(false)
|
||||
})
|
||||
|
||||
it('unlinks a symlink row without touching (or recursing into) its target', async () => {
|
||||
mkdirSync(join(root, 'realdir'), { recursive: true })
|
||||
writeFileSync(join(root, 'realdir/keep.txt'), 'x')
|
||||
symlinkSync(join(root, 'realdir'), join(root, 'linkdir'))
|
||||
await removeWorkspaceEntry({ cwd: root, path: join(root, 'linkdir') })
|
||||
expect(existsSync(join(root, 'linkdir'))).toBe(false)
|
||||
expect(readFileSync(join(root, 'realdir/keep.txt'), 'utf8')).toBe('x')
|
||||
})
|
||||
|
||||
it('refuses the workspace root and missing paths', async () => {
|
||||
await expect(removeWorkspaceEntry({ cwd: root, path: root }))
|
||||
.rejects.toMatchObject({ code: 'fs-error' })
|
||||
await expect(removeWorkspaceEntry({ cwd: root, path: join(root, 'no-such.txt') }))
|
||||
.rejects.toMatchObject({ code: 'fs-error' })
|
||||
})
|
||||
})
|
||||
@@ -24,6 +24,18 @@ describe('layout.css contract', () => {
|
||||
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}~="left"] div[role="menu"] div[role="menu"]`)
|
||||
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}~="left"] div[role="menu"] div[role="menu"]::before`)
|
||||
})
|
||||
|
||||
it('keeps the submenu visual tether rules (parent highlight + tight gap)', () => {
|
||||
// Part 1 keeps the parent row lit while its submenu is open (the Menu
|
||||
// marks it aria-expanded); part 2 tightens the card gap to 4px with the
|
||||
// hover corridor narrowed to match. Losing either sends the submenu back
|
||||
// to reading as an unrelated floating card.
|
||||
const css = readFileSync('src/client/layout.css', 'utf8')
|
||||
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}] div[role="menu"] button[aria-expanded="true"]`)
|
||||
expect(css).toContain('left: calc(100% + 4px)')
|
||||
expect(css).toContain('right: calc(100% + 4px)')
|
||||
expect(css).toContain('width: 4px')
|
||||
})
|
||||
})
|
||||
|
||||
describe('submenuFlipTokens', () => {
|
||||
|
||||
Reference in new issue
Block a user