Files
apes-sidebar/tests/file-tree-multiselect.spec.tsx
T
Menghuan1918 ee1fe05067 feat(sidebar): 菜单层级/性能 + 选中条吸底 + 打包进度 + 修复「在侧边打开」
用户实测反馈 5 条:

1) 文件列表性能 / 右键菜单不再刷屏(先测量后改,探针 tests/file-tree-menu-perf.spec.tsx)
   - 宿主应用列表按路径缓存:N 次打开菜单只请求 1 次(原每次 1 次 + Loading 帧)
   - 行上的 git 数据改为原始值(tone/letter):共享 store 每次轮询重建对象不再触达行
     (探针:开窗 folderIcons 4 → 0;root 行也 memo 化)
   - 菜单开关不触发目录重列(fsTree=0);实测「菜单打开期间暂停轮询」会让变更行瞬时
     掉色并多两次重渲染,故按测量结果放弃该做法(数字与理由写进探针注释)

2) 「已选择 N 项」条移到底部:滚动容器最后一个内容子节点 + sticky bottom(不遮最后
   一行),窄栏 flex-wrap 换行不出横向滚动条

3) 菜单层级重构:一级只留默认动作(宿主默认应用 / 打开方式 ▸ / 在文件管理器中显示 /
   新 Tab / 在侧边打开 / 下载 / 压缩并下载 / 复制路径 / 重命名 / 删除;目录行另有
   新建文件夹、上传到此处),应用列表整体收进「打开方式」子菜单;宿主探测到本机关联
   应用时默认不显示插件自研 open-with 项目,新增设置开关 openWithPluginTargets
   (editor descriptor 的 pluginToggles)可强制并存;宿主不可用时插件项目照旧

4) 压缩并下载显示进度:宿主改为可观测任务(archive.build / archive.status /
   /sidebar/archive?id=,4 并发 + 5 分钟 TTL + sessionId 绑定,buildZip 逐条目
   onProgress),客户端轮询 250ms 显示「正在打包 done/total · N%」,ready 后 blob 下载,
   失败进 zipFailed

5) 修复「在侧边打开没有效果」:根因是它只写插件底部工作台(原生右侧栏的 tab 不在
   bottomSplits 里),现按承载面分流 —— 原生 tab 走 service.openTab(target:'side') →
   宿主 openResource(preferNewPane, revealIfOpened:false) 真正分栏;底部工作台行为不变
   (接入 API 变更已同步 docs/external-plugin-guide.md)

验证:typecheck / lint / test(135 文件 1461 通过)/ build 全绿;
DSH_CMD='npx -y --package @deepseek-ai/dsh@0.1.7-rc.1 dsh' pnpm test:mount 7/7 通过;
新增/更新测试:menu-perf(3)、archive(10)、open-in-app(18)、open-with(10)、multiselect(9)、
zip(37)、service(64)、editor-host(11)、builtins(23)、locales(20)
2026-09-28 20:11:46 +08:00

277 lines
12 KiB
TypeScript

/**
* FileTree multi-selection (VS Code semantics): Ctrl/Cmd+click toggles one
* row and seats the Shift anchor, Shift+click selects the visible range from
* that anchor, Escape and a blank click clear the selection, and a right
* click outside the selection collapses it onto the row. A non-empty
* selection shows the batch bar (count + copy paths / delete / clear); the
* batch delete confirms once, removes sequentially, and stops on the first
* failure with the error strip.
*
* The other half of the contract is what must NOT change: an unmodified click
* still opens a file / toggles a directory and drops the selection.
*/
// @vitest-environment jsdom
import { beforeAll, afterEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'node:fs'
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'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
// vitest 4.1.11+ follows the OS locale; pin en-US so the bar's copy is English.
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
const { fsRemove, fsTree } = vi.hoisted(() => ({
fsRemove: vi.fn(async (_scope: unknown, path: string) => ({ path })),
fsTree: vi.fn(async () => ({
path: '/tmp',
entries: [
{ name: 'sub', path: '/tmp/sub', isDir: true },
{ name: 'a.ts', path: '/tmp/a.ts', isDir: false },
{ name: 'b.ts', path: '/tmp/b.ts', isDir: false },
],
truncated: false,
})),
}))
vi.mock('../src/client/api.ts', () => ({
api: {
fsTree,
fsRemove,
// The tree reads the shared git-status store; a non-repo answer keeps
// every row plain (this spec is about the selection).
gitStatus: async () => ({ isRepo: false, entries: [] }),
},
downloadUrl: () => '/sidebar/file',
isOutsideWorkspaceMessage: () => false,
}))
interface Harness {
container: HTMLDivElement
opened: string[]
toggled: string[]
unmount: () => void
}
async function mountTree(expanded: string[] = []): Promise<Harness> {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const opened: string[] = []
const toggled: string[] = []
await act(async () => {
root.render(createElement(FileTree, {
sessionId: 's1',
cwd: '/tmp',
store: createSidebarStore(),
expanded,
revealed: [],
onToggle: (path: string) => { toggled.push(path) },
onOpenFile: (path: string) => { opened.push(path) },
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
}))
})
return {
container,
opened,
toggled,
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
}
/** One tree row by its displayed name. */
function rowByName(container: HTMLElement, name: string): HTMLElement {
const row = [...container.querySelectorAll<HTMLElement>('[role="button"]')]
.find(el => el.querySelector('[class*="explorerName"]')?.textContent === name)
if (row === undefined) throw new Error(`row not found: ${name}`)
return row
}
function click(el: Element, init: MouseEventInit = {}): void {
act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ...init })) })
}
function rightClick(el: Element): void {
act(() => {
el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 }))
})
}
function pressEscape(el: Element): void {
act(() => { el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })) })
}
/** The batch bar (the kit's section band carries the page class). */
function selectionBar(container: HTMLElement): HTMLElement | null {
return container.querySelector<HTMLElement>('[class*="explorerSelectionBar"]')
}
/** The names of the rows currently rendered as selected. */
function selectedNames(container: HTMLElement): string[] {
return [...container.querySelectorAll<HTMLElement>('[class*="explorerRowSelected"]')]
.map(row => row.querySelector('[class*="explorerName"]')?.textContent ?? '')
}
/** One batch-bar action by its label. */
function barAction(container: HTMLElement, label: string): HTMLElement {
const button = [...(selectionBar(container)?.querySelectorAll<HTMLElement>('button') ?? [])]
.find(el => el.textContent === label)
if (button === undefined) throw new Error(`bar action not found: ${label}`)
return button
}
let harness: Harness
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
fsRemove.mockReset()
fsRemove.mockImplementation(async (_scope: unknown, path: string) => ({ path }))
fsTree.mockClear()
})
describe('FileTree multi-selection', () => {
it('keeps the unmodified click semantics and drops the selection', async () => {
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
expect(selectionBar(harness.container)).not.toBeNull()
// A plain click opens the file (and clears the batch).
click(rowByName(harness.container, 'b.ts'))
expect(harness.opened).toEqual(['/tmp/b.ts'])
expect(selectionBar(harness.container)).toBeNull()
// A plain click on a directory row still toggles it.
click(rowByName(harness.container, 'sub'))
expect(harness.toggled).toEqual(['/tmp/sub'])
expect(harness.opened).toEqual(['/tmp/b.ts'])
})
it('Ctrl/Cmd+click toggles rows and the bar counts them', async () => {
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
expect(selectedNames(harness.container)).toEqual(['a.ts'])
expect(selectionBar(harness.container)?.textContent).toContain('1 selected')
click(rowByName(harness.container, 'b.ts'), { metaKey: true })
expect(selectedNames(harness.container)).toEqual(['a.ts', 'b.ts'])
expect(selectionBar(harness.container)?.textContent).toContain('2 selected')
// Toggling the same row off again leaves exactly the other one.
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
expect(selectedNames(harness.container)).toEqual(['a.ts'])
})
it('Shift+click selects the visible range from the Ctrl-seated anchor', async () => {
harness = await mountTree()
// The anchor is 'b.ts' (the last visible row), so the range reaches 'a.ts'.
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
click(rowByName(harness.container, 'a.ts'), { shiftKey: true })
expect(selectedNames(harness.container)).toEqual(['a.ts', 'b.ts'])
// A collapsed directory between two rows is part of the visible order.
click(rowByName(harness.container, 'sub'), { shiftKey: true })
expect(selectedNames(harness.container)).toEqual(['sub', 'a.ts', 'b.ts'])
})
it('Escape, the bar\'s Clear selection, and a click on the tree body all clear the selection', async () => {
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
pressEscape(harness.container.querySelector('[class*="explorerBody"]')!)
expect(selectionBar(harness.container)).toBeNull()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
act(() => { barAction(harness.container, 'Clear selection').click() })
expect(selectionBar(harness.container)).toBeNull()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
click(harness.container.querySelector('[class*="explorerBody"]')!)
expect(selectionBar(harness.container)).toBeNull()
})
it('right-click collapses the selection onto an unselected row and keeps a selected one', async () => {
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
// The row is already part of the selection: the whole batch survives.
rightClick(rowByName(harness.container, 'b.ts'))
expect(selectedNames(harness.container)).toEqual(['a.ts', 'b.ts'])
// An unselected row collapses the batch onto itself.
rightClick(rowByName(harness.container, 'sub'))
expect(selectedNames(harness.container)).toEqual(['sub'])
})
it('copies every selected absolute path, newline separated', async () => {
const writeText = vi.fn(async () => {})
Object.defineProperty(window.navigator, 'clipboard', { value: { writeText }, configurable: true })
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
await act(async () => { barAction(harness.container, 'Copy paths').click() })
expect(writeText).toHaveBeenCalledWith('/tmp/a.ts\n/tmp/b.ts')
})
it('deletes the whole selection through one confirmation, sequentially', async () => {
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
act(() => { barAction(harness.container, 'Delete selected').click() })
const dialog = document.querySelector('[role="dialog"]')
expect(dialog?.textContent).toContain('Delete 2 selected items?')
const confirm = [...document.querySelectorAll<HTMLElement>('button')]
.find(el => el.textContent === 'Delete selected' && el.closest('[role="dialog"]') !== null)!
await act(async () => { confirm.click() })
expect(fsRemove.mock.calls.map(call => call[1])).toEqual(['/tmp/a.ts', '/tmp/b.ts'])
expect(selectionBar(harness.container)).toBeNull()
})
it('docks the batch bar at the BOTTOM of the tree scroll container', async () => {
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
const body = harness.container.querySelector<HTMLElement>('[class*="explorerBody"]')!
const bar = harness.container.querySelector<HTMLElement>('[class*="explorerSelectionBar"]')!
// In flow AFTER every row (the menu's portal anchor and the hidden file
// input are the only trailing siblings) — never absolutely positioned
// over the rows, so scrolled to the bottom it sits BELOW the last row.
const rows = [...body.querySelectorAll<HTMLElement>('[class*="explorerRow"]')]
expect(rows.length).toBeGreaterThan(0)
expect(rows[rows.length - 1]!.compareDocumentPosition(bar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
// The only trailing siblings are the menu's portal anchor and the hidden
// file input, so the bar IS the last piece of tree content.
const content = [...body.children].filter(child =>
child.tagName !== 'INPUT' && !(child as HTMLElement).className.includes('_root_'))
expect(content[content.length - 1]).toBe(bar)
// jsdom has no layout: the sheet is the evidence for the docking mechanic.
const sheet = readFileSync('src/client/sidebar.module.css', 'utf8')
const rule = sheet.match(/\.explorerSelectionBar \{([\s\S]*?)\n\}/)?.[1]
expect(rule, 'the .explorerSelectionBar rule must exist').toBeDefined()
expect(rule).toContain('position: sticky')
expect(rule).toContain('bottom: 0')
expect(rule).not.toContain('position: absolute')
expect(rule).not.toContain('position: fixed')
// Narrow panels WRAP the chips instead of clipping them or scrolling.
const actions = sheet.match(/\.explorerSelectionActions \{([\s\S]*?)\n\}/)?.[1]
expect(actions).toContain('flex-wrap: wrap')
})
it('stops the batch at the first failure and reports it in the strip', async () => {
// The first path lands; the second refuses — the walk must stop there.
fsRemove
.mockImplementationOnce(async (_scope: unknown, path: string) => ({ path }))
.mockRejectedValueOnce(new Error('boom: refused'))
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
act(() => { barAction(harness.container, 'Delete selected').click() })
const confirm = [...document.querySelectorAll<HTMLElement>('button')]
.find(el => el.textContent === 'Delete selected' && el.closest('[role="dialog"]') !== null)!
await act(async () => { confirm.click() })
// Two attempts, in selection order, and nothing after the refusal.
expect(fsRemove.mock.calls.map(call => call[1])).toEqual(['/tmp/a.ts', '/tmp/b.ts'])
expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('boom: refused')
// The removed row left the selection; the refused one stays for a retry.
expect(selectedNames(harness.container)).toEqual(['b.ts'])
})
})