From 307513561bddae6fc69a1631ca918da8c5a032c4 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 23:11:11 +0800 Subject: [PATCH] =?UTF-8?q?fix(explorer):=20Shift=20=E8=BF=9E=E9=80=89?= =?UTF-8?q?=E6=94=B9=E7=94=A8=E6=B8=B2=E6=9F=93=E5=BA=8F=EF=BC=88#132?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `visibleRows` 的 walk 枚举的是层级缓存的宿主序(`level.entries`),而 `renderLevel` 画的是 `sortEntries(level.entries, sort)` —— 排序控制一旦 离开默认档,Shift 连选的坐标系就和用户看到的行序错位:视觉上连续的一段 只选中两端,中间被排序挪过位置的行漏选(实测 `[beta, Gamma.MD]` vs `[beta, zdir, Gamma.MD]`)。 危害不止观感:批量条的 Copy paths / Zip and download / Delete selected 都 作用于这个错误集合,而批量删除确认框只显示数量、不列路径。 让 walk 跑同一个 `sortEntries(...)`,并把 `sort` 加进依赖数组——两条路 (渲染 / 选择)从此共用一份有序视图。 判别性用例 tests/file-tree-select-order.spec.tsx:夹具宿主序 `[zdir(dir), alpha.ts, beta, Gamma.MD]`,非默认档 `{key:'type', dirsFirst:false}` 下渲染序为 `[beta, zdir, Gamma.MD, alpha.ts]`;Ctrl 点第 1 行 + Shift 点第 3 行必须选中 恰好这 3 行。在还原后的源码上该用例红(`expected [ 'beta', 'Gamma.MD' ] to deeply equal [ 'beta', 'zdir', 'Gamma.MD' ]`),修复后绿。 --- src/client/FileTree.tsx | 13 ++- tests/file-tree-select-order.spec.tsx | 142 ++++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 tests/file-tree-select-order.spec.tsx diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index ba0e0ab5..022a1345 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -12,7 +12,8 @@ * * Selection (VS Code semantics, no modifier = the old click semantics * untouched): Ctrl/Cmd+click toggles a row and sets the anchor, Shift+click - * selects the visible range from the anchor, Escape / a blank click clears, + * selects the visible range from the anchor (in the tree's own row order — + * `sort` included), Escape / a blank click clears, * right-clicking outside the selection collapses it onto the row. A non-empty * selection shows the batch bar above the root row (copy paths / delete / * clear); the batch delete confirms once and removes sequentially. @@ -1657,14 +1658,16 @@ export function FileTree(props: { } }, [data]) - // The Shift range walks the rows the user can actually see: depth-first, - // expanded state decides. Recomputed with the level cache, never rendered. + // The Shift range walks the rows the user can actually see: the level's + // rows in the SAME order `renderLevel` draws them (the sort choice), then + // depth-first, expanded state decides. Recomputed with the level cache, + // never rendered. const visibleRows = useMemo(() => { const rows: { path: string; isDir: boolean }[] = [] const walk = (dir: string): void => { const level = data[dir] if (level?.entries === undefined) return - for (const entry of level.entries) { + for (const entry of sortEntries(level.entries, sort)) { // A folded row IS one row: its identity is the chain head (the level // entry the walk is on), and it descends into the chain TAIL — the // same shape `renderLevel` draws, so a Shift range covers what the @@ -1677,7 +1680,7 @@ export function FileTree(props: { } if (root !== undefined) walk(root) return rows - }, [chainFor, data, expandedSet, root]) + }, [chainFor, data, expandedSet, root, sort]) visibleRowsRef.current = visibleRows /** diff --git a/tests/file-tree-select-order.spec.tsx b/tests/file-tree-select-order.spec.tsx new file mode 100644 index 00000000..cae37b3a --- /dev/null +++ b/tests/file-tree-select-order.spec.tsx @@ -0,0 +1,142 @@ +/** + * The Shift range's COORDINATE SPACE: `selectRange` walks + * `visibleRowsRef.current` and takes the slice between the anchor and the + * clicked row, so that walk must enumerate rows in the order the user sees + * them — the tree's sort choice, not the level cache's host order. + * + * The fixture is deliberately one where the two orders differ: with type + + * folders-first-off the rendered order is `beta, zdir, Gamma.MD, alpha.ts` + * while the host order is `zdir, alpha.ts, beta, Gamma.MD`. The walk keeping + * the host order selected the wrong set for a visually contiguous range — the + * batch bar's Copy paths / Zip and download / Delete selected all act on that + * set, and the delete confirmation shows only a COUNT. + */ +// @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 { FileTreeSort } from '../src/client/file-tree-sort.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 { fsTrees } = vi.hoisted(() => ({ + fsTrees: vi.fn(async (_scope: unknown, paths: readonly string[]) => ({ + levels: paths.map(path => ({ + path, + entries: path === '/tmp' ? HOST_ORDER_ROWS : [], + truncated: false, + })), + })), +})) + +vi.mock('../src/client/api.ts', () => ({ + api: { fsTrees, gitStatus: async () => ({ isRepo: false, entries: [] }) }, + downloadUrl: () => '/sidebar/file', + isOutsideWorkspaceMessage: () => false, +})) + +/** The fixture as the host ships it (the hoisted mock cannot close over it). */ +const HOST_ORDER_ROWS = [ + { name: 'zdir', path: '/tmp/zdir', isDir: true }, + { name: 'alpha.ts', path: '/tmp/alpha.ts', isDir: false }, + { name: 'beta', path: '/tmp/beta', isDir: false }, + { name: 'Gamma.MD', path: '/tmp/Gamma.MD', isDir: false }, +] + +interface Harness { + container: HTMLDivElement + unmount: () => void +} + +/** The root level's child rows, in render order. */ +function renderedNames(container: HTMLElement): string[] { + return [...container.querySelectorAll('[class*="explorerRow"]')] + .filter(el => el.style.paddingLeft === '28px') + .map(el => el.querySelector('[class*="explorerName"]')?.textContent ?? '') +} + +/** The names of the rows rendered as SELECTED, in render order. */ +function selectedNames(container: HTMLElement): string[] { + return [...container.querySelectorAll('[class*="explorerRow"]')] + .filter(el => el.getAttribute('data-dsh-selected') === 'true') + .map(el => el.querySelector('[class*="explorerName"]')?.textContent ?? '') +} + +/** One row by its displayed name. */ +function rowByName(container: HTMLElement, name: string): HTMLElement { + const row = [...container.querySelectorAll('[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 })) }) +} + +let harness: Harness | undefined + +afterEach(() => { + harness?.unmount() + harness = undefined + document.body.innerHTML = '' + fsTrees.mockClear() +}) + +describe('FileTree Shift range under a non-default sort', () => { + function mountTree(sort: FileTreeSort): Harness { + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + act(() => { + root.render(createElement(FileTree, { + sessionId: 's1', + cwd: '/tmp', + expanded: [], + revealed: [], + onToggle: () => {}, + onOpenFile: () => {}, + onReferenceFile: () => {}, + refreshTick: 0, + onUploadRequest: () => {}, + busy: false, + sort, + })) + }) + return { container, unmount: () => { act(() => { root.unmount() }); container.remove() } } + } + + it('covers the visually contiguous rows when the rendered order is not the host order', async () => { + harness = mountTree({ key: 'type', dirsFirst: false }) + await act(async () => {}) + // The premise of the case: the rendered order really is the type order, + // so rows 1..3 are beta / zdir / Gamma.MD. + expect(renderedNames(harness.container)).toEqual(['beta', 'zdir', 'Gamma.MD', 'alpha.ts']) + + // Ctrl on the FIRST row seats the anchor, Shift on the THIRD one ranges to + // it — the three rows the user sees between them are all selected. + click(rowByName(harness.container, 'beta'), { ctrlKey: true }) + click(rowByName(harness.container, 'Gamma.MD'), { shiftKey: true }) + expect(selectedNames(harness.container)).toEqual(['beta', 'zdir', 'Gamma.MD']) + // The row OUTSIDE the range stays out of it. + expect(selectedNames(harness.container)).not.toContain('alpha.ts') + }) + + it('follows the default order too (the range is not merely "everything")', async () => { + harness = mountTree({ key: 'name', dirsFirst: true }) + await act(async () => {}) + expect(renderedNames(harness.container)).toEqual(['zdir', 'alpha.ts', 'beta', 'Gamma.MD']) + + click(rowByName(harness.container, 'alpha.ts'), { ctrlKey: true }) + click(rowByName(harness.container, 'beta'), { shiftKey: true }) + expect(selectedNames(harness.container)).toEqual(['alpha.ts', 'beta']) + }) +})