Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(codemirror): leave where a completion list opens to its caller
Elian Doran6b208c7212c9
diff --git a/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsx b/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsxindex 1b48a83841..51393f5eb0 100644--- a/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsx@@ -8,14 +8,14 @@ import type { CodeSnippet } from "./snippets";describe("codeCompletionAt", () => {it("matches a /command where there are snippets, and an identifier or a member where there are type completions", () => {const both = { snippets: true, types: true };- expect(codeCompletionAt("x = /hea", false, both)).toEqual({ kind: "snippets", from: 4, query: "hea", explicit: false });+ expect(codeCompletionAt("x = /hea", false, both)).toEqual({ kind: "snippets", from: 4, query: "hea" });expect(codeCompletionAt("a/b", false, both)).toMatchObject({ kind: "types", from: 2, query: "b" });expect(codeCompletionAt("/hea", false, { snippets: false, types: false })).toBe(null);expect(codeCompletionAt("const x = api.get", false, both)).toMatchObject({ kind: "types", from: 14, query: "get" });expect(codeCompletionAt("api.", false, both)).toMatchObject({ kind: "types", from: 4, query: "" });expect(codeCompletionAt("x = ", false, both)).toBe(null);- expect(codeCompletionAt("x = ", true, both)).toMatchObject({ kind: "types", from: 4, query: "", explicit: true });+ expect(codeCompletionAt("x = ", true, both)).toEqual({ kind: "types", from: 4, query: "" });expect(codeCompletionAt("x = 12", false, both)).toBe(null);expect(codeCompletionAt("api.get", false, { snippets: true, types: false })).toBe(null);});diff --git a/apps/client/src/widgets/type_widgets/code/code_completions.tsx b/apps/client/src/widgets/type_widgets/code/code_completions.tsxindex 6d39f4e8cf..7e7c8cd239 100644--- a/apps/client/src/widgets/type_widgets/code/code_completions.tsx+++ b/apps/client/src/widgets/type_widgets/code/code_completions.tsx@@ -11,8 +11,6 @@ export interface CodeCompletionMatch {from: number;/** What the list filters by: the text after the `/`, or the identifier typed so far. */query: string;- /** Asked for with Ctrl-Space. */- explicit: boolean;}/** An entry of the code completion list, and what picking it puts in place of the match. */@@ -44,7 +42,7 @@ export function codeCompletions(editor: VanillaCodeMirror, getSnippets: () => Coexport function codeCompletionAt(before: string, explicit: boolean, available: { snippets: boolean; types: boolean }): CodeCompletionMatch | null {const command = available.snippets ? COMMAND_TYPED.exec(before) : null;if (command) {- return { kind: "snippets", from: command.index, query: command[0].slice(1), explicit };+ return { kind: "snippets", from: command.index, query: command[0].slice(1) };}if (!available.types) {return null;@@ -54,7 +52,7 @@ export function codeCompletionAt(before: string, explicit: boolean, available: {if (!word && !explicit && !before.endsWith(".")) {return null;}- return { kind: "types", from: before.length - word.length, query: word, explicit };+ return { kind: "types", from: before.length - word.length, query: word };}const COMMAND_TYPED = new RegExp(`${SLASH_COMMAND_REGEX.source}$`);@@ -123,7 +121,7 @@ function createCodeCompletionList(editor: VanillaCodeMirror, getSnippets: () =>if (match.kind === "snippets") {return getSnippets().map(snippetCommand);}- return typeCompletionEntries(await editor.getTypeCompletions(match.explicit) ?? []);+ return typeCompletionEntries(await editor.getTypeCompletions() ?? []);}return {diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.tsindex 8306598fbd..9315e61a53 100644--- a/packages/codemirror/src/index.spec.ts+++ b/packages/codemirror/src/index.spec.ts@@ -621,13 +621,13 @@ describe("CodeMirror", () => {editor = build();await editor.setMimeType("text/plain");expect(editor.hasTypeCompletions()).toBe(false);- expect(await editor.getTypeCompletions(true)).toBe(null);+ expect(await editor.getTypeCompletions()).toBe(null);editor.setText("api.");await editor.setMimeType(SCRIPT_MIME_BACKEND);editor.dispatch({ selection: EditorSelection.cursor(4) });expect(editor.hasTypeCompletions()).toBe(true);- const completions = await editor.getTypeCompletions(false) ?? [];+ const completions = await editor.getTypeCompletions() ?? [];expect(completions).toContainEqual({ label: "getNote", type: "method" });expect(completions.map(({ label }) => label)).not.toContain("Array");}, 30_000);diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex 2780bc826f..1a3c4addce 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -558,8 +558,8 @@ export default class CodeMirror extends EditorView {* The language service's completions at the caret, best first, or null where it offers none* or the MIME type has no language service.*/- async getTypeCompletions(explicit: boolean) {- return await this.typeCompleter?.(this.state.selection.main.head, explicit) ?? null;+ async getTypeCompletions() {+ return await this.typeCompleter?.(this.state.selection.main.head) ?? null;}/**diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.tsdeleted file mode 100644index 57a6dead16..0000000000--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts+++ /dev/null@@ -1,44 +0,0 @@-import { expect, test } from "vitest";-import { ensureAnchor, getLineAtPosition, matchBefore } from "./autocomplete.js";--test("matchBefore", () => {- expect(matchBefore("hi.", 0, /\./)).toEqual(null);- expect(matchBefore("hi.", 3, /\./)).toEqual({- from: 2,- text: ".",- to: 3,- });-});--test("ensureAnchor", () => {- expect(ensureAnchor(/hi/, false)).toEqual(/(?:hi)$/);- expect(ensureAnchor(/hi$/, false)).toEqual(/hi$/);- expect(ensureAnchor(/hi$/, true)).toEqual(/^(?:hi$)/);- expect(ensureAnchor(/^hi$/, true)).toEqual(/^hi$/);-});--test("getLineAtPosition", () => {- expect(getLineAtPosition("x", 0)).toEqual({- from: 0,- text: "x",- to: 1,- });-- expect(getLineAtPosition("x", 10)).toEqual({- from: 0,- text: "x",- to: 1,- });-- expect(getLineAtPosition("x", -10)).toEqual({- from: 0,- text: "x",- to: 1,- });-- expect(getLineAtPosition("first line\nsecond line", 12)).toEqual({- from: 11,- text: "second line",- to: 22,- });-});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.tsindex f56f2330a5..f270fb32f0 100644--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts@@ -1,8 +1,4 @@-import type {- Completion,- CompletionContext,- CompletionResult,-} from "@codemirror/autocomplete";+import type { Completion } from "@codemirror/autocomplete";import ts from "typescript";import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";@@ -10,32 +6,20 @@ const TS_COMPLETE_BLOCKLIST: ts.ScriptElementKind[] = [ts.ScriptElementKind.warning,];+/**+ * The completions the language service offers at `pos`. Whether a list opens there at all is the+ * caller's decision.+ */export async function getAutocompletion({env,path,- context,+ pos,}: {env: VirtualTypeScriptEnvironment;path: string;- /**- * Allow this to be a subset of the full CompletionContext- * object, because the raw object isn't serializable.- */- context: Pick<CompletionContext, "pos" | "explicit">;-}): Promise<CompletionResult | null> {- const { pos, explicit } = context;- const rawContents = env.getSourceFile(path)?.getFullText();-- if (!rawContents) return null;-- // If there's space behind the cursor, don't try and autocomplete.- // https://codemirror.net/examples/autocompletion/- let word = matchBefore(rawContents, pos, /\w*/);- if (!word?.text) {- word = matchBefore(rawContents, pos, /\./);- }-- if (!word?.text && !explicit) return null;+ pos: number;+}): Promise<Completion[] | null> {+ if (!env.getSourceFile(path)) return null;const completionInfo = env.languageService.getCompletionsAtPosition(path,@@ -71,10 +55,7 @@ export async function getAutocompletion({};});- return {- from: word ? (word.text === "." ? word.to : word.from) : pos,- options,- };+ return options;}/**@@ -97,49 +78,3 @@ export const DEFAULT_CODEMIRROR_TYPE_ICONS = new Set([`type`,`variable`,]);--// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L111-// TODO: do we need to vendor this?-export function matchBefore(code: string, pos: number, expr: RegExp) {- const line = getLineAtPosition(code, pos);- let start = Math.max(line.from, pos - 250);- let str = line.text.slice(start - line.from, pos - line.from);- let found = str.search(ensureAnchor(expr, false));- return found < 0- ? null- : { from: start + found, to: pos, text: str.slice(found) };-}--// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L245-// TODO: do we need this, or can use import it from codemirror?-export function ensureAnchor(expr: RegExp, start: boolean) {- let { source } = expr;- let addStart = start && source[0] != "^",- addEnd = source[source.length - 1] != "$";- if (!addStart && !addEnd) return expr;- return new RegExp(- `${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`,- expr.flags ?? (expr.ignoreCase ? "i" : ""),- );-}--/**- * TODO: confirm that this is necessary; it may be possible- * and more efficient to get the line from CodeMirror, though- * that would mean it probably doesn't mix well with the approach- * of persisting code in the TS enviroment.- */-export function getLineAtPosition(code: string, position: number) {- // lineStart is the index of line break or zero- const from = code.lastIndexOf("\n", position - 1) + 1;- let to = code.indexOf("\n", position);- if (to === -1) {- to = code.length;- }- const text = code.slice(from, to);- return {- from,- to,- text,- };-}diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.tsindex 0cf322b173..be04097aa1 100644--- a/packages/codemirror/src/type_completion/index.spec.ts+++ b/packages/codemirror/src/type_completion/index.spec.ts@@ -27,7 +27,7 @@ function completionsAtMarker(mime: string, source: string, context?: ScriptApiCo* The labels `buildTypeCompletion()`'s `complete()` offers at the `|` marker in `source`, as the* editor's completion list asks for them.*/-async function completeAtMarker(mime: string, source: string, explicit = false) {+async function completeAtMarker(mime: string, source: string) {const offset = source.indexOf("|");const code = source.slice(0, offset) + source.slice(offset + 1);const { extensions, complete } = await buildTypeCompletion(mime);@@ -35,7 +35,7 @@ async function completeAtMarker(mime: string, source: string, explicit = false)const config = EditorState.create({ extensions }).facet(tsFacet);expect(config).toBeTruthy();if (config) createOrUpdateFile(config.env, config.path, code);- return (await complete?.(offset, explicit))?.map((entry) => entry.label) ?? [];+ return (await complete?.(offset))?.map((entry) => entry.label) ?? [];}/** "Property 'x' does not exist on type 'y'." */@@ -520,7 +520,7 @@ describe("buildTypeCompletion", () => {it("completes globals and keywords where nothing is typed yet", async () => {// The new list caches the answer for the position it opens at, and filters it as the// word is typed, so the answer with nothing typed has to hold them already.- const labels = await completeAtMarker(SCRIPT_MIME_FRONTEND, "function run() {\n |\n}", true);+ const labels = await completeAtMarker(SCRIPT_MIME_FRONTEND, "function run() {\n |\n}");expect(labels).toEqual(expect.arrayContaining([ "api", "console", "const", "return" ]));}, TIMEOUT);diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.tsindex de4a9f7924..0b05155642 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -202,8 +202,7 @@ export interface TypeCompletion {}/** The completions at `pos`, best first, or null where the language service offers none there. */-export type TypeCompleter =- (pos: number, explicit: boolean) => Promise<TypeCompletionEntry[] | null>;+export type TypeCompleter = (pos: number) => Promise<TypeCompletionEntry[] | null>;/** A completion the TypeScript language service offers. */export interface TypeCompletionEntry {@@ -248,11 +247,11 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContexlintGutter(),hoverTheme],- async complete(pos, explicit) {- const result = await getAutocompletion({ env, path, context: { pos, explicit } });- if (!result) return null;+ async complete(pos) {+ const options = await getAutocompletion({ env, path, pos });+ if (!options) return null;- return [ ...result.options ]+ return options.sort((a, b) => (b.boost ?? 0) - (a.boost ?? 0)).map(({ label, type }) => ({ label, type }));}