Skip to content

Build your personal knowledge base with Trilium Notes

fix(markdown): keep the completions' note links and image uploads whole

Elian Doran5c97b9858989
diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
index 2c12e67484..317d80d3a1 100644
--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
@@ -25,6 +25,12 @@ vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({
createNoteFromSuggestion
}));
+const { uploadImageAndInsert } = vi.hoisted(() => ({ uploadImageAndInsert: vi.fn() }));
+vi.mock("./editor_utils", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./editor_utils")>(),
+ uploadImageAndInsert
+}));
+
vi.mock("../code/snippets", async (importOriginal) => ({
...await importOriginal<typeof import("../code/snippets")>(),
useCodeSnippets: () => ({ current: [] })
@@ -201,6 +207,9 @@ describe("markdownCompletionAt", () => {
expect(at("[[My @Al")).toEqual({ kind: "note", from: 5, query: "Al" });
expect(at("@My [[Al")).toEqual({ kind: "note", from: 4, query: "Al" });
expect(at("`[[Al` b", 5)).toBeNull();
+ // A `/` inside an open link is part of the title; after an `@` it opens the commands, as in a text note.
+ expect(at("[[my /link")).toEqual({ kind: "note", from: 0, query: "my /link" });
+ expect(at("@one /table")).toEqual({ kind: "command", from: 5, query: "table" });
expect(at("text `a @` b", 9)).toBeNull();
});
@@ -225,12 +234,14 @@ describe("buildSlashCommands", () => {
afterEach(() => editor.destroy());
+ let currentNote = { noteId: "first" } as FNote;
+
const todo = (name: string, markdownSymbol: string): TaskStateDef => ({ name, title: name, markdownSymbol, isCompleted: false, icon: `bx bx-${name}` });
function commands(taskStates: TaskStateDef[] = []) {
return buildSlashCommands({
parentComponent: { triggerCommand } as unknown as TypeWidgetProps["parentComponent"],
- note: {} as FNote,
+ getNote: () => currentNote,
editorView: editor,
taskStates,
snippets: [ { noteId: "s1", title: "Greeting", description: "Says hello", content: "Hello!" } ]
@@ -275,6 +286,23 @@ describe("buildSlashCommands", () => {
expect(editor.state.sliceDoc(from, to)).toBe("markdown_slash_commands.placeholders.table_column");
});
+ it("uploads an image picked to the note shown once the file arrives", () => {
+ let picker: HTMLInputElement | undefined;
+ const click = vi.spyOn(HTMLInputElement.prototype, "click").mockImplementation(function (this: HTMLInputElement) { picker = this; });
+ currentNote = { noteId: "first" } as FNote;
+
+ expect(run("image", "/image")).toBe("");
+ expect(picker?.accept).toBe("image/*");
+
+ currentNote = { noteId: "second" } as FNote;
+ const file = new File([ "x" ], "a.png", { type: "image/png" });
+ if (!picker) throw new Error("no file picker opened");
+ Object.defineProperty(picker, "files", { value: [ file ] });
+ picker.dispatchEvent(new Event("change"));
+ expect(uploadImageAndInsert).toHaveBeenCalledExactlyOnceWith(editor, currentNote, file);
+ click.mockRestore();
+ });
+
it("removes the typed command before running one of the text editor's commands", () => {
expect(run("date", "On /date")).toBe("On ");
expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("insertDateTimeToText");
@@ -388,6 +416,15 @@ describe("useMarkdownCompletions", () => {
await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]] x"));
expect(editor.state.selection.main.head).toBe(14);
+ // So does a note created there, once it exists.
+ createNoteFromSuggestion.mockResolvedValueOnce("root/parent/new2");
+ editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "see [[Al]] x" }, selection: { anchor: 8 } });
+ await vi.waitFor(() => expect(rows()).toHaveLength(2));
+ press("ArrowDown");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ press("Enter");
+ await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[new2]] x"));
+
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.tsx
index 607fb265a4..40ae453ae5 100644
--- a/apps/client/src/widgets/type_widgets/markdown/completions.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx
@@ -47,7 +47,8 @@ export interface MarkdownCompletionMatch {
/** What the commands are built from, read again each time the list looks them up. */
export interface SlashCommandContext {
parentComponent: TypeWidgetProps["parentComponent"];
- note: FNote;
+ /** The note being edited, read when a command needs it, as switching notes reuses the editor. */
+ getNote(): FNote;
editorView: VanillaCodeMirror;
/** The user's task states, one `/todo:<state>` each where it has a Markdown marker. */
taskStates: TaskStateDef[];
@@ -90,7 +91,7 @@ export function useMarkdownCompletions(
const commands = () => buildSlashCommands({
parentComponent: parentRef.current,
- note: noteRef.current,
+ getNote: () => noteRef.current,
editorView,
taskStates: taskStatesRef.current,
snippets: snippetsRef.current.filter((snippet) => snippet.noteId !== noteRef.current.noteId)
@@ -120,9 +121,10 @@ export function useMarkdownCompletions(
* block or a code span, where any of them is part of the code.
*/
export function markdownCompletionAt(before: string, _explicit: boolean, state: EditorState): MarkdownCompletionMatch | null {
- const command = COMMAND_TYPED.exec(before);
const mention = NOTE_TYPED.exec(before);
const wikilink = WIKILINK_TYPED.exec(before);
+ // A `/` inside an open link is part of the title being typed.
+ const command = wikilink ? null : COMMAND_TYPED.exec(before);
const note = mention && wikilink
? (mention.index > wikilink.index ? mention : wikilink)
: mention ?? wikilink;
@@ -148,7 +150,7 @@ const WIKILINK_TYPED = /\[\[[^[\]]*$/;
* icons as the text editor's, where it has the command too. Each is found by the word typed after the
* `/` as well, such as `todo:done`.
*/
-export function buildSlashCommands({ parentComponent, note, editorView, taskStates, snippets }: SlashCommandContext): SlashCommand[] {
+export function buildSlashCommands({ parentComponent, getNote, editorView, taskStates, snippets }: SlashCommandContext): SlashCommand[] {
/** Removes the typed command, then runs one of the text editor's commands in its place. */
const runCommand = (name: Parameters<NonNullable<typeof parentComponent>["triggerCommand"]>[0]): HostedCompletionApply =>
(view, from, to) => {
@@ -180,7 +182,7 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
input.accept = "image/*";
input.addEventListener("change", () => {
const file = input.files?.[0];
- if (file) uploadImageAndInsert(editorView, note, file);
+ if (file) uploadImageAndInsert(editorView, getNote(), file);
});
input.click();
}),
@@ -387,7 +389,7 @@ function createMarkdownCompletionList(commands: () => SlashCommand[], getParentN
parentNotePath={getParentNotePath()}
onPick={(notePath) => state.commit(typeof notePath === "string"
? linkTo(notePath)
- : notePath.then((path) => path ? noteLink(path) : undefined))}
+ : notePath.then((path) => path ? linkTo(path) : undefined))}
/>
);
}