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
feat(markdown): link notes with @, as text notes do
Elian Doranaa5d3956daa5
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsxindex f6616bf987..af215cbfdb 100644--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx@@ -24,7 +24,7 @@ import { extractHighlightsFromStaticHtml, type RawHighlight } from "../../sidebaimport SplitEditor from "../helpers/SplitEditor";import { ReadOnlyTextContent } from "../text/ReadOnlyText";import { TypeWidgetProps } from "../type_widget";-import { useSlashCommands } from "./completions";+import { useMarkdownCompletions } from "./completions";import { insertText, replaceSelection, uploadImageAndInsert } from "./editor_utils";const marked = new Marked({ breaks: true, gfm: true });@@ -103,7 +103,7 @@ export default function Markdown(props: TypeWidgetProps) {usePublishHighlights(props.noteContext, editorView, highlights, props.note);useImageDrop(props.note, editorView);useTextCommands(props.parentComponent, editorView);- useSlashCommands(props.parentComponent, editorView, props.note);+ useMarkdownCompletions(props.parentComponent, editorView, props.note, () => props.noteContext?.notePath);useMarkdownKeymap(editorView);const ctx = useMemo<MarkdownContextValue>(diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.tsindex 4b22d2f660..a602bfc4dd 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts@@ -10,10 +10,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type FNote from "../../../entities/fnote";import mime_types from "../../../services/mime_types.js";+import type { NoteSuggestionOptions, Suggestion } from "../../../services/note_autocomplete";import type { TypeWidgetProps } from "../type_widget";-import { buildCodeFenceOptions, buildSlashCommands, buildTaskItemInsert, codeFenceCompletionSource, isClosingFence, parseCodeFencePrefix, slashCommandAt, useSlashCommands } from "./completions";+import { buildCodeFenceOptions, buildSlashCommands, buildTaskItemInsert, codeFenceCompletionSource, isClosingFence, markdownCompletionAt, parseCodeFencePrefix, useMarkdownCompletions } from "./completions";// The hook's two asynchronous sources of menu entries, stubbed so mounting it needs no server.+const { getNoteSuggestions, createNoteFromSuggestion } = vi.hoisted(() => ({+ getNoteSuggestions: vi.fn<(term: string, options?: NoteSuggestionOptions) => Promise<Suggestion[]>>(async () => []),+ createNoteFromSuggestion: vi.fn<(suggestion: Suggestion, childParentNotePath?: string | null) => Promise<string | undefined>>()+}));+vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../../services/note_autocomplete")>(),+ getNoteSuggestions,+ createNoteFromSuggestion+}));+vi.mock("../code/snippets", async (importOriginal) => ({...await importOriginal<typeof import("../code/snippets")>(),useCodeSnippets: () => ({ current: [] })@@ -155,19 +166,28 @@ describe("codeFenceCompletionSource", () => {});});-describe("slashCommandAt", () => {+describe("markdownCompletionAt", () => {/** What is found with the caret at `pos`, or at the end. */function at(doc: string, pos = doc.length) {const state = EditorState.create({ doc, extensions: [ markdown() ], selection: { anchor: pos } });ensureSyntaxTree(state, doc.length);const line = state.doc.lineAt(pos);- return slashCommandAt(line.text.slice(0, pos - line.from), false, state);+ return markdownCompletionAt(line.text.slice(0, pos - line.from), false, state);}it("finds a command at the start of a line or after whitespace, from its slash, by what follows it", () => {- expect(at("/")).toEqual({ from: 0, query: "" });- expect(at("some text /todo:in-progress")).toEqual({ from: 10, query: "todo:in-progress" });- expect(at("first\n /ta")).toEqual({ from: 2, query: "ta" });+ expect(at("/")).toEqual({ kind: "command", from: 0, query: "" });+ expect(at("some text /todo:in-progress")).toEqual({ kind: "command", from: 10, query: "todo:in-progress" });+ expect(at("first\n /ta")).toEqual({ kind: "command", from: 2, query: "ta" });+ });++ it("finds a note at the start of a line or after whitespace, from its @, by what follows it", () => {+ expect(at("@")).toEqual({ kind: "note", from: 0, query: "" });+ expect(at("see @Alp")).toEqual({ kind: "note", from: 4, query: "Alp" });+ // An address is no mention, and a space ends one.+ expect(at("mail [email protected]")).toBeNull();+ expect(at("see @Alpha ")).toBeNull();+ expect(at("text `a @` b", 9)).toBeNull();});it("finds none inside a word, past a space, or in code", () => {@@ -247,7 +267,7 @@ describe("buildSlashCommands", () => {});});-describe("useSlashCommands", () => {+describe("useMarkdownCompletions", () => {let container: HTMLElement;beforeEach(() => {@@ -263,7 +283,7 @@ describe("useSlashCommands", () => {/** Mounts the hook against `editorView`. */function mount(editorView: VanillaCodeMirror) {function Probe() {- useSlashCommands({} as TypeWidgetProps["parentComponent"], editorView, { noteId: "n1" } as FNote);+ useMarkdownCompletions({} as TypeWidgetProps["parentComponent"], editorView, { noteId: "n1" } as FNote, () => "root/parent");return null;}@@ -275,11 +295,11 @@ describe("useSlashCommands", () => {const setCompletionSource = vi.fn();mount({ setNamedExtension, setCompletionSource } as unknown as VanillaCodeMirror);- expect(setNamedExtension).toHaveBeenCalledExactlyOnceWith("slashCommands", expect.anything());+ expect(setNamedExtension).toHaveBeenCalledExactlyOnceWith("markdownCompletions", expect.anything());expect(setCompletionSource).toHaveBeenCalledExactlyOnceWith("markdownCodeFence", expect.any(Function));act(() => render(null, container));- expect(setNamedExtension).toHaveBeenLastCalledWith("slashCommands", []);+ expect(setNamedExtension).toHaveBeenLastCalledWith("markdownCompletions", []);expect(setCompletionSource).toHaveBeenLastCalledWith("markdownCodeFence", null);});@@ -306,4 +326,43 @@ describe("useSlashCommands", () => {act(() => render(null, container));editor.destroy();});++ it("lists the notes for what follows an @, as the text editor does, and links the one picked or created", async () => {+ getNoteSuggestions.mockResolvedValue([+ { notePath: "root/projects/abc123", noteTitle: "Alpha", notePathTitle: "Projects / Alpha", highlightedNotePathTitle: "<b>Al</b>pha" },+ { action: "create-child-note", noteTitle: "Al", parentNoteId: "parent", highlightedNotePathTitle: "Create child note" }+ ]);+ const parent = document.createElement("div");+ document.body.append(parent);+ const editor = new VanillaCodeMirror({ parent });+ mount(editor);+ editor.focus();+ const rows = () => [ ...document.querySelectorAll(".note-autocomplete-menu [role=option]") ];+ const press = (key: string) => editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));++ editor.dispatch({ changes: { from: 0, insert: "see @Al" }, selection: { anchor: 7 } });+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ // At most ten notes, and creation under the note being edited.+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("Al", { allowCreatingNotes: true, limit: 10 });++ // Opened on the best match, so Enter links it.+ press("Enter");+ await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]]"));++ // A note created is linked once it exists, past the dialog taking the focus.+ let created: (notePath: string | undefined) => void = () => {};+ createNoteFromSuggestion.mockReturnValueOnce(new Promise((resolve) => { created = resolve; }));+ editor.dispatch({ changes: { from: 14, insert: " @Al" }, selection: { anchor: 18 } });+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press("ArrowDown");+ await new Promise((resolve) => setTimeout(resolve, 0));+ press("Enter");+ await vi.waitFor(() => expect(createNoteFromSuggestion).toHaveBeenCalledWith(expect.objectContaining({ action: "create-child-note" }), "root/parent"));+ editor.contentDOM.blur();+ created("root/parent/new1");+ await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]] [[new1]]"));++ act(() => render(null, container));+ editor.destroy();+ });});diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.tsx b/apps/client/src/widgets/type_widgets/markdown/completions.tsxindex 08cda7f1e0..7906edde87 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx@@ -24,7 +24,7 @@ import type FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";import mime_types from "../../../services/mime_types";import { getTaskStateDefinitions } from "../../../services/task_states";-import { type CommandEntry, CommandMentionList, createHostedList, filterCommandEntries } from "../../react/NoteAutocomplete";+import { type CommandEntry, CommandMentionList, createHostedList, filterCommandEntries, NoteMentionList } from "../../react/NoteAutocomplete";import { type CodeSnippet, SLASH_COMMAND_REGEX, useCodeSnippets } from "../code/snippets";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";import type { TypeWidgetProps } from "../type_widget";@@ -36,10 +36,11 @@ export interface SlashCommand extends CommandEntry {apply: HostedCompletionApply;}-/** The `/command` typed before the caret, from its `/`. */-export interface SlashCommandMatch {+/** A `/command` or an `@` note typed before the caret, from its `/` or its `@`. */+export interface MarkdownCompletionMatch {+ kind: "command" | "note";from: number;- /** What follows the `/`, which the list filters its commands by, as the text editor's does. */+ /** What follows the `/` or the `@`, which the list filters by, as the text editor's do. */query: string;}@@ -54,15 +55,23 @@ export interface SlashCommandContext {}/**- * Lists the `/` commands typed at the start of a line or after whitespace in the shared command- * list, as the text editor does, through `hostedCompletion()`. The code-fence languages stay with+ * Lists the `/` commands and the `@` notes typed at the start of a line or after whitespace in+ * the text editor's lists, through `hostedCompletion()`. A note picked is linked as `[[noteId]]`,+ * and one created goes under the note at `getNotePath()`. The code-fence languages stay with* CodeMirror's own completion.*/-export function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], editorView: VanillaCodeMirror | null, note: FNote) {- // Held in refs so the commands read the current note and parent component without registering+export function useMarkdownCompletions(+ parentComponent: TypeWidgetProps["parentComponent"],+ editorView: VanillaCodeMirror | null,+ note: FNote,+ getNotePath: () => string | null | undefined+) {+ // Held in refs so the lists read the current note and parent component without registering// the extension again.const noteRef = useRef(note);const parentRef = useRef(parentComponent);+ const getNotePathRef = useRef(getNotePath);+ getNotePathRef.current = getNotePath;// The user-configured todo task states (from the `_taskStates` subtree), loaded once.const taskStatesRef = useRef<TaskStateDef[]>([]);// Markdown snippets (#snippet code notes with a markdown MIME) plus generic plain-text snippets,@@ -86,10 +95,10 @@ export function useSlashCommands(parentComponent: TypeWidgetProps["parentComponesnippets: snippetsRef.current.filter((snippet) => snippet.noteId !== noteRef.current.noteId)});// Bridges the codemirror package's own @codemirror/state identity, as for the sources below.- type CmSlashCommandMatcher = Parameters<typeof hostedCompletion<SlashCommandMatch>>[0]["match"];- editorView.setNamedExtension("slashCommands", hostedCompletion({- match: slashCommandAt as unknown as CmSlashCommandMatcher,- list: () => createSlashCommandList(commands)+ type CmMarkdownMatcher = Parameters<typeof hostedCompletion<MarkdownCompletionMatch>>[0]["match"];+ editorView.setNamedExtension("markdownCompletions", hostedCompletion({+ match: markdownCompletionAt as unknown as CmMarkdownMatcher,+ list: () => createMarkdownCompletionList(commands, () => getNotePathRef.current())}));// CodeMirror allows one `override` config per editor, so sources go through// `setCompletionSource` instead of each adding its own `autocompletion()`.@@ -98,27 +107,32 @@ export function useSlashCommands(parentComponent: TypeWidgetProps["parentComponeeditorView.setCompletionSource("markdownCodeFence", codeFenceCompletionSource as unknown as CmCompletionSource);return () => {- editorView.setNamedExtension("slashCommands", []);+ editorView.setNamedExtension("markdownCompletions", []);editorView.setCompletionSource("markdownCodeFence", null);};}, [editorView]);}/**- * The `/command` typed before the caret, at the start of a line or after whitespace, or `null` in a- * code block or a code span, where a `/` is part of the code.+ * The `/command` or the `@` note typed before the caret, at the start of a line or after whitespace,+ * or `null` in a code block or a code span, where either is part of the code.*/-export function slashCommandAt(before: string, _explicit: boolean, state: EditorState): SlashCommandMatch | null {- const typed = new RegExp(`${SLASH_COMMAND_REGEX.source}$`).exec(before);+export function markdownCompletionAt(before: string, _explicit: boolean, state: EditorState): MarkdownCompletionMatch | null {+ const command = COMMAND_TYPED.exec(before);+ const typed = command ?? NOTE_TYPED.exec(before);if (!typed) return null;for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(state.selection.main.head, -1); node; node = node.parent) {if (node.name.includes("Code")) return null;}- return { from: typed.index, query: typed[0].slice(1) };+ return { kind: command ? "command" : "note", from: typed.index, query: typed[0].slice(1) };}+const COMMAND_TYPED = new RegExp(`${SLASH_COMMAND_REGEX.source}$`);+/** An `@`, and the start of a note's title typed after it, up to a space. */+const NOTE_TYPED = /(?:^|(?<=\s))@[^\s@]*$/;+/*** The commands the `/` list offers, titled, described, found by the same words and drawn with the same* icons as the text editor's, where it has the command too. Each is found by the word typed after the@@ -346,18 +360,44 @@ function command(name: string, entry: Omit<SlashCommand, "id" | "apply">, apply:return { ...entry, id: name, aliases: [ name, ...(entry.aliases ?? []) ], apply };}-/** The `/` list, drawn as the text editor's, which runs the command picked on the typed `/command`. */-function createSlashCommandList(commands: () => SlashCommand[]) {- return createHostedList<HostedCompletionState<SlashCommandMatch>>((state, list) => (- <CommandMentionList<SlashCommand>- key={state.match.from}- {...list}- query={state.match.query}- source={async (query) => filterCommandEntries(commands(), query)}- className="slash-command-menu"- onPick={(entry) => state.commit(entry.apply)}- />- ));+/**+ * The `/` list or the `@` list, drawn as the text editor's: the first runs the command picked on the+ * typed `/command`, the second puts a link to the note picked or created in place of the `@` note.+ */+function createMarkdownCompletionList(commands: () => SlashCommand[], getParentNotePath: () => string | null | undefined) {+ return createHostedList<HostedCompletionState<MarkdownCompletionMatch>>((state, list) => {+ const { kind, from, query } = state.match;+ if (kind === "note") {+ return (+ <NoteMentionList+ key={`note:${from}`}+ {...list}+ query={query}+ allowCreatingNotes+ parentNotePath={getParentNotePath()}+ onPick={(notePath) => state.commit(typeof notePath === "string"+ ? noteLink(notePath)+ : notePath.then((path) => path ? noteLink(path) : undefined))}+ />+ );+ }++ return (+ <CommandMentionList<SlashCommand>+ key={`command:${from}`}+ {...list}+ query={query}+ source={async (typed) => filterCommandEntries(commands(), typed)}+ className="slash-command-menu"+ onPick={(entry) => state.commit(entry.apply)}+ />+ );+ });+}++/** The reference link to the note at `notePath`, which the preview renders with the note's title. */+function noteLink(notePath: string) {+ return `[[${notePath.split("/").pop()}]]`;}/**diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.htmlindex 870596a34f..f8d1f2b09d 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html@@ -211,6 +211,18 @@title, its keyword (as listed above) or a related word such as <code>latex</code> or <code>grid</code> findsit.</p><p>Note that slash commands only work outside of code blocks and inline code.</p>+<h4>Linking notes with <code>@</code></h4>+<p>As in <a class="reference-link" href="#root/_help_iPIMuisry3hd">Text</a> notes,+ typing <code>@</code> at the start of a line or after a space opens the note+ search. Picking a note replaces what was typed with a link to it in the+ Wikilinks-like format (<code>[[noteId]]</code>), which the preview shows+ as an <a class="reference-link" href="#root/_help_hrZ1D00cLbal">internal link</a> with+ the note's title.</p>+<p>The search runs on the text typed after the <code>@</code> up to the next+ space. If no note fits, the list offers to create one, as a child of the+ Markdown note or in the inbox; the link is inserted once the note is created.</p>+<p>Like slash commands, <code>@</code> does nothing inside code blocks and+ inline code.</p><h4>Code block language auto-completion</h4><p>Starting with v0.104.0, typing ``` to insert a code block will automaticallyopen a list of suggested language types which have syntax highlighting.</p>diff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.mdindex 8c90d50e41..d1aa40512c 100644--- a/docs/User Guide/User Guide/Note Types/Markdown.md+++ b/docs/User Guide/User Guide/Note Types/Markdown.md@@ -175,6 +175,14 @@ The list shows each command by its title, as in Text notes. Typing a command's tNote that slash commands only work outside of code blocks and inline code.+#### Linking notes with `@`++As in <a class="reference-link" href="Text.md">Text</a> notes, typing `@` at the start of a line or after a space opens the note search. Picking a note replaces what was typed with a link to it in the Wikilinks-like format (`[[noteId]]`), which the preview shows as an <a class="reference-link" href="Text/Links/Internal%20(reference)%20links.md">internal link</a> with the note's title.++The search runs on the text typed after the `@` up to the next space. If no note fits, the list offers to create one, as a child of the Markdown note or in the inbox; the link is inserted once the note is created.++Like slash commands, `@` does nothing inside code blocks and inline code.+#### Code block language auto-completionStarting with v0.104.0, typing \`\`\` to insert a code block will automatically open a list of suggested language types which have syntax highlighting.diff --git a/packages/codemirror/src/extensions/hosted_completion.spec.ts b/packages/codemirror/src/extensions/hosted_completion.spec.tsindex cb0985b85a..0ca40c8c12 100644--- a/packages/codemirror/src/extensions/hosted_completion.spec.ts+++ b/packages/codemirror/src/extensions/hosted_completion.spec.ts@@ -115,6 +115,51 @@ describe("hostedCompletion", () => {expect(editor?.state.doc.toString()).toBe("~author #book\nabc123 x def456");});+ it("puts what a promise settles on in place of the match once it settles, past the list closing", async () => {+ const { list, shown } = build();+ let resolveLink: (text: string | undefined) => void = () => {};++ type("see @ne");+ await vi.waitFor(() => expect(shown()?.match.query).toBe("ne"));+ shown()?.commit(new Promise<string | undefined>((resolve) => { resolveLink = resolve; }));+ expect(list.hide).toHaveBeenCalledOnce();++ // A dialog takes the focus meanwhile, and the text typed stays, the list closed on it.+ editor?.contentDOM.blur();+ editor?.dispatch({ changes: { from: 0, insert: "I " } });+ editor?.focus();+ await settle();+ expect(list.show).toHaveBeenCalledOnce();++ resolveLink("[[new]]");+ await vi.waitFor(() => expect(editor?.state.doc.toString()).toBe("I see [[new]]"));++ // Settled on nothing, the text stays for good.+ type(" @x");+ await vi.waitFor(() => expect(shown()?.match.query).toBe("x"));+ shown()?.commit(Promise.resolve<string | undefined>(undefined));+ await settle();+ expect(editor?.state.doc.toString()).toBe("I see [[new]] @x");+ // And so does it where the promise fails.+ type(" @z");+ await vi.waitFor(() => expect(shown()?.match.query).toBe("z"));+ shown()?.commit(Promise.reject(new Error("canceled")));+ await settle();+ expect(editor?.state.doc.toString()).toBe("I see [[new]] @x @z");+ editor?.dispatch({ changes: { from: 16, to: 19 }, selection: EditorSelection.cursor(16) });++ // Settling past the editor's end does nothing.+ type(" @y");+ await vi.waitFor(() => expect(shown()?.match.query).toBe("y"));+ shown()?.commit(new Promise<string | undefined>((resolve) => { resolveLink = resolve; }));+ const view = editor;+ editor = undefined;+ view?.destroy();+ resolveLink("[[late]]");+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(view?.state.doc.toString()).toBe("I see [[new]] @x @y");+ });+it("forwards the keys to the open list, which takes them from the field", async () => {const onArrowDown = vi.fn(() => true);const { list, shown } = build({ onArrowDown });diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.tsindex 1d09f1c75c..e6312cba84 100644--- a/packages/codemirror/src/extensions/hosted_completion.ts+++ b/packages/codemirror/src/extensions/hosted_completion.ts@@ -22,9 +22,10 @@ export interface HostedCompletionState<M extends HostedCompletionMatch> {editable: HTMLElement;/*** Replaces what stands between the match's `from` and the caret with `insert`, as a pick does,- * or runs `insert` on that range.+ * or runs `insert` on that range. For a promise, the list closes and the text stays until it+ * settles, past the editor losing the focus, and stays for good where it settles on `undefined`.*/- commit(insert: string | HostedCompletionApply): void;+ commit(insert: string | HostedCompletionApply | Promise<string | undefined>): void;/*** Points the editor at the list's highlighted entry through `aria-activedescendant`, by the id* of the entry's element, or at none for `null`. Once the list closes, it points at none.@@ -79,6 +80,9 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listprivate explicit = false;/** Where the match Escape closed the list on starts, which keeps it closed. */private dismissedAt = -1;+ /** The text that commits waiting on a promise replace, mapped through the edits since. */+ private readonly pending = new Set<{ from: number; to: number }>();+ private destroyed = false;constructor(private readonly view: EditorView) {this.list = list(view);@@ -89,6 +93,13 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list// With `assoc` 1, so text inserted right before the match leaves it on the match.this.dismissedAt = update.changes.mapPos(this.dismissedAt, 1);}+ if (update.docChanged) {+ // Text typed right before or after a waiting commit's range stays outside it.+ for (const range of this.pending) {+ range.from = update.changes.mapPos(range.from, 1);+ range.to = update.changes.mapPos(range.to, -1);+ }+ }if (update.docChanged || update.selectionSet || update.focusChanged) {this.sync();@@ -128,6 +139,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list}destroy() {+ this.destroyed = true;this.setActiveDescendant(null);this.list.hide();this.list.destroy?.();@@ -139,7 +151,9 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listthis.dismissedAt = -1;}- if (!found || this.dismissedAt >= 0) {+ // A match a commit waits on stays closed too, until the commit replaces it.+ const waiting = found && [ ...this.pending ].some((range) => range.from === found.from);+ if (!found || this.dismissedAt >= 0 || waiting) {this.close();return;}@@ -175,7 +189,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list});}- private commit(from: number, insert: string | HostedCompletionApply) {+ private commit(from: number, insert: string | HostedCompletionApply | Promise<string | undefined>) {if (this.from !== from) {return;}@@ -185,6 +199,10 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listinsert(this.view, from, this.view.state.selection.main.head);return;}+ if (insert instanceof Promise) {+ void this.commitWhenSettled(from, insert);+ return;+ }const text = insert;this.view.dispatch({@@ -194,6 +212,25 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list});}+ /** Closes the list, which stays closed on the match, and replaces the match once `insert` settles. */+ private async commitWhenSettled(from: number, insert: Promise<string | undefined>) {+ const range = { from, to: this.view.state.selection.main.head };+ this.pending.add(range);+ this.close();++ const text = await insert.catch(() => undefined);+ this.pending.delete(range);+ if (text === undefined || this.destroyed) {+ return;+ }++ this.view.dispatch({+ changes: { from: range.from, to: range.to, insert: text },+ selection: { anchor: range.from + text.length },+ userEvent: "input.complete"+ });+ }+private close() {this.explicit = false;if (this.from < 0) {