M3.4: completion, hover and signature help from Phpactor
Engine (crates/engine/src/cmd/lsp_assist.rs), on M3.5's pending outcomes:
- lsp.completion {id, position, triggerCharacter?}: items with label,
kind, detail, Markdown documentation, insertText, textEdit,
additionalTextEdits, sortText; sorted, capped at 500 (cut lists are
incomplete), snippets turned into plain text.
- lsp.hover {id, position}: Markdown contents and range.
- lsp.signatureHelp {id, position}: signatures with UTF-16 parameter spans.
- The request is queued after every didChange; the answer is converted
in the reply callback, off the engine lock. Positions are checked
against the buffer. Server strings and lists are capped.
- lutra-lsp-fake answers completion and signature help.
Editor (ui/src/components/editor/assist/):
- Completion source with Lutra's triggers (identifiers, $, ->, ?->, ::,
namespace \; not in strings or comments unless asked), the server's
ranking as boost, text edits and imports applied in UTF-16 (CRLF too),
Lucide kind icons.
- Hover documentation (350 ms) and editor.quickDocumentation (Mod+I).
- Signature help on ( and , following the cursor; editor.parameterInfo.
- editor.complete.
- Lutra's own Markdown renderer without HTML (XSS-tested), tokens only.
- Requests wait for the buffer sync to be idle and use runWaiting.
- New dependency @codemirror/autocomplete (MIT, already transitive).
Tests: 6 engine tests against the fake server, 9 unit tests, an ignored
real-Phpactor latency test, 29 Vitest tests; palette and menu tests list
the new UI commands.
Measured with the real Phpactor (Windows 11, debug build, 25 ms tick):
- Completion 61-109 ms while typing (median 76 ms; ~107 ms in the app).
- Hover and signature help ~16 ms median.
- A useful list 2.3 s after opening a file in a 20-class project, ~65 s
for 2,000 classes (indexing).
- Phpactor 56-71 MB working set, ~6% of one core while typing.
Live-checked in the app on port 7934. Docs: Code completion 0% -> 5%
(est.), feature depth ~4.1% -> ~4.6%, breadth 26/155, architecture, G6,
ui-parity, language-parity, roadmap, README.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
12d21d96f4
commit
a212a44490
35 changed files with 3916 additions and 25 deletions
285
ui/tests/editor/assist/completion.test.ts
Normal file
285
ui/tests/editor/assist/completion.test.ts
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
/**
|
||||
* Tests of the completion source (M3.4, `assist/completion.ts`): Lutra's
|
||||
* trigger rules, the query it sends (UTF-16 columns, trigger characters,
|
||||
* waiting for the buffer sync), local filtering only for complete lists,
|
||||
* and applying items: text edits, text typed after the request, imports
|
||||
* as additional edits, CRLF documents and CRLF insert texts.
|
||||
*/
|
||||
import { CompletionContext, type Completion, type CompletionResult } from "@codemirror/autocomplete";
|
||||
import { php } from "@codemirror/lang-php";
|
||||
import { ensureSyntaxTree } from "@codemirror/language";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
completionChanges,
|
||||
completionTrigger,
|
||||
lspCompletionSource,
|
||||
toOptions,
|
||||
} from "../../../src/components/editor/assist/completion";
|
||||
import { kindIcon } from "../../../src/components/editor/assist/icons";
|
||||
import { assistExtensions } from "../../../src/components/editor/assist";
|
||||
import { toCompletionList, type CompletionItem } from "../../../src/components/editor/assist/types";
|
||||
import { fakeBuffer, fakeTransport } from "./fakes";
|
||||
|
||||
/** Views created by a test, destroyed after it. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
});
|
||||
|
||||
/** A PHP editor state with the cursor at `|` in `text`. */
|
||||
function stateAt(text: string): { state: EditorState; pos: number } {
|
||||
const pos = text.indexOf("|");
|
||||
const doc = text.slice(0, pos) + text.slice(pos + 1);
|
||||
const state = EditorState.create({ doc, extensions: [php()], selection: { anchor: pos } });
|
||||
ensureSyntaxTree(state, state.doc.length, 5000);
|
||||
return { state, pos };
|
||||
}
|
||||
|
||||
/** A complete item with defaults. */
|
||||
function item(over: Partial<CompletionItem>): CompletionItem {
|
||||
return { label: "x", kind: "text", insertText: over.label ?? "x", ...over };
|
||||
}
|
||||
|
||||
/** Applies a plan to a document and returns the text and cursor. */
|
||||
function applyPlan(doc: string, plan: ReturnType<typeof completionChanges>): { text: string; cursor: number } {
|
||||
const state = EditorState.create({ doc });
|
||||
const changes = state.changes(plan.changes);
|
||||
return { text: changes.apply(state.doc).toString(), cursor: changes.mapPos(plan.mainEnd, 1) };
|
||||
}
|
||||
|
||||
describe("completionTrigger", () => {
|
||||
it("triggers after member and static access, variables and namespaces", () => {
|
||||
expect(completionTrigger("$a->", false)).toEqual({ back: 0, character: ">" });
|
||||
expect(completionTrigger("$a?->", false)).toEqual({ back: 0, character: ">" });
|
||||
expect(completionTrigger("Foo::", false)).toEqual({ back: 0, character: ":" });
|
||||
expect(completionTrigger("echo $", false)).toEqual({ back: 1, character: "$" });
|
||||
expect(completionTrigger("new App\\", false)).toEqual({ back: 0, character: "\\" });
|
||||
});
|
||||
|
||||
it("triggers on identifiers and variables being typed", () => {
|
||||
expect(completionTrigger("$a->fo", false)).toEqual({ back: 2 });
|
||||
expect(completionTrigger("echo $na", false)).toEqual({ back: 3 });
|
||||
expect(completionTrigger("strl", false)).toEqual({ back: 4 });
|
||||
expect(completionTrigger("$ä", false)).toEqual({ back: 2 });
|
||||
});
|
||||
|
||||
it("does not trigger on numbers, operators or spaces unless asked", () => {
|
||||
expect(completionTrigger("x = 12", false)).toBeNull();
|
||||
expect(completionTrigger("x = 1e5", false)).toBeNull();
|
||||
expect(completionTrigger("a - ", false)).toBeNull();
|
||||
expect(completionTrigger("a -", false)).toBeNull();
|
||||
expect(completionTrigger("", false)).toBeNull();
|
||||
expect(completionTrigger("a - ", true)).toEqual({ back: 0 });
|
||||
expect(completionTrigger("12", true)).toEqual({ back: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("toCompletionList", () => {
|
||||
it("drops malformed items and defaults the rest", () => {
|
||||
const list = toCompletionList({
|
||||
incomplete: true,
|
||||
items: [
|
||||
{ label: "a", kind: "nonsense" },
|
||||
{ label: "" },
|
||||
"junk",
|
||||
{ label: "b", kind: "class", insertText: "B", textEdit: { range: { start: {}, end: {} }, newText: "x" } },
|
||||
{ label: "c", additionalTextEdits: [{ range: { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } }, newText: "u" }, null] },
|
||||
],
|
||||
});
|
||||
expect(list.incomplete).toBe(true);
|
||||
expect(list.items.map((i) => i.label)).toEqual(["a", "b", "c"]);
|
||||
expect(list.items[0]).toEqual({ label: "a", kind: "text", insertText: "a" });
|
||||
expect(list.items[1]?.textEdit).toBeUndefined();
|
||||
expect(list.items[2]?.additionalTextEdits).toHaveLength(1);
|
||||
expect(toCompletionList(null)).toEqual({ items: [], incomplete: false });
|
||||
expect(toCompletionList({ items: "no" })).toEqual({ items: [], incomplete: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("completionChanges", () => {
|
||||
it("applies a text edit and the typing since the request", () => {
|
||||
const doc = "<?php\n$x->fo";
|
||||
const requestDoc = Text.of(doc.split("\n"));
|
||||
const requestPos = doc.length;
|
||||
const format = item({
|
||||
label: "format",
|
||||
insertText: "format(",
|
||||
textEdit: { range: { start: { line: 1, column: 4 }, end: { line: 1, column: 6 } }, newText: "format(" },
|
||||
});
|
||||
expect(applyPlan(doc, completionChanges(requestDoc, requestPos, format, 10, 12, doc.length))).toEqual({
|
||||
text: "<?php\n$x->format(",
|
||||
cursor: 17,
|
||||
});
|
||||
const typedMore = doc + "rm";
|
||||
expect(applyPlan(typedMore, completionChanges(requestDoc, requestPos, format, 10, 14, typedMore.length))).toEqual({
|
||||
text: "<?php\n$x->format(",
|
||||
cursor: 17,
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces the typed word with insertText without a text edit", () => {
|
||||
const doc = "<?php\necho $na";
|
||||
const plan = completionChanges(Text.of(doc.split("\n")), doc.length, item({ label: "$name", insertText: "$name" }), 11, 14, doc.length);
|
||||
expect(applyPlan(doc, plan)).toEqual({ text: "<?php\necho $name", cursor: 16 });
|
||||
});
|
||||
|
||||
it("adds imports from additional edits and skips overlapping ones", () => {
|
||||
const doc = "<?php\n\nnew Fm";
|
||||
const requestDoc = Text.of(doc.split("\n"));
|
||||
const fmt = item({
|
||||
label: "Fmt",
|
||||
insertText: "Fmt",
|
||||
additionalTextEdits: [
|
||||
{ range: { start: { line: 0, column: 5 }, end: { line: 0, column: 5 } }, newText: "\nuse App\\Fmt;" },
|
||||
{ range: { start: { line: 2, column: 4 }, end: { line: 2, column: 6 } }, newText: "clash" },
|
||||
],
|
||||
});
|
||||
const result = applyPlan(doc, completionChanges(requestDoc, doc.length, fmt, 11, 13, doc.length));
|
||||
expect(result.text).toBe("<?php\nuse App\\Fmt;\n\nnew Fmt");
|
||||
expect(result.cursor).toBe(result.text.length);
|
||||
});
|
||||
|
||||
it("works on CRLF documents and turns CRLF insert texts into line breaks", () => {
|
||||
const engineText = "<?php\r\nfunction a() {\r\n $this->ru\r\n}\r\n";
|
||||
const lines = engineText.split("\r\n");
|
||||
const requestDoc = Text.of(lines);
|
||||
const state = EditorState.create({ doc: requestDoc });
|
||||
const line = state.doc.line(3);
|
||||
const requestPos = line.to;
|
||||
const run = item({
|
||||
label: "run",
|
||||
textEdit: { range: { start: { line: 2, column: 11 }, end: { line: 2, column: 13 } }, newText: "run(\r\n 1\r\n)" },
|
||||
});
|
||||
const plan = completionChanges(requestDoc, requestPos, run, requestPos - 2, requestPos, state.doc.length);
|
||||
const changes = state.changes(plan.changes);
|
||||
const after = changes.apply(state.doc);
|
||||
expect(after.lines).toBe(7);
|
||||
expect(after.line(3).text).toBe(" $this->run(");
|
||||
expect(after.line(4).text).toBe(" 1");
|
||||
expect(after.line(5).text).toBe(")");
|
||||
expect(after.sliceString(0)).not.toContain("\r");
|
||||
});
|
||||
|
||||
it("clamps edits that point past the document to its last line", () => {
|
||||
const doc = "<?php\n$a";
|
||||
const plan = completionChanges(
|
||||
Text.of(doc.split("\n")),
|
||||
doc.length,
|
||||
item({ label: "a", textEdit: { range: { start: { line: 9, column: 0 }, end: { line: 9, column: 99 } }, newText: "$abc" } }),
|
||||
6,
|
||||
8,
|
||||
doc.length,
|
||||
);
|
||||
expect(applyPlan(doc, plan).text).toBe("<?php\n$abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("lspCompletionSource", () => {
|
||||
it("asks with UTF-16 columns after the sync is idle and maps the items", async () => {
|
||||
const transport = fakeTransport({
|
||||
items: [
|
||||
{ label: "format", kind: "method", detail: "format(): string", documentation: "**doc**", insertText: "format(" },
|
||||
{ label: "$value", kind: "variable", insertText: "$value" },
|
||||
],
|
||||
incomplete: false,
|
||||
});
|
||||
const buffer = fakeBuffer(7);
|
||||
const { state, pos } = stateAt("<?php\n$\u{1F9A6}->fo|");
|
||||
const source = lspCompletionSource(buffer, transport);
|
||||
const result = (await source(new CompletionContext(state, pos, false))) as CompletionResult;
|
||||
expect(buffer.idleCalls).toBe(1);
|
||||
expect(transport.calls).toEqual([
|
||||
{ command: "lsp.completion", params: { id: 7, position: { line: 1, column: 7 } } },
|
||||
]);
|
||||
expect(result.from).toBe(pos - 2);
|
||||
expect(result.validFor).toBeInstanceOf(RegExp);
|
||||
expect(result.options.map((o) => o.label)).toEqual(["format", "$value"]);
|
||||
expect(result.options[0]?.detail).toBe("format(): string");
|
||||
expect(result.options[0]?.type).toBe("method");
|
||||
expect((result.options[0]?.boost ?? 0) > (result.options[1]?.boost ?? 0)).toBe(true);
|
||||
const info = result.options[0]?.info;
|
||||
expect(typeof info).toBe("function");
|
||||
});
|
||||
|
||||
it("sends the trigger character and asks again for incomplete lists", async () => {
|
||||
const transport = fakeTransport({ items: [{ label: "run", kind: "method", insertText: "run" }], incomplete: true });
|
||||
const { state, pos } = stateAt("<?php\n$a->|");
|
||||
const result = (await lspCompletionSource(fakeBuffer(1), transport)(new CompletionContext(state, pos, false))) as CompletionResult;
|
||||
expect(transport.calls[0]?.params).toMatchObject({ triggerCharacter: ">" });
|
||||
expect(result.from).toBe(pos);
|
||||
expect(result.validFor).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stays quiet in comments and strings unless asked", async () => {
|
||||
const transport = fakeTransport({ items: [{ label: "x", kind: "text", insertText: "x" }], incomplete: false });
|
||||
const source = lspCompletionSource(fakeBuffer(1), transport);
|
||||
const comment = stateAt("<?php\n// call fo|");
|
||||
expect(await source(new CompletionContext(comment.state, comment.pos, false))).toBeNull();
|
||||
const string = stateAt("<?php\n$s = 'fo|';");
|
||||
expect(await source(new CompletionContext(string.state, string.pos, false))).toBeNull();
|
||||
expect(transport.calls).toHaveLength(0);
|
||||
expect(await source(new CompletionContext(comment.state, comment.pos, true))).not.toBeNull();
|
||||
});
|
||||
|
||||
it("drops the answer when the document moved on or the query failed", async () => {
|
||||
const { state, pos } = stateAt("<?php\nfo|");
|
||||
const view = new EditorView({ state });
|
||||
views.push(view);
|
||||
const buffer = fakeBuffer(1, () => {
|
||||
view.dispatch({ changes: { from: pos, insert: "o" } });
|
||||
});
|
||||
const transport = fakeTransport({ items: [{ label: "foo", kind: "function", insertText: "foo" }], incomplete: false });
|
||||
const context = new CompletionContext(state, pos, false, view);
|
||||
expect(await lspCompletionSource(buffer, transport)(context)).toBeNull();
|
||||
expect(transport.calls).toHaveLength(0);
|
||||
const failing = fakeTransport(null, { code: "failed", message: "no PHP language server is running" });
|
||||
expect(await lspCompletionSource(fakeBuffer(1), failing)(new CompletionContext(state, pos, false))).toBeNull();
|
||||
});
|
||||
|
||||
it("applies an option through the view, with the import", () => {
|
||||
const doc = "<?php\n\nnew Fm";
|
||||
const view = new EditorView({ state: EditorState.create({ doc, selection: { anchor: doc.length } }) });
|
||||
views.push(view);
|
||||
const [option] = toOptions(
|
||||
[
|
||||
item({
|
||||
label: "Fmt",
|
||||
kind: "class",
|
||||
insertText: "Fmt",
|
||||
additionalTextEdits: [{ range: { start: { line: 0, column: 5 }, end: { line: 0, column: 5 } }, newText: "\nuse App\\Fmt;" }],
|
||||
}),
|
||||
],
|
||||
view.state.doc,
|
||||
doc.length,
|
||||
);
|
||||
const apply = (option as Completion).apply;
|
||||
expect(typeof apply).toBe("function");
|
||||
if (typeof apply === "function") {
|
||||
apply(view, option as Completion, doc.length - 2, doc.length);
|
||||
}
|
||||
expect(view.state.doc.toString()).toBe("<?php\nuse App\\Fmt;\n\nnew Fmt");
|
||||
expect(view.state.selection.main.head).toBe(view.state.doc.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assistExtensions", () => {
|
||||
it("is only added for PHP files of a buffer", () => {
|
||||
expect(assistExtensions("a.txt", fakeBuffer(1))).toEqual([]);
|
||||
expect(assistExtensions("a.php", undefined)).toEqual([]);
|
||||
expect(assistExtensions("src/A.php", fakeBuffer(1))).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("renders a Lucide icon with the kind's catalog name", () => {
|
||||
const icon = kindIcon("class");
|
||||
expect(icon.title).toBe("Class");
|
||||
expect(icon.querySelector("svg")).not.toBeNull();
|
||||
expect(kindIcon("nonsense").className).toContain("lt-assist-kind-text");
|
||||
});
|
||||
});
|
||||
|
||||
41
ui/tests/editor/assist/fakes.ts
Normal file
41
ui/tests/editor/assist/fakes.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
* Fakes for the assist tests: a transport that records queries and
|
||||
* answers with a fixed result, and a buffer whose sync is always idle.
|
||||
*/
|
||||
import type { AssistBuffer, AssistTransport } from "../../../src/components/editor/assist/types";
|
||||
import type { EngineError, JsonValue } from "../../../src/ipc";
|
||||
|
||||
/** A recording transport. */
|
||||
export interface FakeTransport extends AssistTransport {
|
||||
/** The queries sent, in order. */
|
||||
calls: { command: string; params: JsonValue }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A transport that answers every query with `value`, or fails with
|
||||
* `error`.
|
||||
*/
|
||||
export function fakeTransport(value: unknown, error?: EngineError): FakeTransport {
|
||||
const calls: { command: string; params: JsonValue }[] = [];
|
||||
return {
|
||||
calls,
|
||||
query: (command, params) => {
|
||||
calls.push({ command, params });
|
||||
return Promise.resolve(error ? { ok: false, error } : { ok: true, value });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A buffer that counts idle waits; `onIdle` runs inside each one. */
|
||||
export function fakeBuffer(id: number, onIdle?: () => void): AssistBuffer & { idleCalls: number } {
|
||||
const buffer = {
|
||||
id,
|
||||
idleCalls: 0,
|
||||
idle: (): Promise<void> => {
|
||||
buffer.idleCalls += 1;
|
||||
onIdle?.();
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
return buffer;
|
||||
}
|
||||
178
ui/tests/editor/assist/hoverSignature.test.ts
Normal file
178
ui/tests/editor/assist/hoverSignature.test.ts
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
/**
|
||||
* Tests of hover documentation and signature help (M3.4,
|
||||
* `assist/hover.ts`, `assist/signature.ts`): the queries they send, the
|
||||
* tooltip range, safe rendering, the highlighted parameter, the counter,
|
||||
* typing `(` and `,`, following the cursor and closing with Escape.
|
||||
*/
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { assistExtensions } from "../../../src/components/editor/assist";
|
||||
import { assistEnabled, quickDocumentation } from "../../../src/components/editor/assist/commands";
|
||||
import { hoverAt } from "../../../src/components/editor/assist/hover";
|
||||
import {
|
||||
lspSignatureHelp,
|
||||
renderSignature,
|
||||
setSignature,
|
||||
signatureField,
|
||||
} from "../../../src/components/editor/assist/signature";
|
||||
import { toHover, toSignatureHelp, type SignatureHelpResult } from "../../../src/components/editor/assist/types";
|
||||
import { fakeBuffer, fakeTransport } from "./fakes";
|
||||
|
||||
/** Views created by a test, destroyed after it. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
});
|
||||
|
||||
/** A mounted view with `doc` and `extensions`. */
|
||||
function mount(doc: string, extensions: Extension = []): EditorView {
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const view = new EditorView({ state: EditorState.create({ doc, extensions }), parent });
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** A signature help result for `pair(int $a, string $b)`. */
|
||||
const pair: SignatureHelpResult = {
|
||||
signatures: [
|
||||
{
|
||||
label: "pair(int $a, string $b): void",
|
||||
documentation: "Makes a *pair*.",
|
||||
parameters: [{ label: [5, 11], documentation: "the `first`" }, { label: [13, 22] }],
|
||||
},
|
||||
],
|
||||
activeSignature: 0,
|
||||
activeParameter: 1,
|
||||
};
|
||||
|
||||
describe("hover", () => {
|
||||
it("asks for the hovered position and spans the returned range", async () => {
|
||||
const view = mount("<?php\r\n$x = new Foo();".replace("\r\n", "\n"));
|
||||
const transport = fakeTransport({
|
||||
contents: "```php\nclass Foo\n```\n<img src=x onerror=alert(1)>",
|
||||
range: { start: { line: 1, column: 9 }, end: { line: 1, column: 12 } },
|
||||
});
|
||||
const tooltip = await hoverAt(view, 16, fakeBuffer(3), transport);
|
||||
expect(transport.calls).toEqual([{ command: "lsp.hover", params: { id: 3, position: { line: 1, column: 10 } } }]);
|
||||
expect(tooltip?.pos).toBe(15);
|
||||
expect(tooltip?.end).toBe(18);
|
||||
expect(tooltip?.above).toBe(true);
|
||||
const dom = tooltip?.create(view).dom as HTMLElement;
|
||||
expect(dom.classList.contains("lt-assist-hover")).toBe(true);
|
||||
expect(dom.querySelector("pre code")?.textContent).toBe("class Foo");
|
||||
expect(dom.querySelector("img")).toBeNull();
|
||||
expect(dom.textContent).toContain("<img src=x onerror=alert(1)>");
|
||||
});
|
||||
|
||||
it("shows nothing for empty or failed answers", async () => {
|
||||
const view = mount("<?php\n");
|
||||
expect(await hoverAt(view, 2, fakeBuffer(1), fakeTransport({ contents: " " }))).toBeNull();
|
||||
expect(await hoverAt(view, 2, fakeBuffer(1), fakeTransport(null, { code: "failed", message: "x" }))).toBeNull();
|
||||
expect(toHover({ contents: 5 })).toBeNull();
|
||||
expect(toHover({ contents: "a", range: { start: { line: -1 } } })).toEqual({ contents: "a" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderSignature", () => {
|
||||
it("highlights the active parameter and shows its and the signature's docs", () => {
|
||||
const dom = renderSignature(pair);
|
||||
expect(dom.querySelector(".lt-assist-signature-label")?.textContent).toBe("pair(int $a, string $b): void");
|
||||
expect(dom.querySelector(".lt-assist-signature-active")?.textContent).toBe("string $b");
|
||||
expect(dom.querySelectorAll(".lt-assist-signature-doc")).toHaveLength(1);
|
||||
const first = renderSignature({ ...pair, activeParameter: 0 });
|
||||
expect(first.querySelector(".lt-assist-signature-active")?.textContent).toBe("int $a");
|
||||
expect(first.querySelectorAll(".lt-assist-signature-doc")).toHaveLength(2);
|
||||
expect(first.querySelector(".lt-assist-signature-doc code")?.textContent).toBe("first");
|
||||
});
|
||||
|
||||
it("counts several signatures and lets a signature override the active parameter", () => {
|
||||
const two: SignatureHelpResult = {
|
||||
signatures: [...pair.signatures, { label: "pair(int $a)", parameters: [{ label: [5, 11] }], activeParameter: 0 }],
|
||||
activeSignature: 1,
|
||||
activeParameter: 3,
|
||||
};
|
||||
const dom = renderSignature(two);
|
||||
expect(dom.querySelector(".lt-assist-signature-count")?.textContent).toBe("2 of 2");
|
||||
expect(dom.querySelector(".lt-assist-signature-active")?.textContent).toBe("int $a");
|
||||
});
|
||||
|
||||
it("checks the untrusted result", () => {
|
||||
expect(toSignatureHelp({ signatures: [] })).toBeNull();
|
||||
expect(toSignatureHelp(null)).toBeNull();
|
||||
const help = toSignatureHelp({
|
||||
signatures: [{ label: "f(a)", parameters: [{ label: [2, 3] }, { label: [2, 99] }, { label: "a" }, "junk"] }],
|
||||
activeSignature: 7,
|
||||
activeParameter: -1,
|
||||
});
|
||||
expect(help?.activeSignature).toBe(0);
|
||||
expect(help?.activeParameter).toBe(0);
|
||||
expect(help?.signatures[0]?.parameters.map((p) => p.label)).toEqual([[2, 3], null, null, null]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("signature help while typing", () => {
|
||||
it("opens on (, follows the cursor and closes with Escape", async () => {
|
||||
const transport = fakeTransport({
|
||||
signatures: [{ label: "pair(int $a, string $b): void", parameters: [{ label: [5, 11] }, { label: [13, 22] }] }],
|
||||
activeSignature: 0,
|
||||
activeParameter: 0,
|
||||
});
|
||||
const view = mount("<?php\npair", lspSignatureHelp(fakeBuffer(5), transport));
|
||||
view.dispatch({ changes: { from: 10, insert: "(" }, selection: { anchor: 11 }, userEvent: "input.type" });
|
||||
await vi.waitFor(() => {
|
||||
expect(view.state.field(signatureField)).not.toBeNull();
|
||||
});
|
||||
expect(transport.calls[0]).toEqual({ command: "lsp.signatureHelp", params: { id: 5, position: { line: 1, column: 5 } } });
|
||||
expect(view.dom.querySelector(".lt-assist-signature-active")?.textContent).toBe("int $a");
|
||||
view.dispatch({ changes: { from: 11, insert: "1" }, selection: { anchor: 12 }, userEvent: "input.type" });
|
||||
await vi.waitFor(() => {
|
||||
expect(transport.calls).toHaveLength(2);
|
||||
});
|
||||
const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true });
|
||||
view.contentDOM.dispatchEvent(escape);
|
||||
expect(view.state.field(signatureField)).toBeNull();
|
||||
});
|
||||
|
||||
it("closes when the server has no signatures any more", async () => {
|
||||
const transport = fakeTransport({ signatures: [], activeSignature: 0, activeParameter: 0 });
|
||||
const view = mount("<?php\npair(1)", lspSignatureHelp(fakeBuffer(5), transport));
|
||||
view.dispatch({ effects: setSignature.of({ pos: 11, help: pair }) });
|
||||
expect(view.state.field(signatureField)).not.toBeNull();
|
||||
view.dispatch({ selection: { anchor: 13 } });
|
||||
await vi.waitFor(() => {
|
||||
expect(view.state.field(signatureField)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores typing that does not start an argument", async () => {
|
||||
const transport = fakeTransport(null);
|
||||
const view = mount("<?php\n", lspSignatureHelp(fakeBuffer(5), transport));
|
||||
view.dispatch({ changes: { from: 6, insert: "x" }, userEvent: "input.type" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(transport.calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assist commands", () => {
|
||||
it("are enabled only with a PHP editor and show quick documentation at the cursor", async () => {
|
||||
expect(assistEnabled()).toBe(false);
|
||||
const transport = fakeTransport({ contents: "**Foo** docs" });
|
||||
const view = mount("<?php\nnew Foo();", assistExtensions("a.php", fakeBuffer(9), transport));
|
||||
view.dispatch({ selection: { anchor: 11 } });
|
||||
expect(assistEnabled()).toBe(true);
|
||||
await quickDocumentation();
|
||||
expect(transport.calls[0]).toEqual({ command: "lsp.hover", params: { id: 9, position: { line: 1, column: 5 } } });
|
||||
expect(view.dom.querySelector(".lt-assist-hover strong")?.textContent).toBe("Foo");
|
||||
view.dispatch({ selection: { anchor: 12 } });
|
||||
expect(view.dom.querySelector(".lt-assist-hover")).toBeNull();
|
||||
view.destroy();
|
||||
views = views.filter((v) => v !== view);
|
||||
expect(assistEnabled()).toBe(false);
|
||||
});
|
||||
});
|
||||
97
ui/tests/editor/assist/markdown.test.ts
Normal file
97
ui/tests/editor/assist/markdown.test.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
/**
|
||||
* Tests of the safe Markdown renderer (M3.4, `assist/markdown.ts`): the
|
||||
* supported blocks and inlines, and that nothing in a server answer turns
|
||||
* into HTML, script, a link target or an image source (XSS).
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MAX_MARKDOWN, renderMarkdown } from "../../../src/components/editor/assist/markdown";
|
||||
|
||||
/** Tag names of every element below `root`. */
|
||||
function tags(root: Element): string[] {
|
||||
return [...root.querySelectorAll("*")].map((e) => e.tagName.toLowerCase());
|
||||
}
|
||||
|
||||
describe("renderMarkdown", () => {
|
||||
it("renders code fences, headings, rules, lists and paragraphs", () => {
|
||||
const root = renderMarkdown(
|
||||
[
|
||||
"```php",
|
||||
"class A { }",
|
||||
"```",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"# Title",
|
||||
"First line",
|
||||
"second line ",
|
||||
"third",
|
||||
"",
|
||||
"- one",
|
||||
"- two",
|
||||
"1. first",
|
||||
"> quoted",
|
||||
].join("\n"),
|
||||
);
|
||||
expect(root.className).toBe("lt-markdown");
|
||||
const code = root.querySelector("pre > code");
|
||||
expect(code?.textContent).toBe("class A { }");
|
||||
expect((code as HTMLElement | null)?.dataset.language).toBe("php");
|
||||
expect(root.querySelector("hr")).not.toBeNull();
|
||||
expect(root.querySelector(".lt-markdown-heading strong")?.textContent).toBe("Title");
|
||||
const paragraph = [...root.querySelectorAll("p")].find((p) => p.textContent.startsWith("First"));
|
||||
expect(paragraph?.textContent).toBe("First line second linethird");
|
||||
expect(paragraph?.querySelector("br")).not.toBeNull();
|
||||
expect([...root.querySelectorAll("ul > li")].map((li) => li.textContent)).toEqual(["one", "two"]);
|
||||
expect(root.querySelector("ol > li")?.textContent).toBe("first");
|
||||
expect(root.querySelector("blockquote")?.textContent).toBe("quoted");
|
||||
});
|
||||
|
||||
it("renders inline code, strong, emphasis, links and escapes", () => {
|
||||
const root = renderMarkdown("Use `a*b*c` with **bold**, *em*, _em2_, snake_case_name, [docs](https://php.net) and \\*not em\\*.");
|
||||
const p = root.querySelector("p");
|
||||
expect(p?.querySelector("code")?.textContent).toBe("a*b*c");
|
||||
expect(p?.querySelector("strong")?.textContent).toBe("bold");
|
||||
expect([...(p?.querySelectorAll("em") ?? [])].map((e) => e.textContent)).toEqual(["em", "em2"]);
|
||||
expect(p?.querySelector(".lt-markdown-link")?.textContent).toBe("docs");
|
||||
expect(p?.textContent).toContain("snake_case_name");
|
||||
expect(p?.textContent).toContain("*not em*.");
|
||||
});
|
||||
|
||||
it("never creates HTML, links, images or script from the source (XSS)", () => {
|
||||
const attacks = [
|
||||
"<img src=x onerror=alert(1)>",
|
||||
"<script>alert(1)</script>",
|
||||
"[click](javascript:alert(1))",
|
||||
"",
|
||||
"<a href=\"javascript:alert(1)\">a</a>",
|
||||
"<svg onload=alert(1)>",
|
||||
"```\n</code><script>alert(1)</script>\n```",
|
||||
"**<iframe src=//evil>**",
|
||||
"<https://evil.example>",
|
||||
"<b> <script>",
|
||||
];
|
||||
for (const attack of attacks) {
|
||||
const root = renderMarkdown(attack);
|
||||
const allowed = ["p", "pre", "code", "strong", "em", "ul", "ol", "li", "hr", "blockquote", "span", "br"];
|
||||
expect(tags(root).every((tag) => allowed.includes(tag)), attack).toBe(true);
|
||||
for (const element of root.querySelectorAll("*")) {
|
||||
const names = [...element.attributes].map((a) => a.name);
|
||||
expect(names.every((n) => n === "class" || n === "data-language"), attack).toBe(true);
|
||||
}
|
||||
}
|
||||
const img = renderMarkdown("<img src=x onerror=alert(1)>");
|
||||
expect(img.textContent).toBe("<img src=x onerror=alert(1)>");
|
||||
expect(renderMarkdown("<b>").textContent).toBe("<b>");
|
||||
const fenced = renderMarkdown("```\"onmouseover=alert(1)\n```");
|
||||
expect(fenced.querySelector<HTMLElement>("code")?.dataset.language).toBeUndefined();
|
||||
});
|
||||
|
||||
it("caps the source and survives deep nesting", () => {
|
||||
const long = renderMarkdown("a".repeat(MAX_MARKDOWN + 100));
|
||||
expect(long.textContent.length).toBe(MAX_MARKDOWN);
|
||||
const nested = renderMarkdown("*".repeat(200) + "x" + "*".repeat(200));
|
||||
expect(nested.textContent).toContain("x");
|
||||
const brackets = renderMarkdown("[".repeat(500) + "x");
|
||||
expect(brackets.textContent).toContain("x");
|
||||
});
|
||||
});
|
||||
|
|
@ -254,7 +254,7 @@ describe("AppMenu", () => {
|
|||
expect(menuShown()).toBe(true);
|
||||
expect(menu.find("[data-test=menu-button]").attributes("aria-expanded")).toBe("true");
|
||||
const headings = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => g.querySelector(".app-menu__heading")?.textContent.trim());
|
||||
expect(headings).toEqual(["File", "View", "Go", "Help"]);
|
||||
expect(headings).toEqual(["File", "Edit", "View", "Go", "Help"]);
|
||||
expect(itemIds()).toEqual([
|
||||
"project.openDialog",
|
||||
"file.save",
|
||||
|
|
@ -262,6 +262,9 @@ describe("AppMenu", () => {
|
|||
"buffer.close",
|
||||
"project.close",
|
||||
"app.quit",
|
||||
"editor.complete",
|
||||
"editor.parameterInfo",
|
||||
"editor.quickDocumentation",
|
||||
"palette.open",
|
||||
"view.toggleProjectTree",
|
||||
"view.toggleStructure",
|
||||
|
|
|
|||
|
|
@ -260,13 +260,16 @@ describe("CommandPalette", () => {
|
|||
expect(rows(wrapper)).toEqual([
|
||||
"project.close",
|
||||
"palette.open",
|
||||
"editor.complete",
|
||||
"find.open",
|
||||
"goto.classOpen",
|
||||
"goto.fileOpen",
|
||||
"goto.symbolOpen",
|
||||
"project.openDialog",
|
||||
"menu.open",
|
||||
"editor.parameterInfo",
|
||||
"problems.open",
|
||||
"editor.quickDocumentation",
|
||||
"app.quit",
|
||||
"editor.reveal",
|
||||
"settings.open",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue