M3.5: go to definition, find references and rename through Phpactor
Engine (`cmd/lsp_nav.rs`, on the pending outcomes of 20d1d28):
- `lsp.definition` (F12) and `lsp.references` (Shift+F12, sorted, with
line previews) return project-relative locations; locations outside
the project, such as PHAR stubs and symlink escapes, are dropped.
- `lsp.prepareRename` uses the word at the cursor when the server has
no prepareProvider.
- `lsp.rename` (F2) applies the workspace edit (`lsp_nav/edit.rs`):
1. Check everything first: inside the project, ranges fit (UTF-16,
CRLF), open buffers unchanged since the request, no file
operations, no incomplete edit.
2. Write closed files atomically through the VFS, restoring earlier
writes when a later one fails.
3. Change open buffers through `buffer.edit` (dirty, undoable).
4. Send each written file to Phpactor as didOpen/didSave/didClose
plus didChangeWatchedFiles; without this its index kept the old
names. Then the summary notification `notification.lsp.renamed`.
UI (`components/editor/nav/`):
- Mod+click goes to the definition, with a pointer cursor while Mod is
held.
- A location picker for several definitions (exclusive modal).
- A References tab in the bottom panel, grouped by file.
- An inline rename field with a use/file count (exclusive modal).
- `BufferSync.beginUndoableRemote` puts the engine's rename edit into
the editor history as one undo step per buffer.
- Catalog strings and tokens only.
Fake LSP server: `--script FILE` with scripted capabilities and
answers (additive next to M3.4's arms).
Tests:
- `crates/engine/tests/lsp_nav.rs` (fake): definition; bad positions;
references; prepareRename; a multi-file rename incl. a closed CRLF
file; refusals for outside the project, a bad range, a stale buffer,
bad names and no server.
- The ignored real-Phpactor test covers definition, references and a
rename and back across 3 files.
- Vitest `ui/tests/nav/`.
Live (Phpactor 2026.06.25.0, Windows, port 7935, tick on):
- definition 93 ms cold / 7-18 ms warm
- references ~140 ms
- prepareRename ~11 ms
- rename 28-59 ms
- index follows written files in 140 ms
- Phpactor 57 MB working set, ~1.6% of a core while ticking idle
Gate: 13 steps, 197 s, Vitest 484 + 1 skipped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b3fd7c6478
commit
578160a2ba
28 changed files with 3730 additions and 34 deletions
|
|
@ -49,6 +49,7 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
|||
const RUNTIME_KEYS = new Set([
|
||||
"notification.command.failed",
|
||||
"notification.lsp.failed",
|
||||
"notification.lsp.renamed",
|
||||
"notification.project.notLocal",
|
||||
"notification.project.openFailed",
|
||||
"notification.project.unsavedChanges",
|
||||
|
|
@ -141,7 +142,7 @@ describe("en.json", () => {
|
|||
it("uses flat dotted keys of known areas with string values", () => {
|
||||
for (const [key, value] of Object.entries(en)) {
|
||||
expect(key).toMatch(
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
);
|
||||
expect(typeof value).toBe("string");
|
||||
expect(value.trim()).not.toBe("");
|
||||
|
|
|
|||
354
ui/tests/nav/nav.test.ts
Normal file
354
ui/tests/nav/nav.test.ts
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
/**
|
||||
* 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<string, unknown> }[];
|
||||
/** Answers by command id; a function gets the params. */
|
||||
let answers: Record<string, unknown>;
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components. */
|
||||
let mounted: VueWrapper[];
|
||||
/** Params of every `editor.reveal`. */
|
||||
let reveals: unknown[];
|
||||
|
||||
const TEXT = "<?php\nclass Greeter {\n public function hello() {}\n}\n";
|
||||
|
||||
/**
|
||||
* A range on one line.
|
||||
*
|
||||
* @param line - 0-based line.
|
||||
* @param from - start column.
|
||||
* @param to - end column.
|
||||
*/
|
||||
function range(line: number, from: number, to: number): Record<string, unknown> {
|
||||
return { start: { line, column: from }, end: { line, column: to } };
|
||||
}
|
||||
|
||||
/** The params of every call of a command. */
|
||||
function paramsOf(command: string): Record<string, unknown>[] {
|
||||
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<void> {
|
||||
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<typeof mount>[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<string, unknown> }) => {
|
||||
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<HTMLInputElement>("[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<HTMLInputElement>("[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 = "<?php\nhello();\n";
|
||||
let version = 1;
|
||||
const sent: unknown[] = [];
|
||||
const transport: SyncTransport = {
|
||||
edit: (params) => {
|
||||
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 = "<?php\ngreet();\n";
|
||||
version = 2;
|
||||
sync.notifyVersion(2);
|
||||
await flushPromises();
|
||||
sync.endUndoableRemote(2);
|
||||
expect(sync.state.doc.toString()).toBe("<?php\ngreet();\n");
|
||||
expect(sent).toEqual([]);
|
||||
expect(history).toEqual([true]);
|
||||
|
||||
engineText = "<?php\nhello2();\n";
|
||||
version = 3;
|
||||
sync.notifyVersion(3);
|
||||
await flushPromises();
|
||||
expect(sync.state.doc.toString()).toBe("<?php\nhello2();\n");
|
||||
expect(history).toEqual([true, false]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue