/** * Tests of the Find tool window (M2.4): the Find store (search params, * results sorted by file, events of other searches ignored, events before * the `searchId` answer replayed, a new search cancelling the old one, * refused queries, malformed matches, project close), the prefill from the * editor, the window (status and counts, truncated hint, highlight, toggles * repeating the search, cancel, keyboard navigation and opening a match * through `editor.reveal`), the bottom panel, and `find.open` through the * main layout and `uiCommand`. The engine is a fake behind the mocked Tauri * `invoke` and `listen`. */ import { EditorSelection, EditorState } from "@codemirror/state"; import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia, type Pinia } from "pinia"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); const listen = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/event", () => ({ listen })); import { useCommandsStore } from "../../src/commands/store"; import FindToolWindow from "../../src/components/find/FindToolWindow.vue"; import BottomPanel from "../../src/components/layout/BottomPanel.vue"; import MainLayout from "../../src/components/layout/MainLayout.vue"; import { prefillFrom, splitGlobs, toMatches, useFindStore } from "../../src/stores/find"; /** Every `engine_execute` call, in order. */ let calls: { command: string; params: Record }[]; /** Engine event callbacks of every subscription. */ let listeners: ((event: { payload: unknown }) => void)[]; /** Next `searchId` the fake returns. */ let nextSearchId: number; /** Error the next `search.find` fails with, if any. */ let findError: { code: string; message: string } | null; /** Events the fake emits before `search.find` answers. */ let beforeAnswer: unknown[]; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components, unmounted after each test. */ let mounted: VueWrapper[]; /** * Sends an engine event to every subscription. * * @param payload - the event. */ async function emit(payload: unknown): Promise { for (const listener of [...listeners]) { listener({ payload }); } await flushPromises(); } /** * A `searchResults` event. * * @param searchId - the search. * @param path - the file. * @param lines - one match per entry: line number and preview with the * match marked by `[` and `]`. */ function results(searchId: number, path: string, lines: [number, string][]): unknown { return { kind: "searchResults", searchId, path, matches: lines.map(([line, marked]) => { const start = marked.indexOf("["); const end = marked.indexOf("]") - 1; const preview = marked.replace("[", "").replace("]", ""); return { line, column: start + 2, length: end - start, preview, previewColumn: start }; }), }; } /** * A `searchDone` event. * * @param searchId - the search. * @param extra - fields to override. */ function done(searchId: number, extra: Record = {}): unknown { return { kind: "searchDone", searchId, files: 2, matches: 3, truncated: false, cancelled: false, elapsedMs: 12, ...extra }; } /** The params of every call of a command. */ function paramsOf(command: string): Record[] { return calls.filter((c) => c.command === command).map((c) => c.params); } /** Mounts the Find window with a started store and an `editor.reveal` spy. */ async function mountFind(): Promise<{ wrapper: VueWrapper; reveals: unknown[] }> { const reveals: unknown[] = []; useCommandsStore(pinia).provide("editor.reveal", { run: (params) => void reveals.push(params) }); useFindStore(pinia).start(); const wrapper = mount(FindToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); await flushPromises(); return { wrapper, reveals }; } /** * Types a query and presses Enter. * * @param wrapper - the Find window. * @param text - the query. */ async function searchFor(wrapper: VueWrapper, text: string): Promise { await wrapper.get("[data-test=find-query]").setValue(text); await wrapper.get("form").trigger("submit"); await flushPromises(); } beforeEach(() => { pinia = createPinia(); setActivePinia(pinia); calls = []; listeners = []; nextSearchId = 7; findError = null; beforeAnswer = []; mounted = []; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); listen.mockReset(); listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { listeners.push(callback); return Promise.resolve(() => { listeners = listeners.filter((l) => l !== callback); }); }); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (cmd === "engine_list_commands") { return Promise.resolve([]); } if (cmd !== "engine_execute" || !args) { return Promise.resolve(null); } calls.push({ command: args.command, params: args.params }); if (args.command === "search.find") { if (findError) { return Promise.reject(Object.assign(new Error(findError.code), findError)); } const searchId = nextSearchId; nextSearchId += 1; for (const event of beforeAnswer) { for (const listener of [...listeners]) { listener({ payload: event }); } } return Promise.resolve({ searchId }); } if (args.command === "search.cancel") { return Promise.resolve({ cancelled: true }); } return Promise.resolve(null); }); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } useFindStore(pinia).stop(); useCommandsStore(pinia).stop(); }); describe("find store", () => { it("sends the query, options and split globs", async () => { const find = useFindStore(); find.start(); await flushPromises(); find.query = "foo"; find.caseSensitive = true; find.regex = true; find.include = " *.php, src/** ,"; find.exclude = "vendor/**"; await find.search(); expect(paramsOf("search.find")).toEqual([ { query: "foo", regex: true, caseSensitive: true, wholeWord: false, include: ["*.php", "src/**"], exclude: ["vendor/**"] }, ]); expect(find.searchId).toBe(7); expect(find.running).toBe(true); }); it("keeps files sorted, ignores other searches and ends with the summary", async () => { const find = useFindStore(); find.start(); await flushPromises(); find.query = "foo"; await find.search(); await emit(results(7, "src/b.php", [[3, " $[foo] = 1;"]])); await emit(results(99, "src/x.php", [[0, "[foo]"]])); await emit(results(7, "a.php", [[0, "[foo]"], [4, "x [foo]"]])); expect(find.files.map((f) => f.path)).toEqual(["a.php", "src/b.php"]); expect(find.matchCount).toBe(3); await emit(done(99)); expect(find.running).toBe(true); await emit(done(7, { truncated: true })); expect(find.running).toBe(false); expect(find.summary).toEqual({ files: 2, matches: 3, truncated: true, cancelled: false, elapsedMs: 12 }); }); it("replays events that arrive before search.find answers", async () => { const find = useFindStore(); find.start(); await flushPromises(); beforeAnswer = [results(7, "a.php", [[0, "[foo]"]]), results(3, "old.php", [[0, "[foo]"]]), done(7, { files: 1, matches: 1 })]; find.query = "foo"; await find.search(); expect(find.files.map((f) => f.path)).toEqual(["a.php"]); expect(find.summary?.matches).toBe(1); expect(find.running).toBe(false); }); it("cancels the running search when a new one starts", async () => { const find = useFindStore(); find.start(); await flushPromises(); find.query = "foo"; await find.search(); await emit(results(7, "a.php", [[0, "[foo]"]])); find.query = "bar"; await find.search(); expect(paramsOf("search.cancel")).toEqual([{ searchId: 7 }]); expect(find.searchId).toBe(8); expect(find.files).toEqual([]); await emit(results(7, "late.php", [[0, "[foo]"]])); expect(find.files).toEqual([]); }); it("drops the answer of a search overtaken by a newer one and cancels it", async () => { const find = useFindStore(); find.start(); await flushPromises(); find.query = "foo"; const first = find.search(); find.query = "bar"; const second = find.search(); await Promise.all([first, second]); expect(find.searchId).toBe(8); expect(paramsOf("search.cancel")).toEqual([{ searchId: 7 }]); }); it("shows a refused query in place", async () => { const find = useFindStore(); find.start(); findError = { code: "invalid_params", message: "search.find: regex parse error" }; find.query = "("; find.regex = true; await find.search(); expect(find.error).toBe("search.find: regex parse error"); expect(find.running).toBe(false); }); it("does not search for an empty query", async () => { const find = useFindStore(); await find.search(); expect(paramsOf("search.find")).toEqual([]); }); it("cancels through search.cancel", async () => { const find = useFindStore(); find.start(); await flushPromises(); find.query = "foo"; await find.search(); await find.cancel(); expect(paramsOf("search.cancel")).toEqual([{ searchId: 7 }]); await emit(done(7, { cancelled: true })); expect(find.summary?.cancelled).toBe(true); }); it("clears the results when the project closes", async () => { const find = useFindStore(); find.start(); await flushPromises(); find.query = "foo"; await find.search(); await emit(results(7, "a.php", [[0, "[foo]"]])); await emit({ kind: "projectClosed" }); expect(find.files).toEqual([]); expect(find.running).toBe(false); await emit(results(7, "b.php", [[0, "[foo]"]])); expect(find.files).toEqual([]); }); it("drops malformed matches and clamps the highlight", () => { expect( toMatches([ { line: 1, column: 2, length: 3, preview: "abc", previewColumn: 9 }, { line: -1, column: 0, length: 1, preview: "x", previewColumn: 0 }, { line: 0, column: 0, length: 1, preview: 5, previewColumn: 0 }, null, "x", ]), ).toEqual([{ line: 1, column: 2, length: 3, preview: "abc", previewColumn: 3 }]); expect(toMatches("nope")).toEqual([]); }); it("splits globs", () => { expect(splitGlobs("")).toEqual([]); expect(splitGlobs("*.php,, *.twig ")).toEqual(["*.php", "*.twig"]); }); }); describe("prefill", () => { /** * An editor state with a selection. * * @param doc - the text. * @param anchor - selection anchor. * @param head - selection head. */ function stateOf(doc: string, anchor: number, head = anchor): EditorState { return EditorState.create({ doc, selection: EditorSelection.single(anchor, head) }); } it("takes the selection", () => { expect(prefillFrom(stateOf("echo $foo->bar();", 5, 14))).toBe("$foo->bar"); }); it("takes the word at the cursor without a selection", () => { expect(prefillFrom(stateOf("echo productName;", 8))).toBe("productName"); }); it("ignores a multi-line selection and falls back to the word", () => { expect(prefillFrom(stateOf("alpha\nbeta", 0, 8))).toBe("beta"); }); it("gives nothing without an editor or a word", () => { expect(prefillFrom(undefined)).toBeNull(); expect(prefillFrom(stateOf("a ; b", 3))).toBeNull(); }); }); describe("find.open prefill", () => { it("replaces the query from the editor and drops a stale error", async () => { const find = useFindStore(); const editor = (await import("../../src/stores/editor")).useEditorStore(); const state = EditorState.create({ doc: "echo productName;", selection: EditorSelection.single(8) }); editor.tabs = [{ id: 1, path: "a.php", name: "a.php", dirty: false, notice: null }]; editor.activeId = 1; vi.spyOn(editor, "syncOf").mockReturnValue({ state } as unknown as ReturnType); find.query = "("; find.error = "bad regex"; await find.open({}); expect(find.query).toBe("productName"); expect(find.error).toBeNull(); expect(find.visible).toBe(true); expect(paramsOf("search.find")).toEqual([]); }); }); describe("Find tool window", () => { it("searches on Enter and shows counts, files and highlighted matches", async () => { const { wrapper } = await mountFind(); expect(wrapper.get("[data-test=find-status]").text()).toBe("Type a text and press Enter"); await searchFor(wrapper, "foo"); expect(paramsOf("search.find")[0]?.query).toBe("foo"); expect(wrapper.find("[data-test=find-cancel]").exists()).toBe(true); await emit(results(7, "src/b.php", [[3, " $[foo] = 1;"]])); await emit(results(7, "a.php", [[0, "[foo]"], [4, "x [foo] y"]])); expect(wrapper.get("[data-test=find-status]").text()).toBe("Searching… 3 matches in 2 files"); const files = wrapper.findAll("[data-test=find-file]").map((f) => f.text()); expect(files).toEqual(["a.php2", "b.phpsrc1"]); const rows = wrapper.findAll("[data-test=find-row]"); expect(rows.map((r) => r.text())).toEqual(["1foo", "5x foo y", "4$foo = 1;"]); expect(wrapper.findAll("[data-test=find-hit]").map((h) => h.text())).toEqual(["foo", "foo", "foo"]); await emit(done(7, { truncated: true, matches: 3, files: 2 })); expect(wrapper.get("[data-test=find-status]").text()).toContain("3 matches in 2 files · 12 ms"); expect(wrapper.find("[data-test=find-truncated]").exists()).toBe(true); expect(wrapper.find("[data-test=find-submit]").exists()).toBe(true); }); it("uses the singular for one match and one file", async () => { const { wrapper } = await mountFind(); await searchFor(wrapper, "foo"); await emit(results(7, "a.php", [[0, "[foo]"]])); expect(wrapper.get("[data-test=find-status]").text()).toBe("Searching… 1 match in 1 file"); await emit(done(7, { matches: 2, files: 1 })); expect(wrapper.get("[data-test=find-status]").text()).toContain("2 matches in 1 file · "); }); it("says when nothing matched or the search was cancelled", async () => { const { wrapper } = await mountFind(); await searchFor(wrapper, "zzz"); await emit(done(7, { files: 0, matches: 0 })); expect(wrapper.get("[data-test=find-status]").text()).toBe("No matches"); await searchFor(wrapper, "foo"); await wrapper.get("[data-test=find-cancel]").trigger("click"); await flushPromises(); expect(paramsOf("search.cancel")).toEqual([{ searchId: 8 }]); await emit(done(8, { cancelled: true, files: 0, matches: 0 })); expect(wrapper.get("[data-test=find-status]").text()).toContain("Cancelled"); }); it("shows a refused regex as an alert", async () => { const { wrapper } = await mountFind(); findError = { code: "invalid_params", message: "invalid params for search.find: invalid pattern: unclosed group" }; await searchFor(wrapper, "("); expect(wrapper.get("[data-test=find-error]").text()).toBe("invalid pattern: unclosed group"); expect(wrapper.get("[data-test=find-query]").attributes("aria-invalid")).toBe("true"); expect(wrapper.get("[data-test=find-status]").text()).toBe(""); }); it("repeats the search when an option is toggled", async () => { const { wrapper } = await mountFind(); await wrapper.get("[data-test=find-word]").trigger("click"); expect(paramsOf("search.find")).toEqual([]); await searchFor(wrapper, "foo"); await wrapper.get("[data-test=find-case]").trigger("click"); await flushPromises(); await wrapper.get("[data-test=find-regex]").trigger("click"); await flushPromises(); const sent = paramsOf("search.find"); expect(sent.map((p) => [p.wholeWord, p.caseSensitive, p.regex])).toEqual([ [true, false, false], [true, true, false], [true, true, true], ]); expect(wrapper.get("[data-test=find-regex]").attributes("aria-pressed")).toBe("true"); }); it("walks the results with the keyboard and opens them through editor.reveal", async () => { const { wrapper, reveals } = await mountFind(); await searchFor(wrapper, "foo"); await emit(results(7, "a.php", [[0, "[foo]"], [4, "x [foo]"]])); await emit(results(7, "b.php", [[2, "[foo]"]])); await wrapper.get("[data-test=find-query]").trigger("keydown", { key: "ArrowDown" }); const list = wrapper.get("[data-test=find-results]"); expect(document.activeElement).toBe(list.element); expect(list.attributes("aria-activedescendant")).toBe("find-row-0"); await list.trigger("keydown", { key: "ArrowDown" }); await list.trigger("keydown", { key: "ArrowDown" }); await list.trigger("keydown", { key: "ArrowDown" }); expect(list.attributes("aria-activedescendant")).toBe("find-row-2"); await list.trigger("keydown", { key: "Home" }); expect(list.attributes("aria-activedescendant")).toBe("find-row-0"); await list.trigger("keydown", { key: "ArrowDown" }); await list.trigger("keydown", { key: "Enter" }); await flushPromises(); expect(reveals).toEqual([{ path: "a.php", line: 4, column: 4, preview: true }]); await list.trigger("keydown", { key: "End" }); expect(wrapper.findAll("[data-test=find-row]")[2]?.attributes("aria-selected")).toBe("true"); await wrapper.findAll("[data-test=find-row]")[0]?.trigger("click"); await flushPromises(); expect(reveals).toEqual([ { path: "a.php", line: 4, column: 4, preview: true }, { path: "a.php", line: 0, column: 2, preview: true }, ]); }); it("focuses and selects the query field when find.open runs again", async () => { const { wrapper } = await mountFind(); const input = wrapper.get("[data-test=find-query]").element as HTMLInputElement; document.body.focus(); await useFindStore(pinia).open({}); await flushPromises(); expect(document.activeElement).toBe(input); }); }); describe("bottom panel", () => { it("collapses to its header, expands, closes and resizes with the keyboard", async () => { const closes: number[] = []; const wrapper = mount(BottomPanel, { props: { title: "Find", open: true, height: 200, minHeight: 100, maxHeight: 230, "onUpdate:open": (open: boolean) => wrapper.setProps({ open }), "onUpdate:height": (height: number) => wrapper.setProps({ height }), onClose: () => closes.push(1), }, slots: { default: "

results

" }, }); const splitter = wrapper.get("[data-test=bottom-panel-splitter]"); await splitter.trigger("keydown", { key: "ArrowUp" }); expect(wrapper.get(".bottom-panel__body").attributes("style")).toContain("height: 212px"); await splitter.trigger("keydown", { key: "ArrowUp", shiftKey: true }); expect(wrapper.get(".bottom-panel__body").attributes("style")).toContain("height: 230px"); await splitter.trigger("keydown", { key: "ArrowDown", shiftKey: true }); await splitter.trigger("keydown", { key: "ArrowDown", shiftKey: true }); await splitter.trigger("keydown", { key: "ArrowDown", shiftKey: true }); expect(wrapper.get(".bottom-panel__body").attributes("style")).toContain("height: 100px"); await wrapper.get("[data-test=bottom-panel-toggle]").trigger("click"); expect(wrapper.find("[data-test=content]").exists()).toBe(false); expect(wrapper.find("[data-test=bottom-panel-splitter]").exists()).toBe(false); await wrapper.get("[data-test=bottom-panel-toggle]").trigger("click"); expect(wrapper.find("[data-test=content]").exists()).toBe(true); await wrapper.get("[data-test=bottom-panel-close]").trigger("click"); expect(closes).toEqual([1]); }); }); describe("find.open", () => { /** Mounts the main layout with the commands store started. */ async function mountLayout(): Promise { const wrapper = mount(MainLayout, { attachTo: document.body, global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } }, }); mounted.push(wrapper); await useCommandsStore(pinia).start(); await flushPromises(); return wrapper; } it("is registered with its own shortcut", async () => { await mountLayout(); const registered = paramsOf("ui.registerCommands")[0]?.commands as { id: string; defaultShortcut?: string }[]; expect(registered.find((c) => c.id === "find.open")?.defaultShortcut).toBe("Mod+Alt+F"); }); it("opens the panel from the shortcut, then hides and keeps the results", async () => { const wrapper = await mountLayout(); expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false); window.dispatchEvent(new KeyboardEvent("keydown", { key: "f", code: "KeyF", ctrlKey: true, altKey: true, bubbles: true })); await flushPromises(); expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(true); expect(document.activeElement).toBe(wrapper.get("[data-test=find-query]").element); await wrapper.get("[data-test=bottom-panel-close]").trigger("click"); expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false); }); it("searches at once for an agent's uiCommand with a query", async () => { const wrapper = await mountLayout(); await emit({ kind: "uiCommand", id: "find.open", params: { query: "needle", wholeWord: true, include: "*.php" } }); expect(paramsOf("search.find")).toEqual([ { query: "needle", regex: false, caseSensitive: false, wholeWord: true, include: ["*.php"], exclude: [] }, ]); await emit(results(7, "a.php", [[0, "[needle]"]])); expect(wrapper.findAll("[data-test=find-row]")).toHaveLength(1); expect((wrapper.get("[data-test=find-query]").element as HTMLInputElement).value).toBe("needle"); }); });