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
|
|
@ -22,6 +22,9 @@ export interface UiCommandSpec {
|
|||
/** The frontend's UI commands. */
|
||||
export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
||||
{ id: "editor.reveal", labelKey: "command.editor.reveal" },
|
||||
{ id: "editor.complete", labelKey: "command.editor.complete", menuPath: "Edit/Complete Code" },
|
||||
{ id: "editor.quickDocumentation", labelKey: "command.editor.quickDocumentation", menuPath: "Edit/Quick Documentation", defaultShortcut: "Mod+I" },
|
||||
{ id: "editor.parameterInfo", labelKey: "command.editor.parameterInfo", menuPath: "Edit/Parameter Info" },
|
||||
{ id: "find.open", labelKey: "command.find.open", menuPath: "View/Find in Files…", defaultShortcut: "Mod+Alt+F" },
|
||||
{ id: "goto.classOpen", labelKey: "command.goto.classOpen", menuPath: "Go/Class…", defaultShortcut: "Mod+Alt+C" },
|
||||
{ id: "goto.fileOpen", labelKey: "command.goto.fileOpen", menuPath: "Go/File…", defaultShortcut: "Mod+P" },
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
* Save, save all and close run through the global keymap and the
|
||||
* palette (`commands/store.ts`): the area supplies their behaviour with the
|
||||
* active buffer as context and says when they can run. It also supplies the
|
||||
* UI command `editor.reveal` (`reveal.ts`).
|
||||
* UI commands `editor.reveal` (`reveal.ts`) and the assist commands
|
||||
* (`assist/commands.ts`).
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
|
|
@ -16,6 +17,7 @@ import ClosePrompt from "./ClosePrompt.vue";
|
|||
import CodeEditor from "./CodeEditor.vue";
|
||||
import EditorTabs from "./EditorTabs.vue";
|
||||
import { reveal, REVEAL_COMMAND } from "./reveal";
|
||||
import * as assist from "./assist/commands";
|
||||
|
||||
const editor = useEditorStore();
|
||||
const commands = useCommandsStore();
|
||||
|
|
@ -31,6 +33,9 @@ onMounted(() => {
|
|||
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
||||
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
||||
commands.provide(REVEAL_COMMAND, { run: (params) => reveal(editor, params) }),
|
||||
commands.provide(assist.COMPLETE_COMMAND, { run: assist.completeAtCursor, enabled: assist.assistEnabled }),
|
||||
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
|
||||
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
|
||||
];
|
||||
});
|
||||
|
||||
|
|
|
|||
127
ui/src/components/editor/assist/commands.ts
Normal file
127
ui/src/components/editor/assist/commands.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
/**
|
||||
* The assist UI commands, so the palette, the keymap, agents and the
|
||||
* control channel reach completion, quick documentation and parameter
|
||||
* info without typing:
|
||||
* - `editor.complete` opens the completion list at the cursor (in the
|
||||
* editor also `Ctrl-Space`, CodeMirror's key).
|
||||
* - `editor.quickDocumentation` shows the hover documentation of the
|
||||
* symbol at the cursor (`Mod+I`); `Escape` or moving on closes it.
|
||||
* - `editor.parameterInfo` shows the signature help (in the editor also
|
||||
* `Mod-Shift-Space`).
|
||||
*
|
||||
* They act on the active PHP editor, which a view plugin of the assist
|
||||
* extensions records ({@link assistTracker}); without one they are
|
||||
* disabled.
|
||||
*/
|
||||
import { startCompletion } from "@codemirror/autocomplete";
|
||||
import { StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip } from "@codemirror/view";
|
||||
import { hoverAt } from "./hover";
|
||||
import { requestSignatureHelp } from "./signature";
|
||||
import type { AssistBuffer, AssistTransport } from "./types";
|
||||
|
||||
/** Command ids. */
|
||||
export const COMPLETE_COMMAND = "editor.complete";
|
||||
/** Command id of quick documentation. */
|
||||
export const QUICK_DOC_COMMAND = "editor.quickDocumentation";
|
||||
/** Command id of parameter info. */
|
||||
export const PARAMETER_INFO_COMMAND = "editor.parameterInfo";
|
||||
|
||||
/** The active PHP editor and what its assist features use. */
|
||||
interface Active {
|
||||
/** The view. */
|
||||
view: EditorView;
|
||||
/** Its buffer. */
|
||||
buffer: AssistBuffer;
|
||||
/** How it reaches the engine. */
|
||||
transport: AssistTransport;
|
||||
}
|
||||
|
||||
/** The active PHP editor, if any. */
|
||||
let active: Active | null = null;
|
||||
|
||||
/** Shows (a tooltip) or clears (null) the quick documentation. */
|
||||
const setQuickDoc = StateEffect.define<Tooltip | null>();
|
||||
|
||||
/** The quick documentation tooltip; closed by any edit or cursor move. */
|
||||
const quickDocField = StateField.define<Tooltip | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setQuickDoc)) {
|
||||
return effect.value;
|
||||
}
|
||||
}
|
||||
return tr.docChanged || tr.selection ? null : value;
|
||||
},
|
||||
provide: (field) => showTooltip.from(field),
|
||||
});
|
||||
|
||||
/**
|
||||
* Records the view as the active PHP editor while it shows a state with
|
||||
* these extensions, and adds the quick documentation tooltip.
|
||||
*
|
||||
* @param buffer - the buffer the state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
export function assistTracker(buffer: AssistBuffer, transport: AssistTransport): Extension {
|
||||
return [
|
||||
quickDocField,
|
||||
ViewPlugin.define((view) => {
|
||||
active = { view, buffer, transport };
|
||||
return {
|
||||
destroy(): void {
|
||||
if (active?.view === view) {
|
||||
active = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}),
|
||||
keymap.of([
|
||||
{
|
||||
key: "Escape",
|
||||
run: (view) => {
|
||||
if (!view.state.field(quickDocField, false)) {
|
||||
return false;
|
||||
}
|
||||
view.dispatch({ effects: setQuickDoc.of(null) });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/** Whether an assist command can run (a PHP editor is active). */
|
||||
export function assistEnabled(): boolean {
|
||||
return active !== null;
|
||||
}
|
||||
|
||||
/** Opens the completion list at the cursor. */
|
||||
export function completeAtCursor(): void {
|
||||
if (active) {
|
||||
active.view.focus();
|
||||
startCompletion(active.view);
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the documentation of the symbol at the cursor. */
|
||||
export async function quickDocumentation(): Promise<void> {
|
||||
const current = active;
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
const { view } = current;
|
||||
const pos = view.state.selection.main.head;
|
||||
const tooltip = await hoverAt(view, pos, current.buffer, current.transport);
|
||||
if (tooltip && view.state.selection.main.head === pos) {
|
||||
view.dispatch({ effects: setQuickDoc.of({ ...tooltip, pos, end: pos }) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the signature help at the cursor. */
|
||||
export function parameterInfo(): void {
|
||||
if (active) {
|
||||
requestSignatureHelp(active.view);
|
||||
}
|
||||
}
|
||||
289
ui/src/components/editor/assist/completion.ts
Normal file
289
ui/src/components/editor/assist/completion.ts
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
/**
|
||||
* Code completion from the language server (`lsp.completion`) as a
|
||||
* CodeMirror completion source.
|
||||
*
|
||||
* Trigger rules (Lutra's own, see {@link completionTrigger}): typing an
|
||||
* identifier, `$`, `->`, `?->`, `::` or a namespace `\` asks the server;
|
||||
* so does the explicit completion shortcut anywhere. Typing inside a
|
||||
* string or comment does not, unless asked explicitly. Typing on filters
|
||||
* the list locally while the server says the list is complete; an
|
||||
* incomplete list is asked for again on every keystroke.
|
||||
*
|
||||
* Applying an item ({@link completionChanges}) uses its `textEdit` when it
|
||||
* has one, else replaces the typed word with `insertText`, and applies the
|
||||
* `additionalTextEdits` (such as a `use` import) in the same transaction.
|
||||
* The server's positions refer to the text at the time of the request;
|
||||
* text typed since then (after the request position) is accounted for.
|
||||
* Positions are lines and UTF-16 columns, which CodeMirror counts the same
|
||||
* way within a line, so CRLF files need no conversion here.
|
||||
*/
|
||||
import type {
|
||||
Completion,
|
||||
CompletionContext,
|
||||
CompletionResult,
|
||||
CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { pickedCompletion } from "@codemirror/autocomplete";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { EditorState, Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { positionOf } from "../engineText";
|
||||
import { renderMarkdown } from "./markdown";
|
||||
import { engineAssistTransport, queryAt } from "./request";
|
||||
import {
|
||||
toCompletionList,
|
||||
type AssistBuffer,
|
||||
type AssistEdit,
|
||||
type AssistTransport,
|
||||
type CompletionItem,
|
||||
} from "./types";
|
||||
|
||||
/** Where a completion starts and what triggered it. */
|
||||
export interface CompletionTrigger {
|
||||
/** How many characters before the cursor the completed word starts. */
|
||||
back: number;
|
||||
/** The trigger character sent to the server, if typing one triggered. */
|
||||
character?: string;
|
||||
}
|
||||
|
||||
/** An identifier (optionally a `$variable`) right before the cursor. */
|
||||
const WORD_BEFORE = /\$?[A-Za-z_\u0080-][\w\u0080-]*$/;
|
||||
|
||||
/** What may follow while the list is filtered locally. */
|
||||
const WORD_CHARS = /^\$?[\w\u0080-]*$/;
|
||||
|
||||
/**
|
||||
* Decides whether the text before the cursor asks for completion.
|
||||
*
|
||||
* @param before - the line's text up to the cursor.
|
||||
* @param explicit - whether the user asked (the completion shortcut).
|
||||
* @returns the trigger, or null for none.
|
||||
*/
|
||||
export function completionTrigger(before: string, explicit: boolean): CompletionTrigger | null {
|
||||
if (/(?:->|::)$/.test(before)) {
|
||||
return { back: 0, character: before.slice(-1) };
|
||||
}
|
||||
if (before.endsWith("$")) {
|
||||
return { back: 1, character: "$" };
|
||||
}
|
||||
if (before.endsWith("\\")) {
|
||||
return { back: 0, character: "\\" };
|
||||
}
|
||||
const word = WORD_BEFORE.exec(before);
|
||||
if (word) {
|
||||
const start = before.length - word[0].length;
|
||||
if (!/[0-9]/.test(before.charAt(start - 1))) {
|
||||
return { back: word[0].length };
|
||||
}
|
||||
return explicit ? { back: 0 } : null;
|
||||
}
|
||||
return explicit ? { back: 0 } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `pos` lies in a string or comment of the parsed document.
|
||||
*
|
||||
* @param state - the editor state.
|
||||
* @param pos - the cursor.
|
||||
*/
|
||||
export function inStringOrComment(state: EditorState, pos: number): boolean {
|
||||
for (let node: { name: string; parent: unknown } | null = syntaxTree(state).resolveInner(pos, -1); node; ) {
|
||||
if (/String|Comment|Heredoc|Nowdoc/.test(node.name)) {
|
||||
return true;
|
||||
}
|
||||
node = node.parent as { name: string; parent: unknown } | null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** One change in document offsets. */
|
||||
export interface DocChange {
|
||||
/** Start. */
|
||||
from: number;
|
||||
/** End. */
|
||||
to: number;
|
||||
/** Inserted text. */
|
||||
insert: string;
|
||||
}
|
||||
|
||||
/** The changes that apply an item, and where the cursor goes. */
|
||||
export interface CompletionPlan {
|
||||
/** Non-overlapping changes in offsets of the current document. */
|
||||
changes: DocChange[];
|
||||
/** The end of the main replacement in the current document, before the changes. */
|
||||
mainEnd: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The changes that apply a completion item.
|
||||
*
|
||||
* @param requestDoc - the document the completion was asked for.
|
||||
* @param requestPos - the cursor then.
|
||||
* @param item - the chosen item.
|
||||
* @param from - where the completed word starts now.
|
||||
* @param to - where it ends now (the cursor).
|
||||
* @param length - the current document's length.
|
||||
*/
|
||||
export function completionChanges(
|
||||
requestDoc: Text,
|
||||
requestPos: number,
|
||||
item: CompletionItem,
|
||||
from: number,
|
||||
to: number,
|
||||
length: number,
|
||||
): CompletionPlan {
|
||||
const typed = Math.max(0, to - requestPos);
|
||||
const clamp = (p: number): number => Math.max(0, Math.min(p, length));
|
||||
const offset = (edit: AssistEdit): [number, number] => {
|
||||
const start = positionOf(requestDoc, edit.range.start.line, edit.range.start.column);
|
||||
const end = Math.max(start, positionOf(requestDoc, edit.range.end.line, edit.range.end.column));
|
||||
return [start, end];
|
||||
};
|
||||
let main: DocChange;
|
||||
let mainRange: [number, number];
|
||||
if (item.textEdit) {
|
||||
const [start, end] = offset(item.textEdit);
|
||||
mainRange = [start, end];
|
||||
const mainFrom = start <= requestPos ? start : start + typed;
|
||||
const mainTo = end < requestPos ? end : end + typed;
|
||||
main = { from: clamp(mainFrom), to: clamp(Math.max(mainFrom, mainTo)), insert: item.textEdit.newText };
|
||||
} else {
|
||||
mainRange = [Math.min(from, requestPos), requestPos];
|
||||
main = { from: clamp(from), to: clamp(Math.max(from, to)), insert: item.insertText };
|
||||
}
|
||||
const changes: DocChange[] = [main];
|
||||
const taken: [number, number][] = [mainRange];
|
||||
for (const edit of item.additionalTextEdits ?? []) {
|
||||
const [start, end] = offset(edit);
|
||||
const overlaps = taken.some(([a, b]) => start < b && end > a) || taken.some(([a, b]) => start === end && start > a && start < b);
|
||||
if (overlaps) {
|
||||
continue;
|
||||
}
|
||||
taken.push([start, end]);
|
||||
const shift = (p: number): number => (p < requestPos ? p : p + typed);
|
||||
changes.push({ from: clamp(shift(start)), to: clamp(shift(end)), insert: edit.newText });
|
||||
}
|
||||
return { changes, mainEnd: main.to };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a completion item to a view.
|
||||
*
|
||||
* @param view - the editor view.
|
||||
* @param completion - the CodeMirror option (for `pickedCompletion`).
|
||||
* @param item - the item.
|
||||
* @param requestDoc - the document the completion was asked for.
|
||||
* @param requestPos - the cursor then.
|
||||
* @param from - start of the completed word now.
|
||||
* @param to - its end now.
|
||||
*/
|
||||
export function applyCompletion(
|
||||
view: EditorView,
|
||||
completion: Completion,
|
||||
item: CompletionItem,
|
||||
requestDoc: Text,
|
||||
requestPos: number,
|
||||
from: number,
|
||||
to: number,
|
||||
): void {
|
||||
const plan = completionChanges(requestDoc, requestPos, item, from, to, view.state.doc.length);
|
||||
const changes = view.state.changes(plan.changes);
|
||||
view.dispatch({
|
||||
changes,
|
||||
selection: { anchor: changes.mapPos(plan.mainEnd, 1) },
|
||||
scrollIntoView: true,
|
||||
userEvent: "input.complete",
|
||||
annotations: pickedCompletion.of(completion),
|
||||
});
|
||||
}
|
||||
|
||||
/** The items behind the CodeMirror options, for icons and classes. */
|
||||
export const itemOf = new WeakMap<Completion, CompletionItem>();
|
||||
|
||||
/**
|
||||
* Builds the documentation panel of an item.
|
||||
*
|
||||
* @param item - the item.
|
||||
* @returns a node, or null without documentation.
|
||||
*/
|
||||
export function infoOf(item: CompletionItem): HTMLElement | null {
|
||||
if (item.documentation === undefined) {
|
||||
return null;
|
||||
}
|
||||
const dom = renderMarkdown(item.documentation);
|
||||
dom.classList.add("lt-assist-info");
|
||||
return dom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the server's items into CodeMirror options. The server's order
|
||||
* becomes the boost, so it decides among equally good matches.
|
||||
*
|
||||
* @param items - the items, best first.
|
||||
* @param requestDoc - the document they were asked for.
|
||||
* @param requestPos - the cursor then.
|
||||
*/
|
||||
export function toOptions(items: readonly CompletionItem[], requestDoc: Text, requestPos: number): Completion[] {
|
||||
return items.map((item, index) => {
|
||||
const option: Completion = {
|
||||
label: item.label,
|
||||
type: item.kind,
|
||||
boost: items.length > 1 ? Math.round(99 - (198 * index) / (items.length - 1)) : 0,
|
||||
apply: (view, completion, from, to) => {
|
||||
applyCompletion(view, completion, item, requestDoc, requestPos, from, to);
|
||||
},
|
||||
};
|
||||
if (item.detail !== undefined) {
|
||||
option.detail = item.detail;
|
||||
}
|
||||
if (item.documentation !== undefined) {
|
||||
option.info = () => infoOf(item);
|
||||
}
|
||||
itemOf.set(option, item);
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The completion source for one buffer.
|
||||
*
|
||||
* @param buffer - the buffer the editor state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
export function lspCompletionSource(
|
||||
buffer: AssistBuffer,
|
||||
transport: AssistTransport = engineAssistTransport,
|
||||
): CompletionSource {
|
||||
return async (context: CompletionContext): Promise<CompletionResult | null> => {
|
||||
const line = context.state.doc.lineAt(context.pos);
|
||||
const trigger = completionTrigger(line.text.slice(0, context.pos - line.from), context.explicit);
|
||||
if (!trigger || (!context.explicit && inStringOrComment(context.state, context.pos))) {
|
||||
return null;
|
||||
}
|
||||
const doc = context.state.doc;
|
||||
const value = await queryAt({
|
||||
buffer,
|
||||
transport,
|
||||
doc,
|
||||
current: () => context.view?.state.doc ?? doc,
|
||||
pos: context.pos,
|
||||
command: "lsp.completion",
|
||||
extra: trigger.character === undefined ? {} : { triggerCharacter: trigger.character },
|
||||
});
|
||||
if (context.aborted || value === null) {
|
||||
return null;
|
||||
}
|
||||
const list = toCompletionList(value);
|
||||
if (list.items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const result: CompletionResult = {
|
||||
from: context.pos - trigger.back,
|
||||
options: toOptions(list.items, doc, context.pos),
|
||||
};
|
||||
if (!list.incomplete) {
|
||||
result.validFor = WORD_CHARS;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
69
ui/src/components/editor/assist/hover.ts
Normal file
69
ui/src/components/editor/assist/hover.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
/**
|
||||
* Hover documentation from the language server (`lsp.hover`): resting the
|
||||
* pointer on a symbol shows its Markdown documentation, rendered safely
|
||||
* ({@link renderMarkdown}), in a tooltip above it.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { hoverTooltip, type EditorView, type Tooltip } from "@codemirror/view";
|
||||
import { positionOf } from "../engineText";
|
||||
import { renderMarkdown } from "./markdown";
|
||||
import { engineAssistTransport, queryAt } from "./request";
|
||||
import { toHover, type AssistBuffer, type AssistTransport } from "./types";
|
||||
|
||||
/** Milliseconds the pointer rests before the hover is asked for. */
|
||||
export const HOVER_DELAY = 350;
|
||||
|
||||
/**
|
||||
* Asks for the hover at `pos` and builds its tooltip.
|
||||
*
|
||||
* @param view - the editor view.
|
||||
* @param pos - the hovered offset.
|
||||
* @param buffer - the buffer the view shows.
|
||||
* @param transport - how to reach the engine.
|
||||
* @returns the tooltip, or null when there is nothing to show.
|
||||
*/
|
||||
export async function hoverAt(
|
||||
view: EditorView,
|
||||
pos: number,
|
||||
buffer: AssistBuffer,
|
||||
transport: AssistTransport = engineAssistTransport,
|
||||
): Promise<Tooltip | null> {
|
||||
const doc = view.state.doc;
|
||||
const value = await queryAt({
|
||||
buffer,
|
||||
transport,
|
||||
doc,
|
||||
current: () => view.state.doc,
|
||||
pos,
|
||||
command: "lsp.hover",
|
||||
});
|
||||
const hover = toHover(value);
|
||||
if (!hover) {
|
||||
return null;
|
||||
}
|
||||
const start = hover.range ? positionOf(doc, hover.range.start.line, hover.range.start.column) : pos;
|
||||
const end = hover.range ? positionOf(doc, hover.range.end.line, hover.range.end.column) : pos;
|
||||
return {
|
||||
pos: Math.min(start, pos),
|
||||
end: Math.max(end, pos),
|
||||
above: true,
|
||||
create: () => {
|
||||
const dom = renderMarkdown(hover.contents, view.dom.ownerDocument);
|
||||
dom.classList.add("lt-assist-hover");
|
||||
return { dom };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The hover extension for one buffer.
|
||||
*
|
||||
* @param buffer - the buffer the editor state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
export function lspHover(buffer: AssistBuffer, transport: AssistTransport = engineAssistTransport): Extension {
|
||||
return hoverTooltip((view, pos) => hoverAt(view, pos, buffer, transport), {
|
||||
hoverTime: HOVER_DELAY,
|
||||
hideOnChange: true,
|
||||
});
|
||||
}
|
||||
104
ui/src/components/editor/assist/icons.ts
Normal file
104
ui/src/components/editor/assist/icons.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
/**
|
||||
* Lucide icons (ISC) for completion item kinds, rendered into plain DOM
|
||||
* nodes for CodeMirror's completion list. The icon has the kind's catalog
|
||||
* name as its tooltip; its colour is the list's text colour.
|
||||
*/
|
||||
import {
|
||||
Box,
|
||||
Braces,
|
||||
Code,
|
||||
Component,
|
||||
File,
|
||||
Folder,
|
||||
Hash,
|
||||
KeyRound,
|
||||
Link,
|
||||
ListOrdered,
|
||||
Package,
|
||||
Palette,
|
||||
Ruler,
|
||||
Scissors,
|
||||
SquareDot,
|
||||
SquareFunction,
|
||||
Text,
|
||||
Type,
|
||||
Variable,
|
||||
Zap,
|
||||
} from "@lucide/vue";
|
||||
import { h, render, type Component as VueComponent } from "vue";
|
||||
import { t } from "../../../i18n";
|
||||
import type { CompletionKind } from "./types";
|
||||
|
||||
/** The icon of each kind. */
|
||||
export const KIND_ICONS: Readonly<Record<CompletionKind, VueComponent>> = {
|
||||
text: Text,
|
||||
method: SquareFunction,
|
||||
function: SquareFunction,
|
||||
constructor: SquareFunction,
|
||||
field: SquareDot,
|
||||
variable: Variable,
|
||||
class: Box,
|
||||
interface: Component,
|
||||
module: Package,
|
||||
property: SquareDot,
|
||||
unit: Ruler,
|
||||
value: Hash,
|
||||
enum: ListOrdered,
|
||||
keyword: KeyRound,
|
||||
snippet: Scissors,
|
||||
color: Palette,
|
||||
file: File,
|
||||
reference: Link,
|
||||
folder: Folder,
|
||||
enumMember: ListOrdered,
|
||||
constant: Hash,
|
||||
struct: Braces,
|
||||
event: Zap,
|
||||
operator: Code,
|
||||
typeParameter: Type,
|
||||
};
|
||||
|
||||
/** The catalog name of each kind, shown as the icon's tooltip. */
|
||||
export const KIND_LABELS: Readonly<Record<CompletionKind, () => string>> = {
|
||||
text: () => t("editor.assist.kind.text"),
|
||||
method: () => t("editor.assist.kind.method"),
|
||||
function: () => t("editor.assist.kind.function"),
|
||||
constructor: () => t("editor.assist.kind.constructor"),
|
||||
field: () => t("editor.assist.kind.field"),
|
||||
variable: () => t("editor.assist.kind.variable"),
|
||||
class: () => t("editor.assist.kind.class"),
|
||||
interface: () => t("editor.assist.kind.interface"),
|
||||
module: () => t("editor.assist.kind.module"),
|
||||
property: () => t("editor.assist.kind.property"),
|
||||
unit: () => t("editor.assist.kind.unit"),
|
||||
value: () => t("editor.assist.kind.value"),
|
||||
enum: () => t("editor.assist.kind.enum"),
|
||||
keyword: () => t("editor.assist.kind.keyword"),
|
||||
snippet: () => t("editor.assist.kind.snippet"),
|
||||
color: () => t("editor.assist.kind.color"),
|
||||
file: () => t("editor.assist.kind.file"),
|
||||
reference: () => t("editor.assist.kind.reference"),
|
||||
folder: () => t("editor.assist.kind.folder"),
|
||||
enumMember: () => t("editor.assist.kind.enumMember"),
|
||||
constant: () => t("editor.assist.kind.constant"),
|
||||
struct: () => t("editor.assist.kind.struct"),
|
||||
event: () => t("editor.assist.kind.event"),
|
||||
operator: () => t("editor.assist.kind.operator"),
|
||||
typeParameter: () => t("editor.assist.kind.typeParameter"),
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the icon of a kind.
|
||||
*
|
||||
* @param kind - the kind; unknown kinds get the `text` icon.
|
||||
* @param owner - the document that creates the node.
|
||||
* @returns a `span.lt-assist-kind` with the SVG inside.
|
||||
*/
|
||||
export function kindIcon(kind: string, owner: Document = document): HTMLElement {
|
||||
const known = Object.hasOwn(KIND_ICONS, kind) ? (kind as CompletionKind) : "text";
|
||||
const span = owner.createElement("span");
|
||||
span.className = `lt-assist-kind lt-assist-kind-${known}`;
|
||||
span.title = KIND_LABELS[known]();
|
||||
render(h(KIND_ICONS[known], { size: 14, "aria-hidden": "true" }), span);
|
||||
return span;
|
||||
}
|
||||
153
ui/src/components/editor/assist/index.ts
Normal file
153
ui/src/components/editor/assist/index.ts
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
/**
|
||||
* Code assistance in the editor (M3.4): completion, hover documentation
|
||||
* and signature help from the PHP language server, through the engine's
|
||||
* `lsp.completion`, `lsp.hover` and `lsp.signatureHelp` (pending
|
||||
* queries, see `request.ts`).
|
||||
*
|
||||
* {@link assistExtensions} is the hook the editor uses: PHP files of a
|
||||
* buffer get the extensions, everything else none. Colours come from
|
||||
* `--lt-*` tokens only; strings from the catalog.
|
||||
*/
|
||||
import { autocompletion } from "@codemirror/autocomplete";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { languageOf } from "../language";
|
||||
import { assistTracker } from "./commands";
|
||||
import { itemOf, lspCompletionSource } from "./completion";
|
||||
import { lspHover } from "./hover";
|
||||
import { kindIcon } from "./icons";
|
||||
import { engineAssistTransport } from "./request";
|
||||
import { lspSignatureHelp } from "./signature";
|
||||
import type { AssistBuffer, AssistTransport } from "./types";
|
||||
|
||||
export type { AssistBuffer } from "./types";
|
||||
|
||||
/** Markdown and tooltip styles from tokens. */
|
||||
const assistTheme: Extension = EditorView.theme({
|
||||
".cm-tooltip.cm-tooltip-autocomplete > ul": {
|
||||
fontFamily: "var(--lt-font-mono)",
|
||||
maxHeight: "16em",
|
||||
},
|
||||
".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "6px",
|
||||
padding: "1px 8px 1px 4px",
|
||||
},
|
||||
".cm-tooltip-autocomplete ul li[aria-selected]": {
|
||||
backgroundColor: "var(--lt-editor-selection-bg)",
|
||||
color: "var(--lt-fg)",
|
||||
},
|
||||
".cm-completionMatchedText": {
|
||||
textDecoration: "none",
|
||||
fontWeight: "600",
|
||||
color: "var(--lt-accent)",
|
||||
},
|
||||
".cm-completionDetail": {
|
||||
marginLeft: "auto",
|
||||
paddingLeft: "16px",
|
||||
fontStyle: "normal",
|
||||
color: "var(--lt-fg-muted)",
|
||||
},
|
||||
".lt-assist-kind": {
|
||||
display: "inline-flex",
|
||||
flex: "none",
|
||||
color: "var(--lt-fg-muted)",
|
||||
},
|
||||
".lt-assist-deprecated .cm-completionLabel": {
|
||||
textDecoration: "line-through",
|
||||
},
|
||||
".cm-tooltip.cm-completionInfo": {
|
||||
maxWidth: "480px",
|
||||
padding: "4px 8px",
|
||||
},
|
||||
".cm-tooltip-hover": {
|
||||
maxWidth: "640px",
|
||||
},
|
||||
".lt-markdown": {
|
||||
padding: "4px 8px",
|
||||
maxHeight: "320px",
|
||||
overflow: "auto",
|
||||
lineHeight: "1.45",
|
||||
color: "var(--lt-fg)",
|
||||
},
|
||||
".lt-markdown p, .lt-markdown ul, .lt-markdown ol, .lt-markdown blockquote": {
|
||||
margin: "4px 0",
|
||||
},
|
||||
".lt-markdown ul, .lt-markdown ol": {
|
||||
paddingLeft: "20px",
|
||||
},
|
||||
".lt-markdown pre": {
|
||||
margin: "4px 0",
|
||||
padding: "4px 6px",
|
||||
whiteSpace: "pre-wrap",
|
||||
backgroundColor: "var(--lt-editor-bg)",
|
||||
border: "1px solid var(--lt-border)",
|
||||
fontFamily: "var(--lt-font-mono)",
|
||||
},
|
||||
".lt-markdown code": {
|
||||
fontFamily: "var(--lt-font-mono)",
|
||||
},
|
||||
".lt-markdown hr": {
|
||||
border: "none",
|
||||
borderTop: "1px solid var(--lt-border)",
|
||||
margin: "6px 0",
|
||||
},
|
||||
".lt-markdown blockquote": {
|
||||
paddingLeft: "8px",
|
||||
borderLeft: "3px solid var(--lt-border)",
|
||||
color: "var(--lt-fg-muted)",
|
||||
},
|
||||
".lt-markdown-link": {
|
||||
color: "var(--lt-accent)",
|
||||
},
|
||||
".lt-assist-signature": {
|
||||
maxWidth: "640px",
|
||||
padding: "2px 0",
|
||||
},
|
||||
".lt-assist-signature-label": {
|
||||
padding: "2px 8px",
|
||||
fontFamily: "var(--lt-font-mono)",
|
||||
},
|
||||
".lt-assist-signature-active": {
|
||||
fontWeight: "700",
|
||||
color: "var(--lt-accent)",
|
||||
},
|
||||
".lt-assist-signature-count": {
|
||||
marginRight: "8px",
|
||||
color: "var(--lt-fg-muted)",
|
||||
},
|
||||
".lt-assist-signature-doc": {
|
||||
borderTop: "1px solid var(--lt-border)",
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The assist extensions of an editor state.
|
||||
*
|
||||
* @param path - project-relative path of the file.
|
||||
* @param buffer - the buffer it shows; none for states without one.
|
||||
* @param transport - how to reach the engine.
|
||||
* @returns the extensions; empty unless a PHP file of a buffer.
|
||||
*/
|
||||
export function assistExtensions(
|
||||
path: string,
|
||||
buffer: AssistBuffer | undefined,
|
||||
transport: AssistTransport = engineAssistTransport,
|
||||
): Extension {
|
||||
if (!buffer || languageOf(path) !== "php") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
autocompletion({
|
||||
override: [lspCompletionSource(buffer, transport)],
|
||||
icons: false,
|
||||
addToOptions: [{ render: (completion) => kindIcon(completion.type ?? "text"), position: 20 }],
|
||||
optionClass: (completion) => (itemOf.get(completion)?.deprecated === true ? "lt-assist-deprecated" : ""),
|
||||
}),
|
||||
lspHover(buffer, transport),
|
||||
lspSignatureHelp(buffer, transport),
|
||||
assistTracker(buffer, transport),
|
||||
assistTheme,
|
||||
];
|
||||
}
|
||||
292
ui/src/components/editor/assist/markdown.ts
Normal file
292
ui/src/components/editor/assist/markdown.ts
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
/**
|
||||
* A small, safe Markdown renderer for language server documentation
|
||||
* (hover, completion details, signature help).
|
||||
*
|
||||
* Safety: the renderer never parses HTML. It builds DOM nodes with
|
||||
* `createElement` and `textContent` only, from a fixed set of elements
|
||||
* (`p`, `pre`, `code`, `strong`, `em`, `ul`, `ol`, `li`, `hr`,
|
||||
* `blockquote`, `span`). HTML in the source shows as text; links and
|
||||
* images show their text only (no `href`, no `src`), so nothing in a
|
||||
* server answer can run script, load a resource or navigate the window.
|
||||
*
|
||||
* Supported: fenced code blocks (``` and ~~~), ATX headings (shown as
|
||||
* bold paragraphs), thematic breaks, bullet and numbered lists (flat),
|
||||
* block quotes, paragraphs with hard breaks, and inline code, strong,
|
||||
* emphasis, links, images and backslash escapes. That covers what
|
||||
* Phpactor writes. Styling comes from `--lt-*` tokens in the assist theme.
|
||||
*/
|
||||
|
||||
/** Longest source rendered; the rest is cut. */
|
||||
export const MAX_MARKDOWN = 64 * 1024;
|
||||
|
||||
/** Deepest nesting of inline emphasis followed. */
|
||||
const MAX_DEPTH = 8;
|
||||
|
||||
/** ASCII punctuation a backslash can escape (CommonMark). */
|
||||
const ESCAPABLE = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
|
||||
|
||||
/** A thematic break line. */
|
||||
const RULE = /^ {0,3}([-*_])(?: *\1){2,} *$/;
|
||||
|
||||
/** An ATX heading line. */
|
||||
const HEADING = /^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/;
|
||||
|
||||
/** The opening line of a fenced code block. */
|
||||
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^`\s]*)/;
|
||||
|
||||
/** A list item line. */
|
||||
const LIST_ITEM = /^\s{0,3}([-*+]|\d{1,9}[.)])\s+(.*)$/;
|
||||
|
||||
/** A block quote line. */
|
||||
const QUOTE = /^ {0,3}> ?(.*)$/;
|
||||
|
||||
/**
|
||||
* Renders Markdown into a detached element.
|
||||
*
|
||||
* @param source - the Markdown text (untrusted).
|
||||
* @param owner - the document that creates the nodes.
|
||||
* @returns a `div.lt-markdown` with the rendered blocks.
|
||||
*/
|
||||
export function renderMarkdown(source: string, owner: Document = document): HTMLElement {
|
||||
const root = owner.createElement("div");
|
||||
root.className = "lt-markdown";
|
||||
const lines = source.slice(0, MAX_MARKDOWN).split(/\r\n|\r|\n/);
|
||||
let paragraph: string[] = [];
|
||||
let list: HTMLElement | null = null;
|
||||
const flushParagraph = (): void => {
|
||||
if (paragraph.length > 0) {
|
||||
const p = owner.createElement("p");
|
||||
appendLines(p, paragraph, owner);
|
||||
root.append(p);
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const endBlocks = (): void => {
|
||||
flushParagraph();
|
||||
list = null;
|
||||
};
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i] ?? "";
|
||||
const fence = FENCE.exec(line);
|
||||
if (fence) {
|
||||
endBlocks();
|
||||
const marker = fence[1] ?? "```";
|
||||
const code: string[] = [];
|
||||
i += 1;
|
||||
while (i < lines.length && !(lines[i] ?? "").trimStart().startsWith(marker)) {
|
||||
code.push(lines[i] ?? "");
|
||||
i += 1;
|
||||
}
|
||||
const pre = owner.createElement("pre");
|
||||
const element = owner.createElement("code");
|
||||
const language = fence[2] ?? "";
|
||||
if (/^[\w+-]{1,32}$/.test(language)) {
|
||||
element.dataset.language = language;
|
||||
}
|
||||
element.textContent = code.join("\n");
|
||||
pre.append(element);
|
||||
root.append(pre);
|
||||
continue;
|
||||
}
|
||||
if (line.trim() === "") {
|
||||
endBlocks();
|
||||
continue;
|
||||
}
|
||||
if (RULE.test(line)) {
|
||||
endBlocks();
|
||||
root.append(owner.createElement("hr"));
|
||||
continue;
|
||||
}
|
||||
const heading = HEADING.exec(line);
|
||||
if (heading) {
|
||||
endBlocks();
|
||||
const p = owner.createElement("p");
|
||||
p.className = "lt-markdown-heading";
|
||||
const strong = owner.createElement("strong");
|
||||
appendInline(strong, heading[2] ?? "", owner, 0);
|
||||
p.append(strong);
|
||||
root.append(p);
|
||||
continue;
|
||||
}
|
||||
const item = LIST_ITEM.exec(line);
|
||||
if (item) {
|
||||
flushParagraph();
|
||||
const ordered = /\d/.test(item[1] ?? "");
|
||||
const tag = ordered ? "OL" : "UL";
|
||||
if (!list || list.tagName !== tag) {
|
||||
list = owner.createElement(ordered ? "ol" : "ul");
|
||||
root.append(list);
|
||||
}
|
||||
const li = owner.createElement("li");
|
||||
appendInline(li, item[2] ?? "", owner, 0);
|
||||
list.append(li);
|
||||
continue;
|
||||
}
|
||||
const quote = QUOTE.exec(line);
|
||||
if (quote) {
|
||||
endBlocks();
|
||||
const block = owner.createElement("blockquote");
|
||||
appendInline(block, quote[1] ?? "", owner, 0);
|
||||
root.append(block);
|
||||
continue;
|
||||
}
|
||||
if (list && /^\s{2,}\S/.test(line) && list.lastElementChild) {
|
||||
list.lastElementChild.append(owner.createTextNode(" "));
|
||||
appendInline(list.lastElementChild as HTMLElement, line.trim(), owner, 0);
|
||||
continue;
|
||||
}
|
||||
list = null;
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the lines of one paragraph: joined with spaces, with a line
|
||||
* break where a line ends in two spaces or a backslash.
|
||||
*/
|
||||
function appendLines(parent: HTMLElement, lines: readonly string[], owner: Document): void {
|
||||
lines.forEach((raw, index) => {
|
||||
const hard = / {2,}$/.test(raw) || (raw.endsWith("\\") && !raw.endsWith("\\\\"));
|
||||
const text = hard ? raw.replace(/ +$/, "").replace(/\\$/, "") : raw;
|
||||
appendInline(parent, index === 0 ? text.trimStart() : text.trim(), owner, 0);
|
||||
if (index < lines.length - 1) {
|
||||
parent.append(hard ? owner.createElement("br") : owner.createTextNode(" "));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends inline Markdown as nodes.
|
||||
*
|
||||
* @param parent - the element that receives the nodes.
|
||||
* @param text - one block's inline source.
|
||||
* @param owner - the document that creates the nodes.
|
||||
* @param depth - the current emphasis nesting.
|
||||
*/
|
||||
function appendInline(parent: HTMLElement, text: string, owner: Document, depth: number): void {
|
||||
let plain = "";
|
||||
const flush = (): void => {
|
||||
if (plain !== "") {
|
||||
parent.append(owner.createTextNode(plain));
|
||||
plain = "";
|
||||
}
|
||||
};
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const c = text.charAt(i);
|
||||
const next = text.charAt(i + 1);
|
||||
if (c === "\\" && next !== "" && ESCAPABLE.includes(next)) {
|
||||
plain += next;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c === "`") {
|
||||
const run = /^`+/.exec(text.slice(i))?.[0] ?? "`";
|
||||
const close = text.indexOf(run, i + run.length);
|
||||
if (close > 0) {
|
||||
flush();
|
||||
const code = owner.createElement("code");
|
||||
code.textContent = text.slice(i + run.length, close).replace(/^ (.*) $/, "$1");
|
||||
parent.append(code);
|
||||
i = close + run.length;
|
||||
continue;
|
||||
}
|
||||
plain += run;
|
||||
i += run.length;
|
||||
continue;
|
||||
}
|
||||
if ((c === "*" || c === "_") && depth < MAX_DEPTH) {
|
||||
const before = text.charAt(i - 1);
|
||||
const opens = c === "*" || !/[\p{L}\p{N}]/u.test(before);
|
||||
const strong = next === c;
|
||||
const marker = strong ? c + c : c;
|
||||
const close = opens ? findClose(text, marker, i + marker.length) : -1;
|
||||
if (close > i + marker.length) {
|
||||
flush();
|
||||
const element = owner.createElement(strong ? "strong" : "em");
|
||||
appendInline(element, text.slice(i + marker.length, close), owner, depth + 1);
|
||||
parent.append(element);
|
||||
i = close + marker.length;
|
||||
continue;
|
||||
}
|
||||
plain += marker;
|
||||
i += marker.length;
|
||||
continue;
|
||||
}
|
||||
if (c === "[" || (c === "!" && next === "[")) {
|
||||
const start = c === "!" ? i + 1 : i;
|
||||
const link = matchLink(text, start);
|
||||
if (link && depth < MAX_DEPTH) {
|
||||
flush();
|
||||
const span = owner.createElement("span");
|
||||
span.className = "lt-markdown-link";
|
||||
appendInline(span, link.label, owner, depth + 1);
|
||||
parent.append(span);
|
||||
i = link.end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (c === "<") {
|
||||
const auto = /^<((?:https?|mailto):[^\s<>]*)>/i.exec(text.slice(i));
|
||||
if (auto) {
|
||||
plain += auto[1] ?? "";
|
||||
i += auto[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
plain += c;
|
||||
i += 1;
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the closing emphasis marker: the next `marker` after `from` that
|
||||
* is not escaped and not preceded by whitespace.
|
||||
*
|
||||
* @returns its index, or -1.
|
||||
*/
|
||||
function findClose(text: string, marker: string, from: number): number {
|
||||
let at = text.indexOf(marker, from);
|
||||
while (at >= 0) {
|
||||
const before = text.charAt(at - 1);
|
||||
const doubled = marker.length === 1 && text.charAt(at + 1) === marker;
|
||||
if (before !== "\\" && !/\s/.test(before) && !doubled) {
|
||||
return at;
|
||||
}
|
||||
at = text.indexOf(marker, at + (doubled ? 2 : 1));
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches `[label](target)` at `start`.
|
||||
*
|
||||
* @returns the label and the index after the link, or null.
|
||||
*/
|
||||
function matchLink(text: string, start: number): { label: string; end: number } | null {
|
||||
let depth = 0;
|
||||
for (let i = start; i < text.length; i += 1) {
|
||||
const c = text.charAt(i);
|
||||
if (c === "\\") {
|
||||
i += 1;
|
||||
} else if (c === "[") {
|
||||
depth += 1;
|
||||
} else if (c === "]") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
if (text.charAt(i + 1) !== "(") {
|
||||
return null;
|
||||
}
|
||||
const close = text.indexOf(")", i + 2);
|
||||
if (close < 0) {
|
||||
return null;
|
||||
}
|
||||
return { label: text.slice(start + 1, i), end: close + 1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
73
ui/src/components/editor/assist/request.ts
Normal file
73
ui/src/components/editor/assist/request.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/**
|
||||
* Sending an assist query for a position of an editor state.
|
||||
*
|
||||
* Positions must refer to the text the engine has. The local document can
|
||||
* be ahead of it while the buffer sync has edits in flight, so a query
|
||||
* first waits until the sync is idle and then checks that the document is
|
||||
* still the one the position belongs to; if the user typed meanwhile, the
|
||||
* query is dropped (the editor asks again for the new text).
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import { runWaiting, type JsonValue } from "../../../ipc";
|
||||
import type { AssistBuffer, AssistPosition, AssistTransport } from "./types";
|
||||
|
||||
/**
|
||||
* The transport through the engine IPC: `runWaiting` waits for the
|
||||
* language server on a worker thread of the shell and without the engine
|
||||
* lock, so a slow server never blocks the window or the engine.
|
||||
*/
|
||||
export const engineAssistTransport: AssistTransport = {
|
||||
query: (command, params) => runWaiting<unknown>(command, params),
|
||||
};
|
||||
|
||||
/**
|
||||
* The engine position of a document offset: 0-based line and UTF-16
|
||||
* column, which is what CodeMirror counts within a line. CRLF files have
|
||||
* the same lines and columns in the engine.
|
||||
*
|
||||
* @param doc - the document.
|
||||
* @param pos - an offset in it.
|
||||
*/
|
||||
export function positionAt(doc: Text, pos: number): AssistPosition {
|
||||
const line = doc.lineAt(Math.max(0, Math.min(pos, doc.length)));
|
||||
return { line: line.number - 1, column: Math.max(0, Math.min(pos, doc.length)) - line.from };
|
||||
}
|
||||
|
||||
/** What one query needs. */
|
||||
export interface QueryRequest {
|
||||
/** The buffer. */
|
||||
buffer: AssistBuffer;
|
||||
/** How to reach the engine. */
|
||||
transport: AssistTransport;
|
||||
/** The document the position refers to. */
|
||||
doc: Text;
|
||||
/** The current document, read after the sync is idle. */
|
||||
current: () => Text;
|
||||
/** The offset. */
|
||||
pos: number;
|
||||
/** The command id. */
|
||||
command: string;
|
||||
/** More params next to `id` and `position`. */
|
||||
extra?: Record<string, JsonValue>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs an assist query once the engine has the document.
|
||||
*
|
||||
* @returns the untrusted result, or null when the document moved on, the
|
||||
* query failed (no language server, a timeout) or nothing was found.
|
||||
* Failures are not shown: assistance is best effort while typing.
|
||||
*/
|
||||
export async function queryAt(request: QueryRequest): Promise<unknown> {
|
||||
await request.buffer.idle();
|
||||
if (request.current() !== request.doc) {
|
||||
return null;
|
||||
}
|
||||
const position = positionAt(request.doc, request.pos);
|
||||
const result = await request.transport.query(request.command, {
|
||||
id: request.buffer.id,
|
||||
position: { line: position.line, column: position.column },
|
||||
...request.extra,
|
||||
});
|
||||
return result.ok ? result.value : null;
|
||||
}
|
||||
270
ui/src/components/editor/assist/signature.ts
Normal file
270
ui/src/components/editor/assist/signature.ts
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
/**
|
||||
* Signature help (`lsp.signatureHelp`) while typing call arguments.
|
||||
*
|
||||
* Typing `(` or `,` asks the server for the signatures of the call around
|
||||
* the cursor; while the tooltip is open, every edit and cursor move asks
|
||||
* again (debounced), so the highlighted parameter follows the cursor and
|
||||
* the tooltip closes when the cursor leaves the call (the server returns
|
||||
* no signatures). `Escape` closes it, `Mod-Shift-Space` opens it on
|
||||
* demand. The tooltip shows the active signature with its active
|
||||
* parameter highlighted, a counter when there are several, and the
|
||||
* parameter's and the signature's documentation as safe Markdown.
|
||||
*/
|
||||
import { StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import {
|
||||
EditorView,
|
||||
ViewPlugin,
|
||||
keymap,
|
||||
showTooltip,
|
||||
type PluginValue,
|
||||
type Tooltip,
|
||||
type ViewUpdate,
|
||||
} from "@codemirror/view";
|
||||
import { t } from "../../../i18n";
|
||||
import { renderMarkdown } from "./markdown";
|
||||
import { engineAssistTransport, queryAt } from "./request";
|
||||
import { toSignatureHelp, type AssistBuffer, type AssistTransport, type SignatureHelpResult } from "./types";
|
||||
|
||||
/** Milliseconds between a cursor move or edit and the follow-up request. */
|
||||
export const SIGNATURE_DEBOUNCE = 120;
|
||||
|
||||
/** What the tooltip shows, anchored at `pos`. */
|
||||
export interface SignatureState {
|
||||
/** Where the tooltip is anchored (the cursor when it was asked for). */
|
||||
pos: number;
|
||||
/** The signatures. */
|
||||
help: SignatureHelpResult;
|
||||
}
|
||||
|
||||
/** Sets or clears (null) the shown signature help. */
|
||||
export const setSignature = StateEffect.define<SignatureState | null>();
|
||||
|
||||
/** The shown signature help, mapped through edits. */
|
||||
export const signatureField = StateField.define<SignatureState | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setSignature)) {
|
||||
return effect.value;
|
||||
}
|
||||
}
|
||||
if (value && tr.docChanged) {
|
||||
return { pos: tr.changes.mapPos(value.pos), help: value.help };
|
||||
}
|
||||
return value;
|
||||
},
|
||||
provide: (field) =>
|
||||
showTooltip.from(field, (value): Tooltip | null =>
|
||||
value
|
||||
? {
|
||||
pos: value.pos,
|
||||
above: true,
|
||||
create: (view) => ({ dom: renderSignature(value.help, view.dom.ownerDocument) }),
|
||||
}
|
||||
: null,
|
||||
),
|
||||
});
|
||||
|
||||
/**
|
||||
* Renders signature help.
|
||||
*
|
||||
* @param help - the signatures.
|
||||
* @param owner - the document that creates the nodes.
|
||||
* @returns a `div.lt-assist-signature`.
|
||||
*/
|
||||
export function renderSignature(help: SignatureHelpResult, owner: Document = document): HTMLElement {
|
||||
const root = owner.createElement("div");
|
||||
root.className = "lt-assist-signature";
|
||||
const signature = help.signatures[help.activeSignature] ?? help.signatures[0];
|
||||
if (!signature) {
|
||||
return root;
|
||||
}
|
||||
const head = owner.createElement("div");
|
||||
head.className = "lt-assist-signature-label";
|
||||
const active = signature.activeParameter ?? help.activeParameter;
|
||||
const span = signature.parameters[active]?.label ?? null;
|
||||
if (span) {
|
||||
const [from, to] = span;
|
||||
const mark = owner.createElement("span");
|
||||
mark.className = "lt-assist-signature-active";
|
||||
mark.textContent = signature.label.slice(from, to);
|
||||
head.append(owner.createTextNode(signature.label.slice(0, from)), mark, owner.createTextNode(signature.label.slice(to)));
|
||||
} else {
|
||||
head.textContent = signature.label;
|
||||
}
|
||||
if (help.signatures.length > 1) {
|
||||
const counter = owner.createElement("span");
|
||||
counter.className = "lt-assist-signature-count";
|
||||
counter.textContent = t("editor.assist.signature.count", {
|
||||
index: help.activeSignature + 1,
|
||||
count: help.signatures.length,
|
||||
});
|
||||
head.prepend(counter);
|
||||
}
|
||||
root.append(head);
|
||||
const parameterDoc = signature.parameters[active]?.documentation;
|
||||
for (const doc of [parameterDoc, signature.documentation]) {
|
||||
if (doc !== undefined) {
|
||||
const dom = renderMarkdown(doc, owner);
|
||||
dom.classList.add("lt-assist-signature-doc");
|
||||
root.append(dom);
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an update typed a character that opens or continues an
|
||||
* argument list.
|
||||
*
|
||||
* @param update - the view update.
|
||||
*/
|
||||
export function typedArgumentStart(update: ViewUpdate): boolean {
|
||||
let typed = false;
|
||||
for (const tr of update.transactions) {
|
||||
if (!tr.isUserEvent("input")) {
|
||||
continue;
|
||||
}
|
||||
tr.changes.iterChanges((_fromA, _toA, _fromB, _toB, inserted) => {
|
||||
if (/[(,]$/.test(inserted.toString())) {
|
||||
typed = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
return typed;
|
||||
}
|
||||
|
||||
/** The plugin that asks for signature help; see the module docs. */
|
||||
class SignaturePlugin implements PluginValue {
|
||||
/** The pending debounce timer. */
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
/** Number of the newest request; older answers are dropped. */
|
||||
private sequence = 0;
|
||||
/** Set once the view is gone. */
|
||||
private destroyed = false;
|
||||
|
||||
/**
|
||||
* @param view - the editor view.
|
||||
* @param buffer - the buffer it shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
constructor(
|
||||
private readonly view: EditorView,
|
||||
private readonly buffer: AssistBuffer,
|
||||
private readonly transport: AssistTransport,
|
||||
) {}
|
||||
|
||||
/** Asks again after relevant typing or, while open, any edit or move. */
|
||||
update(update: ViewUpdate): void {
|
||||
const open = update.state.field(signatureField, false) ?? null;
|
||||
if (typedArgumentStart(update)) {
|
||||
this.schedule(0);
|
||||
} else if (open && (update.docChanged || update.selectionSet)) {
|
||||
this.schedule(SIGNATURE_DEBOUNCE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks for signature help after `delay` milliseconds.
|
||||
*
|
||||
* @param delay - the debounce.
|
||||
*/
|
||||
schedule(delay: number): void {
|
||||
if (this.timer !== null) {
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.ask();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/** Sends the request and shows or clears the answer. */
|
||||
private async ask(): Promise<void> {
|
||||
this.sequence += 1;
|
||||
const sequence = this.sequence;
|
||||
const view = this.view;
|
||||
const pos = view.state.selection.main.head;
|
||||
const value = await queryAt({
|
||||
buffer: this.buffer,
|
||||
transport: this.transport,
|
||||
doc: view.state.doc,
|
||||
current: () => view.state.doc,
|
||||
pos,
|
||||
command: "lsp.signatureHelp",
|
||||
});
|
||||
if (this.destroyed || sequence !== this.sequence || view.state.selection.main.head !== pos) {
|
||||
return;
|
||||
}
|
||||
const help = toSignatureHelp(value);
|
||||
const shown = view.state.field(signatureField, false) ?? null;
|
||||
if (!help && !shown) {
|
||||
return;
|
||||
}
|
||||
view.dispatch({ effects: setSignature.of(help ? { pos, help } : null) });
|
||||
}
|
||||
|
||||
/** Stops pending work. */
|
||||
destroy(): void {
|
||||
this.destroyed = true;
|
||||
this.sequence += 1;
|
||||
if (this.timer !== null) {
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The plugins of every signature help extension built so far. */
|
||||
const plugins = new Set<ViewPlugin<SignaturePlugin>>();
|
||||
|
||||
/**
|
||||
* Asks for signature help at the cursor of `view` now.
|
||||
*
|
||||
* @param view - an editor view with the signature help extension.
|
||||
*/
|
||||
export function requestSignatureHelp(view: EditorView): void {
|
||||
for (const plugin of plugins) {
|
||||
const instance = view.plugin(plugin);
|
||||
if (instance) {
|
||||
instance.schedule(0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The signature help extension for one buffer.
|
||||
*
|
||||
* @param buffer - the buffer the editor state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
export function lspSignatureHelp(
|
||||
buffer: AssistBuffer,
|
||||
transport: AssistTransport = engineAssistTransport,
|
||||
): Extension {
|
||||
const plugin = ViewPlugin.define((view) => new SignaturePlugin(view, buffer, transport));
|
||||
plugins.add(plugin);
|
||||
return [
|
||||
signatureField,
|
||||
plugin,
|
||||
keymap.of([
|
||||
{
|
||||
key: "Mod-Shift-Space",
|
||||
run: (view) => {
|
||||
view.plugin(plugin)?.schedule(0);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "Escape",
|
||||
run: (view) => {
|
||||
if (!view.state.field(signatureField, false)) {
|
||||
return false;
|
||||
}
|
||||
view.dispatch({ effects: setSignature.of(null) });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
]),
|
||||
];
|
||||
}
|
||||
319
ui/src/components/editor/assist/types.ts
Normal file
319
ui/src/components/editor/assist/types.ts
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
/**
|
||||
* Shapes of the engine's assist results (`lsp.completion`, `lsp.hover`,
|
||||
* `lsp.signatureHelp`) and checks that turn the untrusted command results
|
||||
* into them. Anything malformed is dropped, never thrown.
|
||||
*/
|
||||
import type { JsonValue, RunResult } from "../../../ipc";
|
||||
|
||||
/** A 0-based position; the column counts UTF-16 code units. */
|
||||
export interface AssistPosition {
|
||||
/** Line. */
|
||||
line: number;
|
||||
/** Column. */
|
||||
column: number;
|
||||
}
|
||||
|
||||
/** A range between two positions, end exclusive. */
|
||||
export interface AssistRange {
|
||||
/** Start. */
|
||||
start: AssistPosition;
|
||||
/** End. */
|
||||
end: AssistPosition;
|
||||
}
|
||||
|
||||
/** A text edit of a completion item. */
|
||||
export interface AssistEdit {
|
||||
/** What it replaces, in the text the completion was asked for. */
|
||||
range: AssistRange;
|
||||
/** The replacement. */
|
||||
newText: string;
|
||||
}
|
||||
|
||||
/** The completion item kinds the engine names. */
|
||||
export const COMPLETION_KINDS = [
|
||||
"text",
|
||||
"method",
|
||||
"function",
|
||||
"constructor",
|
||||
"field",
|
||||
"variable",
|
||||
"class",
|
||||
"interface",
|
||||
"module",
|
||||
"property",
|
||||
"unit",
|
||||
"value",
|
||||
"enum",
|
||||
"keyword",
|
||||
"snippet",
|
||||
"color",
|
||||
"file",
|
||||
"reference",
|
||||
"folder",
|
||||
"enumMember",
|
||||
"constant",
|
||||
"struct",
|
||||
"event",
|
||||
"operator",
|
||||
"typeParameter",
|
||||
] as const;
|
||||
|
||||
/** A completion item kind. */
|
||||
export type CompletionKind = (typeof COMPLETION_KINDS)[number];
|
||||
|
||||
/** One completion item, as `lsp.completion` returns it. */
|
||||
export interface CompletionItem {
|
||||
/** Shown and matched against the typed text. */
|
||||
label: string;
|
||||
/** What it is. */
|
||||
kind: CompletionKind;
|
||||
/** A one-line description (signature, type). */
|
||||
detail?: string;
|
||||
/** Markdown documentation. */
|
||||
documentation?: string;
|
||||
/** Inserted text when there is no {@link textEdit}. */
|
||||
insertText: string;
|
||||
/** The edit to apply instead of inserting {@link insertText}. */
|
||||
textEdit?: AssistEdit;
|
||||
/** More edits elsewhere, such as a `use` import. */
|
||||
additionalTextEdits?: AssistEdit[];
|
||||
/** Whether the symbol is deprecated. */
|
||||
deprecated?: boolean;
|
||||
}
|
||||
|
||||
/** The result of `lsp.completion`. */
|
||||
export interface CompletionList {
|
||||
/** The items, best first. */
|
||||
items: CompletionItem[];
|
||||
/** Whether typing more should ask the server again. */
|
||||
incomplete: boolean;
|
||||
}
|
||||
|
||||
/** The result of `lsp.hover`. */
|
||||
export interface HoverResult {
|
||||
/** Markdown; empty when there is nothing to show. */
|
||||
contents: string;
|
||||
/** The range the hover applies to. */
|
||||
range?: AssistRange;
|
||||
}
|
||||
|
||||
/** One parameter of a signature. */
|
||||
export interface SignatureParameter {
|
||||
/** UTF-16 offsets of the parameter inside the signature label. */
|
||||
label: [number, number] | null;
|
||||
/** Markdown documentation. */
|
||||
documentation?: string;
|
||||
}
|
||||
|
||||
/** One signature of `lsp.signatureHelp`. */
|
||||
export interface Signature {
|
||||
/** The whole signature. */
|
||||
label: string;
|
||||
/** Markdown documentation. */
|
||||
documentation?: string;
|
||||
/** Its parameters. */
|
||||
parameters: SignatureParameter[];
|
||||
/** The active parameter, overriding the result's. */
|
||||
activeParameter?: number;
|
||||
}
|
||||
|
||||
/** The result of `lsp.signatureHelp`. */
|
||||
export interface SignatureHelpResult {
|
||||
/** The signatures; empty outside a call. */
|
||||
signatures: Signature[];
|
||||
/** The signature to show. */
|
||||
activeSignature: number;
|
||||
/** The parameter to highlight. */
|
||||
activeParameter: number;
|
||||
}
|
||||
|
||||
/** How the assist features reach the engine; replaced by a fake in tests. */
|
||||
export interface AssistTransport {
|
||||
/**
|
||||
* Runs an engine command that waits for the language server
|
||||
* (`runWaiting` in `ipc.ts`).
|
||||
*
|
||||
* @param command - the command id.
|
||||
* @param params - its params.
|
||||
*/
|
||||
query(command: string, params: JsonValue): Promise<RunResult<unknown>>;
|
||||
}
|
||||
|
||||
/** The buffer an editor state shows, as the assist features need it. */
|
||||
export interface AssistBuffer {
|
||||
/** Engine buffer id. */
|
||||
id: number;
|
||||
/** Resolves once every local edit has reached the engine. */
|
||||
idle(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Whether a value is a plain object. */
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** A non-negative integer, or null. */
|
||||
function count(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/** A string, or undefined. */
|
||||
function text(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
/** Reads a position. */
|
||||
function toPosition(value: unknown): AssistPosition | null {
|
||||
if (!isObject(value)) {
|
||||
return null;
|
||||
}
|
||||
const line = count(value.line);
|
||||
const column = count(value.column);
|
||||
return line === null || column === null ? null : { line, column };
|
||||
}
|
||||
|
||||
/** Reads a range. */
|
||||
export function toRange(value: unknown): AssistRange | null {
|
||||
if (!isObject(value)) {
|
||||
return null;
|
||||
}
|
||||
const start = toPosition(value.start);
|
||||
const end = toPosition(value.end);
|
||||
return start && end ? { start, end } : null;
|
||||
}
|
||||
|
||||
/** Reads a text edit. */
|
||||
function toEdit(value: unknown): AssistEdit | null {
|
||||
if (!isObject(value)) {
|
||||
return null;
|
||||
}
|
||||
const range = toRange(value.range);
|
||||
const newText = text(value.newText);
|
||||
return range && newText !== undefined ? { range, newText } : null;
|
||||
}
|
||||
|
||||
/** Reads one completion item. */
|
||||
function toItem(value: unknown): CompletionItem | null {
|
||||
if (!isObject(value)) {
|
||||
return null;
|
||||
}
|
||||
const label = text(value.label);
|
||||
if (label === undefined || label === "") {
|
||||
return null;
|
||||
}
|
||||
const kind = COMPLETION_KINDS.find((k) => k === value.kind) ?? "text";
|
||||
const item: CompletionItem = { label, kind, insertText: text(value.insertText) ?? label };
|
||||
const detail = text(value.detail);
|
||||
if (detail !== undefined && detail !== "") {
|
||||
item.detail = detail;
|
||||
}
|
||||
const documentation = text(value.documentation);
|
||||
if (documentation !== undefined && documentation !== "") {
|
||||
item.documentation = documentation;
|
||||
}
|
||||
const edit = toEdit(value.textEdit);
|
||||
if (edit) {
|
||||
item.textEdit = edit;
|
||||
}
|
||||
if (Array.isArray(value.additionalTextEdits)) {
|
||||
const extra = value.additionalTextEdits.map(toEdit).filter((e): e is AssistEdit => e !== null);
|
||||
if (extra.length > 0) {
|
||||
item.additionalTextEdits = extra;
|
||||
}
|
||||
}
|
||||
if (value.deprecated === true) {
|
||||
item.deprecated = true;
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an `lsp.completion` result.
|
||||
*
|
||||
* @param value - the untrusted result.
|
||||
* @returns the list; empty when malformed.
|
||||
*/
|
||||
export function toCompletionList(value: unknown): CompletionList {
|
||||
if (!isObject(value) || !Array.isArray(value.items)) {
|
||||
return { items: [], incomplete: false };
|
||||
}
|
||||
return {
|
||||
items: value.items.map(toItem).filter((i): i is CompletionItem => i !== null),
|
||||
incomplete: value.incomplete === true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an `lsp.hover` result.
|
||||
*
|
||||
* @param value - the untrusted result.
|
||||
* @returns the hover, or null when there is nothing to show.
|
||||
*/
|
||||
export function toHover(value: unknown): HoverResult | null {
|
||||
if (!isObject(value)) {
|
||||
return null;
|
||||
}
|
||||
const contents = text(value.contents);
|
||||
if (contents === undefined || contents.trim() === "") {
|
||||
return null;
|
||||
}
|
||||
const range = toRange(value.range);
|
||||
return range ? { contents, range } : { contents };
|
||||
}
|
||||
|
||||
/** Reads one signature. */
|
||||
function toSignature(value: unknown): Signature | null {
|
||||
if (!isObject(value)) {
|
||||
return null;
|
||||
}
|
||||
const label = text(value.label);
|
||||
if (label === undefined) {
|
||||
return null;
|
||||
}
|
||||
const parameters: SignatureParameter[] = Array.isArray(value.parameters)
|
||||
? value.parameters.map((p): SignatureParameter => {
|
||||
const span = isObject(p) && Array.isArray(p.label) ? p.label : null;
|
||||
const from = span ? count(span[0]) : null;
|
||||
const to = span ? count(span[1]) : null;
|
||||
const parameter: SignatureParameter = {
|
||||
label: from !== null && to !== null && from <= to && to <= label.length ? [from, to] : null,
|
||||
};
|
||||
const documentation = isObject(p) ? text(p.documentation) : undefined;
|
||||
if (documentation !== undefined && documentation !== "") {
|
||||
parameter.documentation = documentation;
|
||||
}
|
||||
return parameter;
|
||||
})
|
||||
: [];
|
||||
const signature: Signature = { label, parameters };
|
||||
const documentation = text(value.documentation);
|
||||
if (documentation !== undefined && documentation !== "") {
|
||||
signature.documentation = documentation;
|
||||
}
|
||||
const active = count(value.activeParameter);
|
||||
if (active !== null) {
|
||||
signature.activeParameter = active;
|
||||
}
|
||||
return signature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an `lsp.signatureHelp` result.
|
||||
*
|
||||
* @param value - the untrusted result.
|
||||
* @returns the signatures, or null when there are none.
|
||||
*/
|
||||
export function toSignatureHelp(value: unknown): SignatureHelpResult | null {
|
||||
if (!isObject(value) || !Array.isArray(value.signatures)) {
|
||||
return null;
|
||||
}
|
||||
const signatures = value.signatures.map(toSignature).filter((s): s is Signature => s !== null);
|
||||
if (signatures.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
signatures,
|
||||
activeSignature: Math.min(count(value.activeSignature) ?? 0, signatures.length - 1),
|
||||
activeParameter: count(value.activeParameter) ?? 0,
|
||||
};
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import type { Extension } from "@codemirror/state";
|
|||
import { basicSetup } from "codemirror";
|
||||
import { languageExtensions, type SYNTAX_CLASS, type SyntaxToken } from "./language";
|
||||
import { lintExtensions } from "./lint";
|
||||
import { assistExtensions, type AssistBuffer } from "./assist";
|
||||
|
||||
/**
|
||||
* Colours of the highlight classes (`language.ts`), one `--lt-syntax-*`
|
||||
|
|
@ -109,7 +110,15 @@ export const lutraEditorTheme: Extension = EditorView.theme({
|
|||
*
|
||||
* @param path - the file's path, which picks the language; plain text when
|
||||
* omitted or unknown.
|
||||
* @param buffer - the engine buffer the state shows; PHP files of a buffer
|
||||
* get completion, hover and signature help (`./assist`).
|
||||
*/
|
||||
export function editorExtensions(path = ""): Extension {
|
||||
return [basicSetup, lutraEditorTheme, languageExtensions(path), lintExtensions(path)];
|
||||
export function editorExtensions(path = "", buffer?: AssistBuffer): Extension {
|
||||
return [
|
||||
basicSetup,
|
||||
lutraEditorTheme,
|
||||
languageExtensions(path),
|
||||
lintExtensions(path),
|
||||
assistExtensions(path, buffer),
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
{
|
||||
"app.statusBar.version": "{name} {version}",
|
||||
"command.editor.complete": "Complete Code",
|
||||
"command.editor.parameterInfo": "Parameter Info",
|
||||
"command.editor.quickDocumentation": "Quick Documentation",
|
||||
"command.editor.reveal": "Reveal Cursor in Editor",
|
||||
"command.find.open": "Find in Files…",
|
||||
"command.goto.classOpen": "Go to Class…",
|
||||
|
|
@ -31,6 +34,32 @@
|
|||
"common.toolWindow.resize": "Resize {title}",
|
||||
"common.toolWindow.show": "Show {title}",
|
||||
"common.toolWindow.stripe": "Tool windows",
|
||||
"editor.assist.kind.class": "Class",
|
||||
"editor.assist.kind.color": "Colour",
|
||||
"editor.assist.kind.constant": "Constant",
|
||||
"editor.assist.kind.constructor": "Constructor",
|
||||
"editor.assist.kind.enum": "Enum",
|
||||
"editor.assist.kind.enumMember": "Enum case",
|
||||
"editor.assist.kind.event": "Event",
|
||||
"editor.assist.kind.field": "Field",
|
||||
"editor.assist.kind.file": "File",
|
||||
"editor.assist.kind.folder": "Folder",
|
||||
"editor.assist.kind.function": "Function",
|
||||
"editor.assist.kind.interface": "Interface",
|
||||
"editor.assist.kind.keyword": "Keyword",
|
||||
"editor.assist.kind.method": "Method",
|
||||
"editor.assist.kind.module": "Namespace",
|
||||
"editor.assist.kind.operator": "Operator",
|
||||
"editor.assist.kind.property": "Property",
|
||||
"editor.assist.kind.reference": "Reference",
|
||||
"editor.assist.kind.snippet": "Snippet",
|
||||
"editor.assist.kind.struct": "Structure",
|
||||
"editor.assist.kind.text": "Text",
|
||||
"editor.assist.kind.typeParameter": "Type parameter",
|
||||
"editor.assist.kind.unit": "Unit",
|
||||
"editor.assist.kind.value": "Value",
|
||||
"editor.assist.kind.variable": "Variable",
|
||||
"editor.assist.signature.count": "{index} of {count}",
|
||||
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
||||
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
|
||||
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { run, type EngineError, type RunResult } from "../ipc";
|
|||
import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync";
|
||||
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
|
||||
import { editorExtensions } from "../components/editor/extensions";
|
||||
import type { AssistBuffer } from "../components/editor/assist";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
|
||||
/** Engine command ids used by the editor. */
|
||||
|
|
@ -111,7 +112,7 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
/** Engine transport for syncs, replaceable in tests. */
|
||||
let transport: SyncTransport = engineTransport;
|
||||
/** Extensions of a new editor state for a file path, replaceable in tests. */
|
||||
let extensions: (path: string) => Extension = editorExtensions;
|
||||
let extensions: (path: string, buffer?: AssistBuffer) => Extension = editorExtensions;
|
||||
/** Counter of tab adoptions, so only the newest open activates its tab. */
|
||||
let openSequence = 0;
|
||||
/** Unsubscribe function of the event subscription. */
|
||||
|
|
@ -144,7 +145,7 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
* @param next - transport for new syncs.
|
||||
* @param nextExtensions - extensions for new editor states, by file path.
|
||||
*/
|
||||
function configure(next: SyncTransport, nextExtensions?: (path: string) => Extension): void {
|
||||
function configure(next: SyncTransport, nextExtensions?: (path: string, buffer?: AssistBuffer) => Extension): void {
|
||||
transport = next;
|
||||
if (nextExtensions) {
|
||||
extensions = nextExtensions;
|
||||
|
|
@ -163,7 +164,7 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
const started = openStarted.get(info.path);
|
||||
syncs.set(
|
||||
info.id,
|
||||
new BufferSync(info, extensions(info.path), transport, (error) => {
|
||||
new BufferSync(info, extensions(info.path, { id: info.id, idle: () => syncs.get(info.id)?.idle() ?? Promise.resolve() }), transport, (error) => {
|
||||
const tab = tabOf(info.id);
|
||||
if (tab) {
|
||||
tab.notice = { kind: "error", message: error.message };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue