Merge pull request #806 from ZinChl/fix/search-result-directory-click
fix(files): 搜索结果里的目录行改为导航文件树,不再当文件打开(#801)
This commit is contained in:
8 files changed
+246
-52
No files matched your search
+42
-12
@@ -23,6 +23,7 @@ import clsx from 'clsx'
|
||||
import { IconFolderOpenRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { api } from './api.ts'
|
||||
import type { BetterSidebarService } from './service.ts'
|
||||
import { ancestorDirs } from './state.ts'
|
||||
import { FileTree } from './FileTree.tsx'
|
||||
import { IconUploadOutline16 } from './icons.tsx'
|
||||
import type { OpenInApp } from './open-in-app.ts'
|
||||
@@ -93,7 +94,7 @@ export function TreePanel(props: {
|
||||
onReferenceFile, onPathRenamed, onPathDeleted, visible, full, service,
|
||||
} = props
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<{ matches: string[]; truncated: boolean } | null>(null)
|
||||
const [results, setResults] = useState<{ matches: string[]; dirs: string[]; truncated: boolean } | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [refreshTick, setRefreshTick] = useState(0)
|
||||
|
||||
@@ -195,6 +196,27 @@ export function TreePanel(props: {
|
||||
}, [sessionId, cwd, needle])
|
||||
|
||||
const busy = upload !== null
|
||||
/** Directory hits (the host reports them separately): a click navigates the
|
||||
* tree for those rows instead of opening them as files. */
|
||||
const dirHits = new Set(results?.dirs)
|
||||
|
||||
/**
|
||||
* Jump to a DIRECTORY hit in the tree. Results include directories (they
|
||||
* show where matches live) and `fs.read` refuses one, so opening such a row
|
||||
* as a file surfaced a bare `"…" is a directory` error. Expand the folder
|
||||
* and its ancestors instead — `onToggle` FLIPS a row, so only collapsed
|
||||
* paths are touched — and clear the query so the tree, not the parked
|
||||
* results panel, is what the user sees next.
|
||||
*/
|
||||
const openSearchDir = (rel: string): void => {
|
||||
const target = resolveSidebarPath(cwd, rel)
|
||||
if (cwd !== undefined) {
|
||||
for (const path of [...ancestorDirs(cwd, [target]), target]) {
|
||||
if (!expanded.includes(path)) onToggle(path)
|
||||
}
|
||||
}
|
||||
setQuery('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={clsx(css.editorTreePanel, full === true && css.editorTreePanelFull)}>
|
||||
@@ -262,17 +284,25 @@ export function TreePanel(props: {
|
||||
{error === null && results !== null && results.matches.length === 0 && (
|
||||
<div className={css.editorSearchHint}>{t('editorSearchNoResults')}</div>
|
||||
)}
|
||||
{error === null && results !== null && results.matches.map(rel => (
|
||||
<button
|
||||
key={rel}
|
||||
type="button"
|
||||
className={css.editorSearchResult}
|
||||
title={rel}
|
||||
onClick={() => { onOpenFile(resolveSidebarPath(cwd, rel)) }}
|
||||
>
|
||||
{rel}
|
||||
</button>
|
||||
))}
|
||||
{error === null && results !== null && results.matches.map((rel) => {
|
||||
const isDirHit = dirHits.has(rel)
|
||||
return (
|
||||
<button
|
||||
key={rel}
|
||||
type="button"
|
||||
className={clsx(css.editorSearchResult, isDirHit && css.editorSearchResultDir)}
|
||||
title={rel}
|
||||
data-dsh-search-dir={isDirHit ? 'true' : undefined}
|
||||
onClick={() => {
|
||||
if (isDirHit) openSearchDir(rel)
|
||||
else onOpenFile(resolveSidebarPath(cwd, rel))
|
||||
}}
|
||||
>
|
||||
{isDirHit && <IconFolderOpenRegular size={14} />}
|
||||
<span className={css.editorSearchResultLabel}>{rel}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{error === null && results?.truncated === true && (
|
||||
<div className={css.editorSearchHint}>{t('editorSearchTruncated')}</div>
|
||||
)}
|
||||
|
||||
+4
-2
@@ -292,9 +292,11 @@ export const api = {
|
||||
fsTrees: (scope: SessionScope, paths: readonly string[], signal?: AbortSignal) =>
|
||||
call<{ levels: FsLevel[] }>('fs.trees', scopePayload(scope, { paths: [...paths] }), signal),
|
||||
/** Global recursive file-name search rooted at the session cwd (the editor
|
||||
* side panel's search box); matches are cwd-relative '/'-separated paths. */
|
||||
* side panel's search box); matches are cwd-relative '/'-separated paths,
|
||||
* and `dirs` names the subset that is a directory (the list navigates the
|
||||
* tree for those — `fs.read` refuses a directory). */
|
||||
fsSearch: (scope: SessionScope, query: string, signal?: AbortSignal) =>
|
||||
call<{ matches: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query }), signal),
|
||||
call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query }), signal),
|
||||
fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) =>
|
||||
call<FsTextResult | FsBinaryResult>('fs.read', scopePayload(scope, { path }), signal),
|
||||
fsWrite: (scope: SessionScope, path: string, content: string) =>
|
||||
|
||||
@@ -1341,7 +1341,9 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
|
||||
}
|
||||
|
||||
.editorSearchResult {
|
||||
display: block;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 28px;
|
||||
@@ -1355,6 +1357,17 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* A directory hit is a navigation target, not an openable file: the folder
|
||||
glyph and the dimmer label say so before the click. */
|
||||
.editorSearchResultDir {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.editorSearchResultLabel {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
+31
-18
@@ -520,6 +520,33 @@ export function toggleExpanded(state: SidebarState, path: string): SidebarState
|
||||
return { ...state, expanded }
|
||||
}
|
||||
|
||||
/**
|
||||
* The absolute ancestor directories between the explorer root (`cwd`) and each
|
||||
* given path, EXCLUDING the paths themselves: the levels a lazy tree must have
|
||||
* expanded before those rows can exist. Empty strings and non-strings are
|
||||
* skipped; the result is de-duplicated in first-seen order.
|
||||
* @param cwd - the explorer's root (session working directory).
|
||||
* @param files - absolute paths whose ancestors are wanted.
|
||||
*/
|
||||
export function ancestorDirs(cwd: string | undefined, files: readonly string[]): string[] {
|
||||
const found = new Set<string>()
|
||||
const rootParts = (cwd ?? '').split(/[\\/]+/).filter(part => part !== '')
|
||||
for (const file of files) {
|
||||
if (typeof file !== 'string' || file === '') continue
|
||||
const parts = file.split(/[\\/]+/).filter(part => part !== '' && part !== '.')
|
||||
const separator = file.includes('\\') ? '\\' : '/'
|
||||
// Keep the original leading separator(s) when rebuilding ancestor dirs:
|
||||
// FileTree matches expansion against ABSOLUTE paths, so dropping the
|
||||
// root (POSIX `/w/src` → `w/src`) or a UNC prefix (`\\server\share`)
|
||||
// would leave every ancestor collapsed and the row unreachable.
|
||||
const prefix = file.startsWith('/') ? '/' : file.startsWith('\\\\') ? '\\\\' : file.startsWith('\\') ? '\\' : ''
|
||||
for (let i = rootParts.length; i < parts.length - 1; i++) {
|
||||
found.add(prefix + parts.slice(0, i + 1).join(separator))
|
||||
}
|
||||
}
|
||||
return [...found]
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveal files in the explorer: expand every ancestor directory between the
|
||||
* explorer root and each file (so the lazy tree actually shows the row) and
|
||||
@@ -531,25 +558,11 @@ export function toggleExpanded(state: SidebarState, path: string): SidebarState
|
||||
* @returns the next state, or the same reference when nothing is revealed.
|
||||
*/
|
||||
export function revealPaths(state: SidebarState, cwd: string | undefined, files: readonly string[]): SidebarState {
|
||||
const expanded = new Set(state.expanded)
|
||||
const revealed: string[] = []
|
||||
const rootParts = (cwd ?? '').split(/[\\/]+/).filter(part => part !== '')
|
||||
for (const file of files) {
|
||||
if (typeof file !== 'string' || file === '') continue
|
||||
revealed.push(file)
|
||||
const parts = file.split(/[\\/]+/).filter(part => part !== '' && part !== '.')
|
||||
const separator = file.includes('\\') ? '\\' : '/'
|
||||
// Keep the original leading separator(s) when rebuilding ancestor dirs:
|
||||
// FileTree matches expansion against ABSOLUTE paths, so dropping the
|
||||
// root (POSIX `/w/src` �W `w/src`) or a UNC prefix (`\\server\share`)
|
||||
// would leave every ancestor collapsed and the row unreachable.
|
||||
const prefix = file.startsWith('/') ? '/' : file.startsWith('\\\\') ? '\\\\' : file.startsWith('\\') ? '\\' : ''
|
||||
for (let i = rootParts.length; i < parts.length - 1; i++) {
|
||||
expanded.add(prefix + parts.slice(0, i + 1).join(separator))
|
||||
}
|
||||
}
|
||||
const revealed = files.filter(file => typeof file === 'string' && file !== '')
|
||||
if (revealed.length === 0) return state
|
||||
return { ...state, expanded: [...expanded], revealed }
|
||||
const expanded = new Set(state.expanded)
|
||||
for (const dir of ancestorDirs(cwd, revealed)) expanded.add(dir)
|
||||
return { ...state, expanded: [...expanded], revealed: [...revealed] }
|
||||
}
|
||||
|
||||
/** Adjust one split divider: `i` is the left/top child index, delta in fractions. */
|
||||
|
||||
+36
-7
@@ -11,14 +11,24 @@
|
||||
* the flat list) and `maxVisited` (a runaway tree — a home directory root
|
||||
* — must not stall the host). Exceeding either stops early with
|
||||
* `truncated: true`.
|
||||
*
|
||||
* A hit can be a DIRECTORY (the list shows where matches live), so the result
|
||||
* separates them: `fs.read` refuses a directory, and the client must navigate
|
||||
* the tree for those rows instead of opening them as files.
|
||||
*/
|
||||
import { opendir } from 'node:fs/promises'
|
||||
import type { Dirent } from 'node:fs'
|
||||
import { opendir, stat } from 'node:fs/promises'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
|
||||
/** One search: the relative paths of the matching entries (dirs included so
|
||||
* the client can hint where matches live) plus the truncation flag. */
|
||||
export interface FsSearchResult {
|
||||
matches: string[]
|
||||
/** The subset of `matches` that are DIRECTORIES (same relative, '/'-separated
|
||||
* form). The client navigates the tree for these instead of opening them:
|
||||
* `fs.read` refuses a directory, so treating a hit as a file surfaces a bare
|
||||
* `"…" is a directory` error. */
|
||||
dirs: string[]
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
@@ -60,6 +70,19 @@ const SEARCH_SKIP_DIRS = new Set([
|
||||
'.dumi',
|
||||
])
|
||||
|
||||
/**
|
||||
* Whether one matched entry is a DIRECTORY, following symlinks the way the
|
||||
* tree and `fs.read` do: the dirent answers for real directories, a link is
|
||||
* stat'ed (a link to a directory is a directory row — `fs.read` refuses it as
|
||||
* a file), and an unresolvable link stays a plain entry.
|
||||
*/
|
||||
async function isDirectoryEntry(absolute: string, dirent: Dirent): Promise<boolean> {
|
||||
if (dirent.isDirectory()) return true
|
||||
if (!dirent.isSymbolicLink()) return false
|
||||
const info = await stat(absolute).catch(() => undefined)
|
||||
return info?.isDirectory() === true
|
||||
}
|
||||
|
||||
/**
|
||||
* Search `root` recursively for entries whose name contains `query`
|
||||
* (case-insensitive).
|
||||
@@ -67,16 +90,18 @@ const SEARCH_SKIP_DIRS = new Set([
|
||||
* @param query - the name substring; empty matches nothing.
|
||||
* @param opts - budget overrides (tests).
|
||||
* @returns the matching paths RELATIVE to `root` ('/'-separated), sorted,
|
||||
* plus whether a budget cut the walk short. An unreadable level is skipped
|
||||
* (permission errors never fail the whole search).
|
||||
* plus which of them are directories and whether a budget cut the walk
|
||||
* short. An unreadable level is skipped (permission errors never fail the
|
||||
* whole search).
|
||||
*/
|
||||
export async function searchFiles(root: string, query: string, opts: FsSearchOptions = {}): Promise<FsSearchResult> {
|
||||
const needle = query.trim().toLowerCase()
|
||||
if (needle === '') return { matches: [], truncated: false }
|
||||
if (needle === '') return { matches: [], dirs: [], truncated: false }
|
||||
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
|
||||
const maxVisited = opts.maxVisited ?? DEFAULT_MAX_VISITED
|
||||
|
||||
const matches: string[] = []
|
||||
const dirs: string[] = []
|
||||
let visited = 0
|
||||
let truncated = false
|
||||
|
||||
@@ -92,8 +117,11 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt
|
||||
}
|
||||
// Dependency / VCS / build-output forests: never matched, never descended.
|
||||
if (dirent.isDirectory() && SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue
|
||||
const absolute = join(dir, dirent.name)
|
||||
if (dirent.name.toLowerCase().includes(needle)) {
|
||||
matches.push(join(relative(root, dir), dirent.name))
|
||||
const hit = join(relative(root, dir), dirent.name)
|
||||
matches.push(hit)
|
||||
if (await isDirectoryEntry(absolute, dirent)) dirs.push(hit)
|
||||
if (matches.length >= maxMatches) {
|
||||
truncated = true
|
||||
return
|
||||
@@ -102,12 +130,13 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt
|
||||
// Descend real directories only: a symlinked directory may point back
|
||||
// up the tree (cycle).
|
||||
if (dirent.isDirectory() && !dirent.isSymbolicLink()) {
|
||||
await walk(join(dir, dirent.name))
|
||||
await walk(absolute)
|
||||
if (truncated) return
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(root)
|
||||
// '/' separators on every platform: the client joins onto the cwd itself.
|
||||
return { matches: matches.sort().map(path => path.split(sep).join('/')), truncated }
|
||||
const normalize = (path: string): string => path.split(sep).join('/')
|
||||
return { matches: matches.sort().map(normalize), dirs: dirs.sort().map(normalize), truncated }
|
||||
}
|
||||
Reference in new issue
Block a user