Skip to content

Build your personal knowledge base with Trilium Notes

fix(code): open the completion list as code is typed, not on a click

Elian Doran9f4c481990c8
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.tsx
index 51393f5eb0..ad0d4fe5a7 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
@@ -63,6 +63,20 @@ describe("codeCompletions", () => {
await vi.waitFor(() => expect(view.getText()).toBe("x;\n// header\n"));
});
+ it("opens as an identifier is typed, not as the caret moves onto one", async () => {
+ const view = build([]);
+ type("return x");
+ vi.spyOn(view, "hasTypeCompletions").mockReturnValue(true);
+ const lookUp = vi.spyOn(view, "getTypeCompletions").mockResolvedValue([ { label: "returns" } ]);
+
+ view.dispatch({ selection: EditorSelection.cursor(6) });
+ await press("Shift");
+ expect(lookUp).not.toHaveBeenCalled();
+
+ type("s");
+ await vi.waitFor(() => expect(lookUp).toHaveBeenCalledOnce());
+ });
+
it("offers nothing in a read-only editor", async () => {
const view = build([ { noteId: "s1", title: "Header", content: "// header\n" } ], true);
vi.spyOn(view, "hasTypeCompletions").mockReturnValue(true);
diff --git a/apps/client/src/widgets/type_widgets/code/code_completions.tsx b/apps/client/src/widgets/type_widgets/code/code_completions.tsx
index 7e7c8cd239..d0eb4aab0c 100644
--- a/apps/client/src/widgets/type_widgets/code/code_completions.tsx
+++ b/apps/client/src/widgets/type_widgets/code/code_completions.tsx
@@ -29,6 +29,7 @@ export function codeCompletions(editor: VanillaCodeMirror, getSnippets: () => Co
snippets: getSnippets().length > 0,
types: editor.hasTypeCompletions()
})),
+ opensOnCaretMove: false,
list: () => createCodeCompletionList(editor, getSnippets)
});
}
diff --git a/packages/codemirror/src/extensions/hosted_completion.spec.ts b/packages/codemirror/src/extensions/hosted_completion.spec.ts
index 7679b7c13c..039695ceb6 100644
--- a/packages/codemirror/src/extensions/hosted_completion.spec.ts
+++ b/packages/codemirror/src/extensions/hosted_completion.spec.ts
@@ -3,7 +3,7 @@ import type { EditorView } from "@codemirror/view";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "../field_editor.js";
-import { hostedCompletion, type HostedCompletionList, type HostedCompletionState } from "./hosted_completion.js";
+import { hostedCompletion, type HostedCompletionConfig, type HostedCompletionList, type HostedCompletionState } from "./hosted_completion.js";
let editor: FieldEditor | undefined;
@@ -270,6 +270,32 @@ describe("hostedCompletion", () => {
expect(list.show).not.toHaveBeenCalled();
});
+ it("opens on a caret move only where the host allows it, and keeps an open list while the caret stays on its match", async () => {
+ // Any word before the caret, as a code editor matches identifiers.
+ const word = (before: string, explicit: boolean, state: EditorState): TestMatch | null => {
+ const found = /\w+$/.exec(before)?.[0];
+ return found ? { from: before.length - found.length, query: found, explicit, at: state.selection.main.head } : null;
+ };
+
+ const { list, shown } = build({ doc: "return x" }, word, { opensOnCaretMove: false });
+ editor?.dispatch({ selection: EditorSelection.cursor(6) });
+ await settle();
+ expect(list.show).not.toHaveBeenCalled();
+
+ type("s");
+ await vi.waitFor(() => expect(shown()?.match.query).toBe("returns"));
+ editor?.dispatch({ selection: EditorSelection.cursor(5) });
+ await vi.waitFor(() => expect(shown()?.match.query).toBe("retur"));
+ editor?.dispatch({ selection: EditorSelection.cursor(9) });
+ await vi.waitFor(() => expect(list.hide).toHaveBeenCalled());
+ await settle();
+ expect(shown()?.match.query).toBe("retur");
+
+ editor?.destroy();
+ const byDefault = build({ doc: "return x" }, word);
+ await vi.waitFor(() => expect(byDefault.shown()?.match.query).toBe("x"));
+ });
+
it("closes as the editor loses the focus, and takes the list down with it", async () => {
const { list, shown } = build();
@@ -329,7 +355,11 @@ describe("hostedCompletion", () => {
});
});
-function build(config: Partial<FieldEditorConfig> = {}, matchAt: typeof match = match) {
+function build(
+ config: Partial<FieldEditorConfig> = {},
+ matchAt: typeof match = match,
+ options: Partial<HostedCompletionConfig<TestMatch>> = {}
+) {
let element: HTMLElement | null = null;
let state: HostedCompletionState<TestMatch> | undefined;
let placed: unknown;
@@ -354,7 +384,7 @@ function build(config: Partial<FieldEditorConfig> = {}, matchAt: typeof match =
editor = createFieldEditor({
parent,
...config,
- extensions: [ hostedCompletion({ match: matchAt, list: () => list }) ]
+ extensions: [ hostedCompletion({ ...options, match: matchAt, list: () => list }) ]
});
editor.focus();
editor.dispatch({ selection: EditorSelection.cursor(editor.state.doc.length) });
diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.ts
index 2fb13d78ec..6065df7dd1 100644
--- a/packages/codemirror/src/extensions/hosted_completion.ts
+++ b/packages/codemirror/src/extensions/hosted_completion.ts
@@ -59,6 +59,12 @@ export interface HostedCompletionConfig<M extends HostedCompletionMatch> {
* offers none. `state` is there for what the text alone does not tell, such as the syntax tree.
*/
match(before: string, explicit: boolean, state: EditorState): M | null;
+ /**
+ * Whether moving the caret onto a match opens the list, as typing does. `true` by default. A host
+ * whose matches are everywhere, such as any identifier in code, passes `false`: a caret move then
+ * only keeps an open list while the caret stays on its match.
+ */
+ opensOnCaretMove?: boolean;
/** Creates the list, once per editor. */
list(view: EditorView): HostedCompletionList<M>;
}
@@ -74,7 +80,7 @@ export interface HostedCompletionConfig<M extends HostedCompletionMatch> {
* the same lists. The list closes when nothing matches, when the editor loses the focus, and on
* Escape, after which it stays closed for that match.
*/
-export function hostedCompletion<M extends HostedCompletionMatch>({ match, list }: HostedCompletionConfig<M>): Extension {
+export function hostedCompletion<M extends HostedCompletionMatch>({ match, opensOnCaretMove = true, list }: HostedCompletionConfig<M>): Extension {
const plugin = ViewPlugin.fromClass(class {
private readonly list: HostedCompletionList<M>;
/** Where the open list's match starts in the document, or `-1` while it is closed. */
@@ -113,7 +119,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list
}
if (update.docChanged || update.selectionSet || update.focusChanged) {
- this.sync();
+ this.sync(update.docChanged);
}
}
@@ -126,7 +132,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list
this.explicit = true;
this.dismissedAt = -1;
this.from = -1;
- this.sync();
+ this.sync(true);
// Nothing to complete here, so the key goes on to the editor's own completion.
if (this.from < 0) {
return false;
@@ -157,7 +163,8 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list
this.list.destroy?.();
}
- private sync() {
+ /** `typed`: the document changed, as typing or a commit does, rather than only the caret. */
+ private sync(typed: boolean) {
const found = this.view.hasFocus ? matchAt(this.view.state, match, this.explicit) : null;
if (found?.from !== this.dismissedAt) {
this.dismissedAt = -1;
@@ -173,6 +180,10 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list
if (found.from === this.from && found.before === this.before) {
return;
}
+ if (!typed && !opensOnCaretMove && found.from !== this.from) {
+ this.close();
+ return;
+ }
this.from = found.from;
this.before = found.before;