diff --git a/src/features/search/__tests__/findPopup.test.tsx b/src/features/search/__tests__/findPopup.test.tsx index e2dac7230..733940754 100644 --- a/src/features/search/__tests__/findPopup.test.tsx +++ b/src/features/search/__tests__/findPopup.test.tsx @@ -1,10 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, within } from "@testing-library/react"; -import type { FileMatches, SearchSummary } from "@/platform/ipc"; +import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; import type { ReplaceRequest } from "../find/replaceFlow"; const replaced: ReplaceRequest[] = []; const confirms: unknown[] = []; +const queries: SearchQuery[] = []; let validation: Promise | null = null; let search: ((onFile: (file: FileMatches) => void) => Promise) | null = null; let confirmation: Promise | null = null; @@ -15,7 +17,8 @@ vi.mock("../find/windowStore", async (orig) => ({ validate: async () => { await validation; }, - start: async (_id: number, _q: unknown, onFile: (f: FileMatches) => void) => { + start: async (_id: number, query: SearchQuery, onFile: (f: FileMatches) => void) => { + queries.push(query); if (search) return search(onFile); onFile({ path: "/p/a.kt", @@ -87,6 +90,7 @@ const field = () => screen.getByLabelText("Text to find"); beforeEach(() => { replaced.length = 0; confirms.length = 0; + queries.length = 0; localStorage.clear(); validation = null; search = null; @@ -108,7 +112,10 @@ beforeEach(() => { }); afterEach(() => { - act(() => hideFindPopup()); + act(() => { + hideFindPopup(); + useProject.setState({ project: null }); + }); }); describe("Find in Files popup", () => { @@ -260,6 +267,53 @@ describe("Find in Files popup", () => { expect(useFindPopup.getState().directory).toBe("/p/src/main"); }); + it.each([false, true])("waits for a directory instead of searching the project (replace=%s)", async (replace) => { + useProject.setState({ project: { root: "/p", name: "p", trusted: true, isGit: false, settings: {} } }); + render(); + act(() => showFindPopup(replace, { query: "order", directory: "/p" })); + await settle(); + expect(queries.map((q) => q.scope)).toEqual([{ kind: "directory", path: "/p" }]); + expect(screen.getByRole("listbox", { name: "Matches" })).toHaveTextContent("a.kt"); + + const directory = screen.getByRole("textbox", { name: "Directory" }); + expect(directory).toHaveValue("."); + fireEvent.change(directory, { target: { value: "" } }); + expect(screen.queryByText("a.kt")).not.toBeInTheDocument(); + await settle(); + expect(queries).toHaveLength(1); + expect(screen.getByRole("tab", { name: "Directory" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getByText("Enter a directory to search")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeDisabled(); + fireEvent.keyDown(field(), { key: "Enter", ctrlKey: true }); + expect(useFindPopup.getState().open).toBe(true); + if (replace) { + expect(screen.getByRole("button", { name: "Replace All" })).toBeDisabled(); + expect(screen.getByRole("button", { name: /^Replace$/ })).toBeDisabled(); + fireEvent.keyDown(field(), { key: "Enter" }); + fireEvent.keyDown(field(), { key: "Enter", altKey: true, shiftKey: true }); + expect(replaced).toHaveLength(0); + expect(confirms).toHaveLength(0); + } + + fireEvent.change(directory, { target: { value: " " } }); + await settle(); + expect(queries).toHaveLength(1); + fireEvent.change(directory, { target: { value: "" } }); + act(() => hideFindPopup()); + act(() => showFindPopup(replace)); + await settle(); + expect(screen.getByRole("tab", { name: "Directory" })).toHaveAttribute("aria-selected", "true"); + expect(queries).toHaveLength(1); + + fireEvent.change(screen.getByRole("textbox", { name: "Directory" }), { target: { value: "src" } }); + await settle(); + expect(queries.at(-1)?.scope).toEqual({ kind: "directory", path: "/p/src" }); + fireEvent.click(screen.getByRole("tab", { name: "In Project" })); + await settle(); + expect(queries.at(-1)?.scope).toEqual({ kind: "project" }); + expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeEnabled(); + }); + it("closing remembers the search text", async () => { render(); act(() => showFindPopup(false, { query: "order" })); diff --git a/src/features/search/__tests__/findScopes.test.ts b/src/features/search/__tests__/findScopes.test.ts index 51e7926ff..6f0e7a200 100644 --- a/src/features/search/__tests__/findScopes.test.ts +++ b/src/features/search/__tests__/findScopes.test.ts @@ -31,6 +31,13 @@ describe("Find in Files module and custom scopes", () => { const inputs = { root: "/p", openPaths: () => ["/p/a.ts"], recentPaths: null }; const base = useFindPopup.getState(); + it.each(["/", "C:/"])("preserves the absolute root directory %s", (directory) => { + expect(resolveFindScope({ ...base, scopeTab: "directory", directory }, inputs)).toEqual({ + kind: "directory", + path: directory, + }); + }); + it("a module searches its folder, the root module the project", () => { expect(resolveFindScope({ ...base, scopeTab: "module", module: "/member" }, inputs)).toEqual({ kind: "directory", @@ -56,7 +63,7 @@ describe("Find in Files module and custom scopes", () => { expect(scope("openFiles")).toEqual({ kind: "files", paths: ["/p/a.ts"] }); expect(scope(customScopeValue("No tests"))).toEqual({ kind: "pattern", pattern: "!file:*test*" }); expect(scope(customScopeValue("gone"))).toEqual({ kind: "project" }); - const q = buildQuery({ ...base, pattern: "x" }, scope(customScopeValue("No tests")), 0); + const q = buildQuery({ ...base, pattern: "x" }, scope(customScopeValue("No tests"))!, 0); expect(describeQuery(q, "/p")).toBe("'x' in Scope 'No tests'"); useCustomScopes.setState({ root: null, scopes: [] }); }); diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx index 3a10b1ed3..3c83ae6cd 100644 --- a/src/features/search/find/FindInFiles.tsx +++ b/src/features/search/find/FindInFiles.tsx @@ -1,11 +1,20 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react"; +import { + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, + type KeyboardEvent, + type MouseEvent, +} from "react"; import clsx from "clsx"; import { openEditorPaths, useEditorRegistry } from "@/editor/api"; import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { t, useTxTemplate, tx } from "@/platform/i18n"; import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap"; -import { call, commands, isTauri, onIdeEvent, type SearchScope } from "@/platform/ipc"; +import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { useProjectModules } from "@/platform/projectRoots"; import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search"; @@ -128,8 +137,10 @@ const NAMED_SCOPES: Array<{ value: BuiltinScope; label: string }> = [ ]; function displayDirectory(dir: string, root: string | null): string { - if (root && dir === root) return ""; - return root && dir.startsWith(root + "/") ? dir.slice(root.length + 1) : dir; + if (!root) return dir; + const prefix = root.endsWith("/") ? root : root + "/"; + if (dir === root) return "."; + return dir.startsWith(prefix) ? dir.slice(prefix.length) || "." : dir; } function FindInFilesDialog() { @@ -169,6 +180,7 @@ function FindInFilesDialog() { const maskRef = useRef(null); const maskInputRef = useRef(null); const contextRef = useRef(null); + const directoryPromptId = useId(); const set = (patch: Partial) => useFindPopup.setState(patch); useEffect(() => () => session.dispose(), [session]); @@ -200,7 +212,7 @@ function FindInFilesDialog() { ); }, [s.scopeTab, s.namedScope, recentPaths]); - const scope: SearchScope = useMemo( + const scope = useMemo( () => resolveFindScope(s, { root, @@ -229,13 +241,13 @@ function FindInFilesDialog() { context: s.context, }; const query = useMemo( - () => buildQuery(options, scope, POPUP_MAX_MATCHES), + () => (scope ? buildQuery(options, scope, POPUP_MAX_MATCHES) : null), // eslint-disable-next-line react-hooks/exhaustive-deps [s.pattern, s.caseSensitive, s.wholeWord, s.isRegex, s.maskEnabled, s.mask, s.context, scope], ); const queryKey = JSON.stringify(query); - const stale = state.stale || (state.query ? JSON.stringify(state.query) !== queryKey : !!s.pattern); + const stale = !!query && (state.stale || (state.query ? JSON.stringify(state.query) !== queryKey : !!s.pattern)); const currentQuery = useRef(queryKey); const [rerun, setRerun] = useState(0); useEffect( @@ -247,6 +259,10 @@ function FindInFilesDialog() { ); useLayoutEffect(() => { currentQuery.current = queryKey; + if (!query) { + void session.search(null); + return; + } session.invalidate(); const t = setTimeout(() => { void session.search(query); @@ -289,9 +305,9 @@ function FindInFilesDialog() { setTimeout(() => void openLocation(row.path, pos, { side }), 0); }; const pin = () => { - if (!s.pattern) return; + if (!query?.pattern) return; if (s.maskEnabled) rememberMask(s.mask); - const pinned = buildQuery(options, scope, 0); + const pinned = { ...query, maxMatches: 0 }; close(); openInFindWindow(pinned, describeQuery(pinned, root), { replacement: s.replace ? s.replacement : null, @@ -302,7 +318,11 @@ function FindInFilesDialog() { // Check again after a confirmation: its captured rows may have been superseded. const canReplace = () => - !stale && !session.current.stale && currentQuery.current === queryKey && session.current.files === state.files; + !!query && + !stale && + !session.current.stale && + currentQuery.current === queryKey && + session.current.files === state.files; /** * IDEA asks before Replace All only when the results span more than one file, or when the @@ -340,7 +360,7 @@ function FindInFilesDialog() { /** Replaces `usages` in the backend, then marks them done (IDEA's Replace / Replace All). */ const replaceUsages = async (usages: Usage[], allInScope = false): Promise => { - if (!canReplace() || !usages.length || running) return null; + if (!query || !canReplace() || !usages.length || running) return null; const run = startReplace( { query, @@ -415,7 +435,7 @@ function FindInFilesDialog() { previewVersion, ]); useEffect(() => { - if (stale || !previewMode || !s.replace || !selected) return; + if (!query || stale || !previewMode || !s.replace || !selected) return; let alive = true; const key = diffPreviewKey; const usages = pendingUsages([selected], marks); @@ -461,7 +481,7 @@ function FindInFilesDialog() { const selectScope = (id: ScopeTab) => { // IDEA starts the Directory scope at the current file's folder. - if (id === "directory" && !s.directory.trim()) { + if (id === "directory" && s.scopeTab !== "directory" && !s.directory.trim()) { const active = maybeEditorService()?.activePath(); const folders = project?.workspace?.projects ?? (root ? [root] : []); const dir = active && folders.some((r) => active.startsWith(r + "/")) ? dirname(active) : root; @@ -580,7 +600,18 @@ function FindInFilesDialog() { rowHeight={ROW} aria-label="Matches" empty={ - set({ isRegex: true })} /> + query ? ( + set({ isRegex: true })} + /> + ) : ( +
+ Enter a directory to search +
+ ) } renderItem={(r, st) => { const state = s.replace ? groupState(r, marks) : "pending"; @@ -769,8 +800,9 @@ function FindInFilesDialog() { value={displayDirectory(s.directory, root)} placeholder={tx("Directory (relative to project root)")} aria-label={tx("Directory")} + aria-invalid={!query || undefined} + aria-describedby={!query ? directoryPromptId : undefined} spellCheck={false} - // Keep the raw text (resolved only when searching), or a typed "/" would be stripped. onChange={(e) => set({ directory: e.target.value })} /> )} @@ -894,7 +926,7 @@ function FindInFilesDialog() { )} {formatBinding(hostBinding("Meta+Enter"))} - {s.replace && ( diff --git a/src/features/search/find/session.ts b/src/features/search/find/session.ts index b6da0801c..8681ac886 100644 --- a/src/features/search/find/session.ts +++ b/src/features/search/find/session.ts @@ -78,12 +78,12 @@ export class FindSession { this.update({ ...this.state, stale: true, matchCount: 0, summary: null, error: null }, true); } - /** Starts (or restarts) a search; an empty pattern resets to idle. */ - async search(query: SearchQuery): Promise { + /** Starts (or restarts) a search; missing query or pattern resets to idle. */ + async search(query: SearchQuery | null): Promise { const seq = ++this.seq; this.disposed = false; this.cancelRunning(); - if (!query.pattern) { + if (!query?.pattern) { this.update({ ...IDLE }, true); return; } diff --git a/src/features/search/find/store.ts b/src/features/search/find/store.ts index b19f9bba9..afe189ffc 100644 --- a/src/features/search/find/store.ts +++ b/src/features/search/find/store.ts @@ -167,8 +167,6 @@ export function showFindPopup(replace: boolean, arg: FindArg & { selection?: str if (arg.directory) { patch.scopeTab = "directory"; patch.directory = arg.directory; - } else if (!s.open && s.scopeTab === "directory" && !s.directory) { - patch.scopeTab = "project"; } useFindPopup.setState(patch); } @@ -244,16 +242,18 @@ export interface ScopeInputs { } export function resolveDirectory(dir: string, root: string | null): string { - const d = dir.trim().replace(/\/+$/, ""); + const d = dir.trim(); if (!d || d.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(d)) return d; - return root ? `${root}/${d}` : d; + return root ? `${root.replace(/\/$/, "")}/${d}` : d; } /** The backend scope of the popup's scope tabs. */ -export function resolveFindScope(o: FindOptions, inputs: ScopeInputs): SearchScope { +export function resolveFindScope(o: FindOptions, inputs: ScopeInputs): SearchScope | null { const { root } = inputs; - if (o.scopeTab === "directory" && o.directory.trim()) - return { kind: "directory", path: resolveDirectory(o.directory, root) }; + if (o.scopeTab === "directory") { + const path = resolveDirectory(o.directory, root); + return path ? { kind: "directory", path } : null; + } if (o.scopeTab === "module") return o.module && root ? { kind: "directory", path: resolveDirectory(o.module, root) } : { kind: "project" }; if (o.scopeTab !== "scope") return { kind: "project" }; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index f5264a850..3f7457a08 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -687,6 +687,7 @@ "Remove Module Overrides": "Remove Module Overrides", "Java compiler output must be inside its module: {output}": "Java compiler output must be inside its module: {output}", "Cannot choose a directory": "Cannot choose a directory", + "Enter a directory to search": "Enter a directory to search", "Open in HTTP Client": "Open in HTTP Client", "Cannot generate the HTTP request": "Cannot generate the HTTP request", "Cannot start container debugging": "Cannot start container debugging", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 1a63f2ad7..488cf92f2 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1222,6 +1222,7 @@ "Staged Changes": "已暂存的更改", "Unstaged Changes": "未暂存的更改", "Directory (relative to project root)": "目录(相对于项目根目录)", + "Enter a directory to search": "请输入要搜索的目录", "Directory Mappings": "目录映射", "Directory mappings": "目录映射", "Directory of the current file": "当前文件所在的目录",