/** * Tests of navigation (M3.5): reading untrusted answers, Go to Definition * (one location reveals, several open the picker, none raises a toast), * the picker (keyboard, click, Escape, modal rule), the References tab * (status, grouping, click and Enter reveal), the inline rename (prepare, * preview count, Enter applies, errors stay in the field, Escape cancels) * and the undoable remote edit of the buffer sync. The engine is a fake * behind the mocked Tauri `invoke` and `listen`. */ import { Transaction } 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 { useModalsStore } from "../../src/commands/modals"; import { BufferSync, type BufferInfo, type SyncTransport } from "../../src/components/editor/bufferSync"; import NavPicker from "../../src/components/editor/nav/NavPicker.vue"; import ReferencesToolWindow from "../../src/components/editor/nav/ReferencesToolWindow.vue"; import RenameInput from "../../src/components/editor/nav/RenameInput.vue"; import { fileCount, toLocations, toReferences, toRenameable, useNavStore, } from "../../src/components/editor/nav/nav"; import { useEditorStore } from "../../src/stores/editor"; import { useNotificationsStore } from "../../src/stores/notifications"; /** Every engine call, in order. */ let calls: { command: string; params: Record }[]; /** Answers by command id; a function gets the params. */ let answers: Record; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components. */ let mounted: VueWrapper[]; /** Params of every `editor.reveal`. */ let reveals: unknown[]; const TEXT = " { return { start: { line, column: from }, end: { line, column: to } }; } /** The params of every call of a command. */ function paramsOf(command: string): Record[] { return calls.filter((c) => c.command === command).map((c) => c.params); } /** Opens `a.php` as the active tab with the cursor on `hello`. */ async function openTab(): Promise { const editor = useEditorStore(); answers["file.open"] = { id: 7, path: "a.php", text: TEXT, version: 1, dirty: false, lineEnding: "lf" }; await editor.openFile("a.php"); editor.syncOf(7)?.dispatch({ selection: { anchor: TEXT.indexOf("hello") + 2 } }); } /** * Mounts a component with the test's pinia. * * @param component - the component. */ function mountIt(component: Parameters[0]): VueWrapper { const wrapper = mount(component, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); return wrapper; } beforeEach(() => { pinia = createPinia(); setActivePinia(pinia); calls = []; answers = {}; mounted = []; reveals = []; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); listen.mockReset(); listen.mockResolvedValue(() => undefined); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (cmd === "engine_list_commands") { return Promise.resolve([]); } if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { return Promise.resolve(null); } calls.push({ command: args.command, params: args.params }); const answer = answers[args.command]; if (answer instanceof Error) { return Promise.reject(Object.assign(new Error(answer.message), { code: "failed" })); } return Promise.resolve(typeof answer === "function" ? (answer as (p: unknown) => unknown)(args.params) : (answer ?? null)); }); useCommandsStore().provide("editor.reveal", { run: (params) => void reveals.push(params) }); useNavStore().start(() => null); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } useNavStore().stop(); }); describe("reading answers", () => { it("drops malformed locations and counts files", () => { const items = toLocations({ locations: [ { path: "a.php", range: range(1, 2, 3) }, { path: "", range: range(0, 0, 1) }, { path: "b.php", range: { start: { line: -1, column: 0 }, end: { line: 0, column: 0 } } }, { path: "b.php", range: range(4, 0, 2) }, "junk", ], }); expect(items.map((i) => i.path)).toEqual(["a.php", "b.php"]); expect(fileCount(items)).toBe(2); expect(toLocations(null)).toEqual([]); const refs = toReferences({ locations: [{ path: "a.php", range: range(2, 4, 9), preview: "$g->hello();", previewColumn: 4 }] }); expect(refs[0]?.preview).toBe("$g->hello();"); expect(toRenameable(null)).toBeNull(); expect(toRenameable({ range: range(2, 20, 25), placeholder: "hello" })?.placeholder).toBe("hello"); expect(toRenameable({ range: range(2, 20, 25), placeholder: "" })).toBeNull(); }); }); describe("go to definition", () => { it("reveals a single location at once, with the cursor position", async () => { await openTab(); answers["lsp.definition"] = { locations: [{ path: "src/G.php", range: range(3, 6, 11) }] }; await useCommandsStore().execute("lsp.definition"); await flushPromises(); expect(paramsOf("lsp.definition")).toEqual([{ id: 7, position: { line: 2, column: 22 } }]); expect(reveals).toEqual([{ path: "src/G.php", line: 3, column: 6 }]); expect(useNavStore().picker).toBeNull(); }); it("opens the picker for several locations; Enter reveals the selected one", async () => { await openTab(); answers["lsp.definition"] = { locations: [ { path: "a.php", range: range(2, 20, 25) }, { path: "lib/b.php", range: range(9, 4, 9) }, ], }; const wrapper = mountIt(NavPicker); await useNavStore().definition(); await flushPromises(); expect(useModalsStore().current).toBe("navPicker"); const rows = wrapper.findAll("[data-test=nav-picker-row]"); expect(rows.map((r) => r.text())).toEqual(["a.phpline 3", "b.phplibline 10"]); const list = wrapper.find("[data-test=nav-picker-list]"); await list.trigger("keydown", { key: "ArrowDown" }); await list.trigger("keydown", { key: "Enter" }); await flushPromises(); expect(reveals).toEqual([{ path: "lib/b.php", line: 9, column: 4 }]); expect(wrapper.find("[data-test=nav-picker]").exists()).toBe(false); expect(useModalsStore().current).toBeNull(); }); it("closes the picker with Escape and when another modal opens", async () => { const nav = useNavStore(); const wrapper = mountIt(NavPicker); nav.openPicker("x", [ { path: "a.php", range: { start: { line: 0, column: 0 }, end: { line: 0, column: 1 } } }, { path: "b.php", range: { start: { line: 0, column: 0 }, end: { line: 0, column: 1 } } }, ]); await flushPromises(); await wrapper.find("[data-test=nav-picker-list]").trigger("keydown", { key: "Escape" }); expect(nav.picker).toBeNull(); nav.openPicker("x", []); useModalsStore().opened("palette", () => undefined); expect(nav.picker).toBeNull(); expect(reveals).toEqual([]); }); it("tells the user when there is no definition", async () => { await openTab(); answers["lsp.definition"] = { locations: [] }; await useNavStore().definition(); await flushPromises(); const toasts = useNotificationsStore().toasts; expect(toasts.map((t) => t.text)).toEqual(["No definition found for hello"]); }); it("raises an error toast when the server fails", async () => { await openTab(); answers["lsp.definition"] = new Error("the PHP language server is not running"); await useNavStore().definition(); await flushPromises(); expect(useNotificationsStore().toasts[0]?.level).toBe("error"); }); }); describe("references", () => { it("fills the References tab grouped by file; click and Enter reveal", async () => { await openTab(); answers["lsp.references"] = { locations: [ { path: "a.php", range: range(2, 20, 25), preview: "public function hello() {}", previewColumn: 16 }, { path: "src/b.php", range: range(2, 4, 9), preview: "$g->hello();", previewColumn: 4 }, { path: "src/b.php", range: range(5, 4, 9), preview: "$h->hello();", previewColumn: 4 }, ], }; const nav = useNavStore(); const wrapper = mountIt(ReferencesToolWindow); await useCommandsStore().execute("lsp.references"); await flushPromises(); expect(nav.visible).toBe(true); expect(wrapper.find("[data-test=references-status]").text()).toBe("3 references to hello in 2 files"); expect(wrapper.findAll("[data-test=references-file]").map((f) => f.text())).toEqual(["a.php1", "b.phpsrc2"]); const rows = wrapper.findAll("[data-test=references-row]"); expect(rows[1]?.find("mark").text()).toBe("hello"); await rows[2]?.trigger("click"); expect(reveals).toEqual([{ path: "src/b.php", line: 5, column: 4 }]); const list = wrapper.find("[data-test=references-list]"); await list.trigger("keydown", { key: "Home" }); await list.trigger("keydown", { key: "Enter" }); expect(reveals[1]).toEqual({ path: "a.php", line: 2, column: 20 }); }); it("shows a failure in the status line", async () => { await openTab(); answers["lsp.references"] = new Error("timed out"); const wrapper = mountIt(ReferencesToolWindow); await useNavStore().findReferences(); await flushPromises(); expect(wrapper.find("[data-test=references-status]").text()).toBe("Find References failed: timed out"); }); }); describe("rename", () => { it("prepares, previews the uses and applies the new name", async () => { await openTab(); answers["lsp.prepareRename"] = { range: range(2, 20, 25), placeholder: "hello" }; answers["lsp.references"] = { locations: [ { path: "a.php", range: range(2, 20, 25) }, { path: "b.php", range: range(2, 4, 9) }, { path: "c.php", range: range(2, 4, 9) }, ], }; answers["lsp.rename"] = { files: [{ path: "a.php", edits: 1, bufferId: 7, version: 2 }], edits: 3, written: 2 }; const wrapper = mountIt(RenameInput); await useCommandsStore().execute("lsp.rename"); await flushPromises(); expect(useModalsStore().current).toBe("rename"); const input = wrapper.find("[data-test=rename-input]"); expect(input.element.value).toBe("hello"); expect(wrapper.find("[data-test=rename-hint]").text()).toBe( "Changes 3 uses in 3 files. Enter to rename, Escape to cancel", ); await input.setValue("greet"); await input.trigger("keydown", { key: "Enter" }); await flushPromises(); expect(paramsOf("lsp.rename")).toEqual([{ id: 7, position: { line: 2, column: 22 }, newName: "greet" }]); expect(wrapper.find("[data-test=rename]").exists()).toBe(false); expect(useModalsStore().current).toBeNull(); }); it("keeps the field open with the error when the rename fails", async () => { await openTab(); answers["lsp.prepareRename"] = { range: range(2, 20, 25), placeholder: "hello" }; answers["lsp.references"] = { locations: [] }; answers["lsp.rename"] = new Error("the edit changes /x.php, which is outside the project"); const wrapper = mountIt(RenameInput); await useNavStore().startRename(null); await flushPromises(); const input = wrapper.find("[data-test=rename-input]"); await input.setValue("greet"); await input.trigger("keydown", { key: "Enter" }); await flushPromises(); expect(wrapper.find("[data-test=rename-hint]").text()).toContain("outside the project"); await input.trigger("keydown", { key: "Escape" }); expect(useNavStore().rename).toBeNull(); }); it("tells the user when nothing can be renamed, and skips an unchanged name", async () => { await openTab(); answers["lsp.prepareRename"] = null; await useNavStore().startRename(null); await flushPromises(); expect(useNavStore().rename).toBeNull(); expect(useNotificationsStore().toasts.map((t) => t.text)).toEqual(["There is nothing to rename at the cursor"]); answers["lsp.prepareRename"] = { range: range(2, 20, 25), placeholder: "hello" }; await useNavStore().startRename(null); await flushPromises(); await useNavStore().commitRename(); expect(paramsOf("lsp.rename")).toEqual([]); expect(useNavStore().rename).toBeNull(); }); }); describe("undoable remote edits", () => { it("puts an engine edit made during a rename into the undo history", async () => { let engineText = " { sent.push(params); version += 1; return Promise.resolve({ ok: true, value: { id: 1, version, dirty: true } }); }, get: () => Promise.resolve({ ok: true, value: { id: 1, path: "a.php", text: engineText, version, dirty: true, lineEnding: "lf" } satisfies BufferInfo, }), }; const sync = new BufferSync( { id: 1, path: "a.php", text: engineText, version: 1, dirty: false, lineEnding: "lf" }, [], transport, ); const history: (boolean | undefined)[] = []; const apply = sync.applyTransactions.bind(sync); sync.applyTransactions = (transactions) => { history.push(...transactions.map((tr) => tr.annotation(Transaction.addToHistory))); apply(transactions); }; sync.beginUndoableRemote(); engineText = "