fix(files): 在途层渲染 loading 行,消除新展开文件夹的空目录闪烁(#789 移植到 loadLevels 新形状)

移植 PR #789 的语义到 v0.24.1(98a446b)重写后的加载形状,原 diff 基于
已不存在的 loadDir 形状,不再适用:

- 核心条件原样保留:renderLevel 对「未请求」(undefined)与「在途标记」
  (loadLevels 非强制路径写入的 {} —— 无 entries 无 error)都画 loading
  行。修复前标记落进 entries ?? [] 渲染零行:展开新目录闪「loading →
  看似又折叠了 → 条目」,且首挂载的根层也是空体。settled 层必带 entries
  (不可读层另带 error),条件不会误伤真实数据。
- 原 PR 改在 per-level loadDir 请求时代;现形状 loadLevels 非强制路径先
  storeLevel(path, {}) 再发批量 fs.trees,在途标记形状未变,故只需渲染
  侧一处扩展,加载逻辑零改动(force 路径保留旧行的语义不受影响)。
- 测试 tests/file-tree-loading.spec.tsx 随形状移植:原版 gate 住单层
  fsTree 路由,现 gate 住批量 fsTrees 的 { levels } envelope;并按真实
  用户流拆成两批——先挂载根层、落地后再展开子目录触发第二批(批量语义
  本身由 file-tree-batch-load.spec.tsx 单独守护)。三个用例语义不变:
  展开期间 loading 行不消失、真空目录渲染零行不卡 loading、整批失败出
  错误行。判别性验证:回退修复后前两用例红(错误路径用例两态都绿,它
  守护边界而非本次回归)。
- 原 PR 未新增词典 key(复用既有 t('loading')),本次同样零词典改动,
  无需触碰 19 份第三语言词典。
- 全套件对照:改动前后均 1485 通过 / 6 失败;6 个失败(locales ja 缺
  2 key、plugin-meta 打包、tasks-model ×4)在干净 origin/main @1499502
  上同样复现,属 main 既有问题,与本提交无关。
This commit is contained in:
HuanLinOTO committed 2026-10-01 17:15:49 +08:00
1 parent 1499502bfa
commit e10510f29a
2 files changed
+225 -1

No files matched your search

+9 -1
View File
@@ -1528,7 +1528,15 @@ export function FileTree(props: {
const renderLevel = (dir: string, depth: number): ReactNode => {
const level = data[dir]
const head = newFolder?.dir === dir ? renderNewFolderRow(dir, depth) : null
if (level === undefined) {
// Both the not-yet-requested level (`undefined`) and the in-flight marker
// `loadLevels` stores (`{}` — no entries, no error yet) draw the loading
// row. Without the second half the marker fell into `entries ?? []` and
// rendered an EMPTY level (zero rows), so expanding a fresh folder flashed
// "loading row → nothing under the folder (looks collapsed again) →
// entries" for the whole request — and a fresh mount showed a blank body
// under the root row. A settled level always carries `entries` (an
// unreadable one carries `error` too), so this never misfires.
if (level === undefined || (level.entries === undefined && level.error === undefined)) {
return (
<>
{head}
+216
View File
@@ -0,0 +1,216 @@
/**
* FileTree in-flight level rendering: the `{}` marker `loadLevels` stores while
* a listing request is running must draw the LOADING row, not an empty level.
* Regression guard for the "expand a fresh folder flashes loading → collapsed
* → entries" flicker: the marker used to fall into `entries ?? []` and render
* zero rows for the whole request, so the folder looked collapsed again until
* the response landed (a fresh mount showed a blank body under the root row).
*
* Ported from PR #789, which gated the per-level `fsTree` route, onto the
* batched `fsTrees` shape: levels still settle one-by-one through per-dir
* gates, but mount and expand are now TWO batch calls (the second lists only
* the newly expanded directory — the batching itself is guarded by
* file-tree-batch-load.spec.tsx, this suite only owns the in-flight frame).
*/
// @vitest-environment jsdom
import { afterEach, 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 { t } from '../src/client/locales.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
interface Listing {
entries: Array<{ name: string; path: string; isDir: boolean }>
}
/** One gate per requested directory: the test decides when each settles. */
const gates = vi.hoisted(() => {
const pending = new Map<string, { promise: Promise<Listing>; resolve: (listing: Listing) => void; reject: (error: Error) => void }>()
const gate = (dir: string): Promise<Listing> => {
const existing = pending.get(dir)
if (existing !== undefined) return existing.promise
let resolve!: (listing: Listing) => void
let reject!: (error: Error) => void
const promise = new Promise<Listing>((res, rej) => { resolve = res; reject = rej })
pending.set(dir, { promise, resolve, reject })
return promise
}
return { gate, pending }
})
vi.mock('../src/client/api.ts', () => ({
api: {
// The batched route: each requested level settles when its gate does.
fsTrees: (_scope: unknown, paths: readonly string[]) =>
Promise.all(paths.map(path => gates.gate(path).then(listing => ({ path, entries: listing.entries, truncated: false }))))
.then(levels => ({ levels })),
// The tree reads the shared git-status store; a non-repo answer keeps
// every row plain.
gitStatus: async () => ({ isRepo: false, entries: [] }),
},
downloadUrl: () => '/sidebar/file',
isOutsideWorkspaceMessage: () => false,
}))
/** The smallest WebSocket the directory watcher talks to (see its spec). */
class FakeSocket {
static instances: FakeSocket[] = []
static readonly OPEN = 1
static readonly CONNECTING = 0
readyState = FakeSocket.CONNECTING
readonly url: string
onopen: (() => void) | null = null
onmessage: ((event: { data: string }) => void) | null = null
onclose: (() => void) | null = null
constructor(url: string) {
this.url = url
FakeSocket.instances.push(this)
}
send(): void {}
close(): void { this.readyState = 3 }
open(): void { this.readyState = FakeSocket.OPEN; this.onopen?.() }
frame(payload: unknown): void { this.onmessage?.({ data: JSON.stringify(payload) }) }
}
const DIR_ENTRY = (name: string): { name: string; path: string; isDir: boolean } =>
({ name, path: `/tmp/${name}`, isDir: true })
interface Harness {
container: HTMLDivElement
/** Re-render with a new expansion set (the expand happens in the caller). */
rerender: (expanded: string[]) => void
unmount: () => void
}
function mountTree(expanded: string[]): Harness {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const render = (dirs: string[]): void => {
root.render(createElement(FileTree, {
sessionId: 's1',
cwd: '/tmp',
expanded: dirs,
revealed: [],
onToggle: () => {},
onOpenFile: () => {},
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
}))
}
act(() => { render(expanded) })
return {
container,
rerender: (dirs: string[]) => { act(() => { render(dirs) }) },
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
}
/** Every rendered row (entry rows and the plain loading/error rows). */
function rows(container: HTMLElement): HTMLElement[] {
return [...container.querySelectorAll<HTMLElement>('[class*="explorerRow"]')]
}
/** The row whose name span matches (entry rows carry `.explorerName`). */
function rowByName(container: HTMLElement, name: string): HTMLElement {
const row = rows(container).find(el => el.querySelector('[class*="explorerName"]')?.textContent === name)
if (row === undefined) throw new Error(`row not found: ${name}`)
return row
}
/** Plain rows render no name span; the loading one shows exactly `t('loading')`. */
const loadingRows = (container: HTMLElement): HTMLElement[] =>
rows(container)
.filter(row => row.querySelector('[class*="explorerName"]') === null)
.filter(row => row.textContent === t('loading'))
/** Settle one directory's listing and flush the batch promise chain. */
async function release(dir: string, listing: Listing): Promise<void> {
await act(async () => {
gates.pending.get(dir)!.resolve(listing)
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
})
}
/** Fail one directory's listing (the whole batch rejects — the loadLevels
* catch turns it into per-level error rows for levels with nothing cached). */
async function fail(dir: string, message: string): Promise<void> {
await act(async () => {
gates.pending.get(dir)!.reject(new Error(message))
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
})
}
let harness: Harness
beforeEach(() => {
FakeSocket.instances = []
vi.stubGlobal('WebSocket', FakeSocket)
})
afterEach(() => {
harness.unmount()
gates.pending.clear()
document.body.innerHTML = ''
vi.unstubAllGlobals()
})
describe('FileTree in-flight level rendering', () => {
it('keeps the loading row under a freshly expanded folder until its listing lands', async () => {
harness = mountTree([])
// Mount batch (root only) in flight: exactly one loading row under the
// root row (the root row itself is drawn from cwd, not from the listing).
// Before the fix the `{}` marker rendered an EMPTY body — zero rows.
expect(loadingRows(harness.container)).toHaveLength(1)
// Root lands; expanding src fires the SECOND batch, which lists only src
// (the root level is cached). While that batch is in flight src keeps ONE
// loading row nested under its own row. Before the fix this frame rendered
// ZERO rows under src — the "folder collapsed again" flash.
await release('/tmp', { entries: [DIR_ENTRY('src'), { name: 'a.ts', path: '/tmp/a.ts', isDir: false }] })
harness.rerender(['/tmp/src'])
const loading = loadingRows(harness.container)
expect(loading).toHaveLength(1)
expect(loading[0]!.parentElement).toBe(rowByName(harness.container, 'src').parentElement)
// The listing lands: rows swap in, no loading row remains.
await release('/tmp/src', { entries: [{ name: 'inner.ts', path: '/tmp/src/inner.ts', isDir: false }] })
expect(loadingRows(harness.container)).toHaveLength(0)
expect(() => rowByName(harness.container, 'inner.ts')).not.toThrow()
})
it('renders a truly empty directory as zero rows, not a stuck loading row', async () => {
harness = mountTree([])
await release('/tmp', { entries: [DIR_ENTRY('empty')] })
harness.rerender(['/tmp/empty'])
// In flight: the empty folder still shows its loading row.
expect(loadingRows(harness.container)).toHaveLength(1)
// Landed as an empty listing: no loading row, and no child row below the
// folder — it is the tree's last row.
await release('/tmp/empty', { entries: [] })
expect(loadingRows(harness.container)).toHaveLength(0)
const all = rows(harness.container)
expect(all[all.length - 1]).toBe(rowByName(harness.container, 'empty'))
})
it('shows the error row when the listing request fails', async () => {
harness = mountTree([])
await release('/tmp', { entries: [DIR_ENTRY('boom')] })
harness.rerender(['/tmp/boom'])
await fail('/tmp/boom', 'boom')
expect(loadingRows(harness.container)).toHaveLength(0)
const errorRow = rows(harness.container)
.filter(row => row.querySelector('[class*="explorerName"]') === null)
.find(row => row.textContent === 'boom')
expect(errorRow).toBeDefined()
})
})