Files
apes-sidebar/tests/file-tree-row-memo.spec.tsx
T
Menghuan1918 36fbc5ac7e feat(sidebar): 文件页与文件变动页 UIUX 重构 + 全局组件抽取
文件页(FileTree/TreePanel)
- Ctrl/Cmd 多选 + Shift 按可见行序连选(Esc/点空白/右键收敛),批量条支持复制路径、批量删除(共享 ConfirmDialog + 顺序 fsRemove)
- Git 变更着色:行名按状态上色 + M/A/D/U 徽标,目录按 dirHasChanges 着色,非仓库静默降级(数据来自共享 git 状态存储)
- 新建文件夹:fs.mkdir 路由 + mkdirWorkspaceEntry + 内联输入行(Enter/Esc/blur/IME 守卫)
- 性能:FileRow/DirRow memo(含反向验证)、搜索 hidden 停车不再卸载树、level 拉取世代守卫 + AbortController、fs.tree truncated 提示、use-dir-watch 入参 memo
- 拖拽上传视觉 token 化(硬编码色清零);可见性下传后隐藏页签停止轮询
- 右键「打开方式」改为复用 DSH 自带 open-in-app(宿主探测的关联应用 + 文件管理器显示)

文件变动页(changes/diff)
- 36px 头(宿主 SegmentedControl)+ 单一 ChangeRow + SectionHeader 分组 + 吸底提交条单状态行 + 历史独立空态
- 修掉:双份空态、暂存失败 unhandled rejection、手动刷新被丢、仓库切换刷新两次、worktree 清单缺 repoRoot、工作树被自动切走、预览持旧快照、恢复高度未 clamp、session ops 无谓轮询
- DiffPane/DiffTab 共用 use-git-diff;修掉 DiffPane 的 untracked 预览从不渲染

全局组件与宿主接入
- 新增 src/client/ui(IconButton/Chip/SectionHeader/Notice/ConfirmDialog/StatusBadge + 共享 git 状态存储)
- 新增 src/client/open-in-app.ts(宿主 open-in-app 客户端适配),删除自研 open-with 全链路与 open.external 路由
- 客户端 inject 补 remote / remote.session:缺声明时 ctx.get('remote').session 会抛出并把整个面板打成错误条(真实挂载 lane 抓到)
- 词典:+25 键 / -20 openWith* / -noChanges,20 份同步

验证:typecheck / lint / test(126 文件 1322 通过)/ build 全绿;
DSH_CMD='npx -y --package @deepseek-ai/dsh@0.1.7-rc.1 dsh' pnpm test:mount 7/7 通过(含 tab sweep 与 perf lane)
2026-09-28 00:27:31 +08:00

135 lines
4.7 KiB
TypeScript

/**
* FileTree row memoization (the tree's performance contract): rows are
* `React.memo` components fed stable callbacks and per-row booleans, so an
* interaction that touches ONE row must re-render that row only — not the
* whole tree. The evidence is the icon resolver: it runs inside the row
* component, so counting its calls counts the rows that re-rendered.
*/
// @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 type { BetterSidebarService } from '../src/client/service.ts'
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 any copy is English.
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
vi.mock('../src/client/api.ts', () => ({
api: {
fsTree: 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 },
{ name: 'c.ts', path: '/tmp/c.ts', isDir: false },
],
truncated: false,
}),
// The tree reads the shared git-status store; a non-repo answer keeps
// every row plain (its arrival must not defeat the memo bail-out either).
gitStatus: async () => ({ isRepo: false, entries: [] }),
},
downloadUrl: () => '/sidebar/file',
isOutsideWorkspaceMessage: () => false,
}))
/** The icon resolutions per render: one per row that actually re-rendered. */
const fileIcons: string[] = []
const folderIcons: string[] = []
/** A minimal registry service: the counters ARE the re-render probe. */
const service = {
subscribe: () => () => {},
fileIcon: (path: string) => { fileIcons.push(path); return null },
folderIcon: (path: string) => { folderIcons.push(path); return null },
} as unknown as BetterSidebarService
interface Harness {
container: HTMLDivElement
unmount: () => void
}
async function mountTree(): Promise<Harness> {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
await act(async () => {
root.render(createElement(FileTree, {
sessionId: 'memo-spec',
cwd: '/tmp',
store: createSidebarStore(),
expanded: [],
revealed: [],
onToggle: () => {},
onOpenFile: () => {},
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
service,
}))
await Promise.resolve()
await Promise.resolve()
})
return {
container,
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 fireDragOver(el: Element): void {
const event = new Event('dragover', { bubbles: true, cancelable: true })
Object.defineProperty(event, 'dataTransfer', { value: { types: ['Files'], dropEffect: '' } })
act(() => { el.dispatchEvent(event) })
}
let harness: Harness
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
fileIcons.length = 0
folderIcons.length = 0
})
describe('FileTree row memoization', () => {
it('re-renders only the toggled row on a Ctrl+click selection change', async () => {
harness = await mountTree()
fileIcons.length = 0
act(() => {
rowByName(harness.container, 'a.ts')
.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ctrlKey: true }))
})
// The other three file rows kept their last render (memo bailed out).
expect(fileIcons).toEqual(['/tmp/a.ts'])
})
it('re-renders only the hovered directory row while a drag retargets', async () => {
harness = await mountTree()
folderIcons.length = 0
fileIcons.length = 0
fireDragOver(rowByName(harness.container, 'sub'))
// Every parent render resolves the ROOT row's icon; the memoized dir row
// resolves its own exactly once (its unhovered render was cached), and
// the file rows (whose drop target is the untouched /tmp) never re-render.
expect(folderIcons.filter(path => path === '/tmp/sub')).toEqual(['/tmp/sub'])
expect(fileIcons).toEqual([])
})
})