按当前 dev 重写贡献者 PR #264 的两项核心意图: 1. 面包屑折叠(VSCode "compact folders"):host 给「内容恰为一个有效 子项」的目录行标记 `compact`,client 把单目录链折叠成一行 `a/b/c` 并整链展开/折叠。 2. `explorerExclude`(VS Code `files.exclude` 风格的 glob 子集):匹配 条目从文件树与文件名搜索中彻底移除;树与搜索共用同一份 host 侧编译 好的 matcher,两个界面永不失配。 为什么按 dev 现有结构重写而不是机械解冲突——证据卡逐条点名的 dev 侧变化: - **客户端树已换成 DirRow 记忆化组件 + loadLevels/api.fsTrees 批量路由**。 PR 改的是旧的 `expanded.includes(...)` 内联目录行与单路径 `api.fsTree`, 该上下文在 dev 已不存在。折叠因此接在 renderLevel/visibleRows 的链上, 并新增「每级缓存修订一次」的链缓存:DirRow 按 prop 身份 memo,每次渲染 新建数组会让选择/悬停把每个目录行都重渲。 - **`api.fsTree(scope, path, signal?)` 的第三位已经是 AbortSignal**,PR 的 `api.fsTree(scope, dir, exclude)` 会把数组当 signal。exclude 统一排在 signal 之前(`fsTree`/`fsTrees`/`fsSearch` 三处一致)。 - **dev 的 `listDirectory` 有 1.5s TTL 缓存,PR 是直接读盘**。照搬会让不同 排除集共用一份缓存(改完排除列表仍读到旧行),而 pref 变更没有可搭的 失效钩子。故把模式集的身份并入 cacheKey(新增 `ExcludeMatcher.key`,含 锚点 root 与大小写折叠语义):同列表命中缓存,改列表即换键。 - **文件树的真实入口是批量路由 `fs.trees`**(挂载/展开一次 POST),PR 只 改了 `fs.tree`/`fs.search` 两处——不接批量路由等于 exclude 不生效。 - PR body 声称移除 `explorerShowHidden`,但净 diff 对它零命中、dev 与 PR 合并基也都没有该键,属失效声明,不做产品取舍。 复用的部分(与 dev 无耦合):`src/exclude-patterns.ts` 与 `src/client/file-tree-compact.ts` 两个纯逻辑模块逐字取用(前者仅新增缓存 身份 `ExcludeMatcher.key`)。设置 UI 沿用 PR 的声明式 `patterns` 行类型 (chips + 删除钮 + 常驻添加输入框,原子提交整表),5 个新词条按仓库规则 同步全部 21 份词典;`src/client/service.ts` 的能力清单新增 `settingPatterns` 并同步 docs/external-plugin-guide.md。 门禁:pnpm typecheck 0;pnpm exec vitest run --maxWorkers=3 全绿 (165 files / 1847 passed / 13 skipped);npx eslint 45 个改动文件 0; 新增与改动的 spec 单跑 154 passed;pnpm build 0。 Refs #264 Co-authored-by: shyuan-hub <311810858+shyuan-hub@users.noreply.github.com>
254 lines
9.2 KiB
TypeScript
254 lines
9.2 KiB
TypeScript
/**
|
|
* Explorer breadcrumb folding in the real tree (VSCode "compact folders").
|
|
*
|
|
* The host marks a directory row `compact` when its contents are exactly one
|
|
* effective child; this spec drives the CLIENT half against the level cache the
|
|
* batch route fills:
|
|
* - a chain of singleton dirs renders as ONE `a/b/c` row, and the collapsed
|
|
* links' levels are PRELOADED (otherwise the label would grow a segment at
|
|
* a time as the user clicks);
|
|
* - a plain click toggles the WHOLE chain, so the row opens and closes as one
|
|
* (only ever toggling the head would strand an earlier-expanded link open);
|
|
* - the open row descends into the chain TAIL, not the head;
|
|
* - the exclude list is carried on every `fs.trees` request and a changed list
|
|
* wipes the level cache (the host filters, so cached rows are stale).
|
|
*/
|
|
// @vitest-environment jsdom
|
|
import { afterEach, beforeAll, beforeEach, 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 { setupReactAct } from './test-utils.ts'
|
|
setupReactAct()
|
|
|
|
// vitest 4.1.11+ follows the OS locale; pin en-US so the copy is English.
|
|
beforeAll(() => {
|
|
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
|
|
})
|
|
|
|
const fsTrees = vi.hoisted(() => vi.fn())
|
|
|
|
vi.mock('../src/client/api.ts', () => ({
|
|
api: {
|
|
fsTree: vi.fn(),
|
|
fsTrees: (...args: unknown[]) => fsTrees(...args),
|
|
gitStatus: async () => ({ isRepo: false, entries: [] }),
|
|
},
|
|
downloadUrl: () => '/sidebar/file',
|
|
isOutsideWorkspaceMessage: () => false,
|
|
}))
|
|
|
|
/** A directory row; `compact` is the host's singleton mark. */
|
|
function dir(path: string, compact = false): {
|
|
name: string; path: string; isDir: boolean; hidden: boolean; isSymlink: boolean; broken: boolean; compact?: boolean
|
|
} {
|
|
const name = path.slice(path.lastIndexOf('/') + 1)
|
|
return {
|
|
name,
|
|
path,
|
|
isDir: true,
|
|
hidden: name.startsWith('.'),
|
|
isSymlink: false,
|
|
broken: false,
|
|
...(compact ? { compact: true } : {}),
|
|
}
|
|
}
|
|
|
|
/** A file row. */
|
|
function file(path: string): {
|
|
name: string; path: string; isDir: boolean; hidden: boolean; isSymlink: boolean; broken: boolean
|
|
} {
|
|
const name = path.slice(path.lastIndexOf('/') + 1)
|
|
return { name, path, isDir: false, hidden: name.startsWith('.'), isSymlink: false, broken: false }
|
|
}
|
|
|
|
/**
|
|
* `/tmp` → `a`, then a/b, then a/b/c, then a real file. Every directory on the
|
|
* chain is a singleton, so `a` folds all the way to `a/b/c`.
|
|
*/
|
|
function levelOf(path: string): {
|
|
path: string; entries: unknown[]; truncated: boolean
|
|
} {
|
|
switch (path) {
|
|
case '/tmp':
|
|
return { path, entries: [dir('/tmp/a', true), file('/tmp/readme.md')], truncated: false }
|
|
case '/tmp/a':
|
|
return { path, entries: [dir('/tmp/a/b', true)], truncated: false }
|
|
case '/tmp/a/b':
|
|
return { path, entries: [dir('/tmp/a/b/c', true)], truncated: false }
|
|
default:
|
|
return { path, entries: [file(`${path}/leaf.txt`)], truncated: false }
|
|
}
|
|
}
|
|
|
|
/** The smallest WebSocket the directory watcher talks to. */
|
|
class FakeSocket {
|
|
static readonly OPEN = 1
|
|
static readonly CONNECTING = 0
|
|
readyState = FakeSocket.CONNECTING
|
|
onopen: (() => void) | null = null
|
|
onmessage: ((event: { data: string }) => void) | null = null
|
|
onclose: (() => void) | null = null
|
|
constructor(readonly url: string) {}
|
|
send(): void {}
|
|
close(): void { this.readyState = 3 }
|
|
}
|
|
|
|
interface Harness {
|
|
container: HTMLDivElement
|
|
toggled: string[]
|
|
rerender: (expanded: string[], exclude?: readonly string[]) => void
|
|
unmount: () => void
|
|
}
|
|
|
|
function mountTree(expanded: string[] = [], exclude?: readonly string[]): Harness {
|
|
const container = document.createElement('div')
|
|
document.body.append(container)
|
|
const root: Root = createRoot(container)
|
|
const toggled: string[] = []
|
|
const render = (dirs: string[], patterns: readonly string[] | undefined): void => {
|
|
root.render(createElement(FileTree, {
|
|
sessionId: 's1',
|
|
cwd: '/tmp',
|
|
expanded: dirs,
|
|
revealed: [],
|
|
onToggle: (path: string) => { toggled.push(path) },
|
|
onOpenFile: () => {},
|
|
onReferenceFile: () => {},
|
|
...(patterns === undefined ? {} : { exclude: patterns }),
|
|
refreshTick: 0,
|
|
onUploadRequest: () => {},
|
|
busy: false,
|
|
}))
|
|
}
|
|
act(() => { render(expanded, exclude) })
|
|
return {
|
|
container,
|
|
toggled,
|
|
rerender: (dirs: string[], patterns?: readonly string[]) => {
|
|
act(() => { render(dirs, patterns ?? exclude) })
|
|
},
|
|
unmount: () => { act(() => { root.unmount() }); container.remove() },
|
|
}
|
|
}
|
|
|
|
/** Flush the batch promise chain. */
|
|
async function flush(): Promise<void> {
|
|
await act(async () => {
|
|
await Promise.resolve()
|
|
await Promise.resolve()
|
|
await Promise.resolve()
|
|
await Promise.resolve()
|
|
})
|
|
}
|
|
|
|
/** The directory rows' rendered labels, in document order. */
|
|
function rowLabels(container: HTMLElement): string[] {
|
|
return [...container.querySelectorAll<HTMLElement>('[role="button"]')]
|
|
.map(row => row.textContent ?? '')
|
|
}
|
|
|
|
/** The row whose label is exactly `label`. */
|
|
function rowByLabel(container: HTMLElement, label: string): HTMLElement {
|
|
const row = [...container.querySelectorAll<HTMLElement>('[role="button"]')]
|
|
.find(candidate => (candidate.textContent ?? '').startsWith(label))
|
|
if (row === undefined) throw new Error(`no row "${label}" in ${JSON.stringify(rowLabels(container))}`)
|
|
return row
|
|
}
|
|
|
|
/** Every path the tree has asked for, across all batches. */
|
|
function requestedPaths(): string[] {
|
|
return fsTrees.mock.calls.flatMap(call => call[1] as string[])
|
|
}
|
|
|
|
let harness: Harness
|
|
beforeEach(() => {
|
|
vi.stubGlobal('WebSocket', FakeSocket)
|
|
fsTrees.mockReset()
|
|
fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({
|
|
levels: paths.map(path => levelOf(path)),
|
|
}))
|
|
})
|
|
|
|
afterEach(() => {
|
|
harness.unmount()
|
|
document.body.innerHTML = ''
|
|
vi.unstubAllGlobals()
|
|
})
|
|
|
|
describe('FileTree breadcrumb folding', () => {
|
|
it('folds a singleton chain into ONE a/b/c row and preloads the collapsed links', async () => {
|
|
harness = mountTree()
|
|
await flush()
|
|
|
|
// The chain renders as one row carrying the full breadcrumb…
|
|
const labels = rowLabels(harness.container)
|
|
expect(labels.some(label => label.startsWith('a/b/c'))).toBe(true)
|
|
// …and NOT as the three nested rows it would be unfolded.
|
|
expect(labels.filter(label => /^a\/?b?\/?c?/.test(label))).toHaveLength(1)
|
|
// The collapsed links' levels were loaded ahead of any expansion: without
|
|
// them the label would grow a segment per click.
|
|
expect(requestedPaths().sort()).toEqual(['/tmp', '/tmp/a', '/tmp/a/b', '/tmp/a/b/c'].sort())
|
|
// The sibling file is untouched by the fold.
|
|
expect(harness.container.textContent).toContain('readme.md')
|
|
})
|
|
|
|
it('toggles the WHOLE chain on a plain click, so the row closes as one', async () => {
|
|
// The head was expanded by an earlier interaction (before the fold formed):
|
|
// closing the row must collapse every link, not just the head.
|
|
harness = mountTree(['/tmp/a'])
|
|
await flush()
|
|
act(() => { rowByLabel(harness.container, 'a/b/c').click() })
|
|
expect(harness.toggled).toEqual(['/tmp/a'])
|
|
})
|
|
|
|
it('expands every link of the chain when the row is closed', async () => {
|
|
harness = mountTree()
|
|
await flush()
|
|
act(() => { rowByLabel(harness.container, 'a/b/c').click() })
|
|
// Closed → open: every link that is not expanded yet gets toggled, which is
|
|
// what makes the tail's children render.
|
|
expect(harness.toggled.sort()).toEqual(['/tmp/a', '/tmp/a/b', '/tmp/a/b/c'].sort())
|
|
})
|
|
|
|
it('descends into the chain TAIL when open, not the head', async () => {
|
|
harness = mountTree(['/tmp/a/b/c'])
|
|
await flush()
|
|
// The folded row shows the tail's contents (the chain's end), never a/b's.
|
|
expect(harness.container.textContent).toContain('leaf.txt')
|
|
expect(rowLabels(harness.container).some(label => label.startsWith('a/b/c'))).toBe(true)
|
|
})
|
|
|
|
it('carries the exclude list on every request, and a changed list wipes the cache', async () => {
|
|
harness = mountTree([], ['node_modules'])
|
|
await flush()
|
|
// Every batch carries the patterns as its third argument.
|
|
for (const call of fsTrees.mock.calls) {
|
|
expect(call[2]).toEqual(['node_modules'])
|
|
}
|
|
expect(requestedPaths()).toContain('/tmp')
|
|
fsTrees.mockClear()
|
|
// A changed list must re-list the visible set: the HOST filters the rows,
|
|
// so what is cached was filtered by the previous list.
|
|
harness.rerender([], ['.DS_Store', 'node_modules'])
|
|
await flush()
|
|
expect(requestedPaths()).toContain('/tmp')
|
|
for (const call of fsTrees.mock.calls) {
|
|
expect(call[2]).toEqual(['.DS_Store', 'node_modules'])
|
|
}
|
|
})
|
|
|
|
it('does not re-list when a value-equal exclude list changes identity', async () => {
|
|
harness = mountTree([], ['node_modules'])
|
|
await flush()
|
|
fsTrees.mockClear()
|
|
// A fresh array with the same content: the cache and the effect key on the
|
|
// VALUE, so a re-render must not cost another listing.
|
|
harness.rerender([], ['node_modules'])
|
|
await flush()
|
|
expect(fsTrees).not.toHaveBeenCalled()
|
|
})
|
|
})
|