Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: add a preview for embedded Excalidraw attachments

Adorian Doran784225666ebd
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
index addf0fa84c..7196adf825 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
@@ -81,7 +81,8 @@
<li>A drawing canvas, inserted with <span class="tn-icon bx bx-pen"></span><em>Drawing canvas</em> in
the <span class="tn-icon cke cke-plus"></span><em>Insert</em> menu, is an
embed of a <code>Canvas.excalidraw</code> attachment that can be drawn on
- in place (see <em>Drawing canvases</em> in&nbsp;<a class="reference-link"
+ in place. An attached Excalidraw file (<code>.excalidraw</code>) is embedded
+ as a drawing canvas too (see <em>Drawing canvases</em> in&nbsp;<a class="reference-link"
href="#root/_help_nBAXQFj20hS1">Include Note</a>).</li>
<li>An embed gets the box size that suits the attachment, as a new included
note does (see <em>Box sizes</em> there). To change its size, select the
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
index 3171586220..4eae4c06e2 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
@@ -214,6 +214,10 @@
right-click it and choose <em>Unlock</em>. The caption of the image is kept,
but not its size, alignment or link. Only an image on its own line can
be converted, not one inside a paragraph. Undo brings the image back.</li>
+ <li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class="tn-icon cke cke-paper-clip"></span><em>Attach file</em> button
+ becomes a drawing canvas too, in a <em>Medium</em> box titled with the file
+ name. It starts with <em>Editable</em> off, so the drawing shows but cannot
+ be changed until <em>Editable</em> is turned on (see below).</li>
<li>To draw on a canvas that does not have the focus, click it first. Until
then, the mouse wheel and touch gestures scroll the note. The canvas then
has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars,
@@ -245,7 +249,7 @@
<li>The Excalidraw shape library is not saved for a drawing canvas.</li>
<li>Outside the editor, for example in a tooltip, when printing or in the
list of attachments, the drawing is shown as a picture. On a <a href="#root/_help_R9pX4DGra2Vt">shared page</a>,
- it appears as a link to download <code>Canvas.excalidraw</code>.</li>
+ it appears as a link to download its <code>.excalidraw</code> file.</li>
<li>A copy of a drawing canvas pasted in the same note shares the drawing
with the original, so a change to one shows in the other only after the
note is opened again. A copy pasted in another note gets a drawing of its
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
index 85eeee4435..238167d07b 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
@@ -43,7 +43,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref
* To attach files and embed them straight away, press the <span class="tn-icon cke cke-paper-clip"></span>_Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.
* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.
-* A drawing canvas, inserted with <span class="tn-icon bx bx-pen"></span>_Drawing canvas_ in the <span class="tn-icon cke cke-plus"></span>_Insert_ menu, is an embed of a `Canvas.excalidraw` attachment that can be drawn on in place (see _Drawing canvases_ in <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>).
+* A drawing canvas, inserted with <span class="tn-icon bx bx-pen"></span>_Drawing canvas_ in the <span class="tn-icon cke cke-plus"></span>_Insert_ menu, is an embed of a `Canvas.excalidraw` attachment that can be drawn on in place. An attached Excalidraw file (`.excalidraw`) is embedded as a drawing canvas too (see _Drawing canvases_ in <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>).
* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar, or the _Size_ submenu of its <span class="tn-icon bx bx-dots-vertical-rounded"></span>_More actions_ menu. A _Small_, _Medium_ or _Expandable_ embed can also be resized by dragging its handles (see _Resizing_ there).
* An embed can have a caption, as an included note can (see _Caption_ there).
* To show only the attachment, select the embed and press the <span class="tn-icon bx bx-window-alt"></span> (_Show title)_ button in its toolbar, as for an included note (see _Title_ there).
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index 54eb538c9c..b813cbed0a 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -121,6 +121,7 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-
* To insert a drawing canvas, open the <span class="tn-icon cke cke-plus"></span> _Insert_ menu of the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a> and choose <span class="tn-icon bx bx-pen"></span> _Drawing canvas_, above _Mermaid diagram_. It is also available as _Drawing canvas_ in the <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a>. The canvas is added empty and editable, in a _Medium_ box with its title hidden, and takes the focus, ready for drawing.
* To draw or write over an image, select the image and press the <span class="tn-icon bx bxs-pen"></span> _Convert image to a drawing canvas_ button of its toolbar. The image is replaced by an editable drawing canvas in a _Medium_ box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose _Unlock_. The caption of the image is kept, but not its size, alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.
+* An Excalidraw file (`.excalidraw`) attached with the <span class="tn-icon cke cke-paper-clip"></span>_Attach file_ button becomes a drawing canvas too, in a _Medium_ box titled with the file name. It starts with _Editable_ off, so the drawing shows but cannot be changed until _Editable_ is turned on (see below).
* To draw on a canvas that does not have the focus, click it first. Until then, the mouse wheel and touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.
* A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.
* To protect a finished drawing from accidental changes, select it and turn off the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or uncheck _Editable_ in its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu. The drawing can then be panned and zoomed but not changed, and its toolbar holds only the zoom buttons. To draw again, turn _Editable_ back on.
@@ -132,5 +133,5 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-
### Limitations
* The Excalidraw shape library is not saved for a drawing canvas.
-* Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture. On a [shared page](../../Advanced%20Usage/Sharing.md), it appears as a link to download `Canvas.excalidraw`.
+* Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture. On a [shared page](../../Advanced%20Usage/Sharing.md), it appears as a link to download its `.excalidraw` file.
* A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.
\ No newline at end of file
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
index 824cc2bb8c..f5febb56fd 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
@@ -148,14 +148,15 @@ describe("FileUploadCommand", () => {
it("inserts an embed placeholder per file, in the size the host gives its type and size", () => {
const getEmbedBoxSize = vi.fn((mime: string, _size: number) =>
- (mime === "image/png" ? "medium" : "tiny"));
+ (mime === "image/png" || mime === "application/vnd.excalidraw+json" ? "medium" : "tiny"));
installGlobMock({ getComponentByEl: () => ({ getEmbedBoxSize }) });
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
editor.execute("fileUpload", {
file: [
new File(["a"], "a.txt", { type: "text/plain" }),
- new File(["b"], "b.png", { type: "image/png" })
+ new File(["b"], "b.png", { type: "image/png" }),
+ new File(["c"], "c.excalidraw")
],
asEmbed: true
});
@@ -166,9 +167,14 @@ describe("FileUploadCommand", () => {
"</contentEmbed>" +
"<contentEmbed boxSize=\"medium\" uploadFileName=\"b.png\" uploadId=\"\\w+\">" +
"</contentEmbed>" +
+ "<contentEmbed boxSize=\"medium\" uploadFileName=\"c.excalidraw\" uploadId=\"\\w+\">" +
+ "</contentEmbed>" +
"<paragraph>\\[\\]bar</paragraph>$"
));
- expect(getEmbedBoxSize.mock.calls).toEqual([ [ "text/plain", 1 ], [ "image/png", 1 ] ]);
+ // A drawing picked from disk has no type, so the host gets the type it is saved with.
+ expect(getEmbedBoxSize.mock.calls).toEqual([
+ [ "text/plain", 1 ], [ "image/png", 1 ], [ "application/vnd.excalidraw+json", 1 ]
+ ]);
});
it("sizes the embeds medium for a host that names no size", () => {
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
index 7f26ebfa21..fa0b2e0a66 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
@@ -1,3 +1,4 @@
+import { getAttachedFileMime } from "@triliumnext/commons";
import {
Command,
FileRepository,
@@ -141,5 +142,6 @@ interface EmbedPlaceholderOptions {
/** The box size the host gives an embed of `file`, `medium` when the host does not say. */
function getEmbedBoxSize(editor: Editor, file: File) {
const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
- return component.getEmbedBoxSize?.(file.type, file.size) ?? "medium";
+ const mime = getAttachedFileMime(file.name, file.type);
+ return component.getEmbedBoxSize?.(mime, file.size) ?? "medium";
}
diff --git a/packages/commons/src/lib/notes.spec.ts b/packages/commons/src/lib/notes.spec.ts
index 6fc02cd59d..1150961563 100644
--- a/packages/commons/src/lib/notes.spec.ts
+++ b/packages/commons/src/lib/notes.spec.ts
@@ -1,8 +1,9 @@
import { describe, expect, it } from "vitest";
import {
- CALENDAR_EVENT_ICON, CANVAS_ATTACHMENT_MIME, GEO_LOCATION_ATTRIBUTE, GEO_SHAPE_ATTRIBUTE, getContentRendererGroup,
- getImageAttachmentTitle, getMimeIcon, getNoteContentType, getNoteIcon, isFullWidthNoteType,
+ CALENDAR_EVENT_ICON, CANVAS_ATTACHMENT_MIME, GEO_LOCATION_ATTRIBUTE, GEO_SHAPE_ATTRIBUTE,
+ getAttachedFileMime, getContentRendererGroup, getImageAttachmentTitle, getMimeIcon,
+ getNoteContentType, getNoteIcon, isFullWidthNoteType,
MAP_POSITION_ATTRIBUTE, MAP_SHAPE_ATTRIBUTE, NOTE_TYPE_ICONS, NOTE_TYPE_IMAGE_ATTACHMENTS,
parseMindMapNoteLink
} from "./notes.js";
@@ -364,3 +365,23 @@ describe("getNoteContentType", () => {
expect(getContentRendererGroup("constructor")).toBeUndefined();
});
});
+
+describe("getAttachedFileMime", () => {
+ it("saves an Excalidraw file as a canvas drawing and keeps the type of any other", () => {
+ expect([
+ getAttachedFileMime("Drawing.excalidraw", "application/octet-stream"),
+ getAttachedFileMime("Sketch.EXCALIDRAW", ""),
+ getAttachedFileMime("Drawing.excalidraw", "application/json"),
+ getAttachedFileMime("data.json", "application/json"),
+ getAttachedFileMime("excalidraw", "application/octet-stream"),
+ getAttachedFileMime("Drawing.excalidraw.md", "text/markdown")
+ ]).toEqual([
+ CANVAS_ATTACHMENT_MIME,
+ CANVAS_ATTACHMENT_MIME,
+ CANVAS_ATTACHMENT_MIME,
+ "application/json",
+ "application/octet-stream",
+ "text/markdown"
+ ]);
+ });
+});
diff --git a/packages/commons/src/lib/notes.ts b/packages/commons/src/lib/notes.ts
index b3a708b1cf..a557bed6c7 100644
--- a/packages/commons/src/lib/notes.ts
+++ b/packages/commons/src/lib/notes.ts
@@ -71,6 +71,14 @@ export const EMPTY_CANVAS_CONTENT = JSON.stringify({
appState: {}
});
+/**
+ * The media type of a file attached under `fileName`: {@link CANVAS_ATTACHMENT_MIME} for an
+ * Excalidraw file, so that it shows as a canvas drawing, else `mime`.
+ */
+export function getAttachedFileMime(fileName: string, mime: string) {
+ return fileName.toLowerCase().endsWith(".excalidraw") ? CANVAS_ATTACHMENT_MIME : mime;
+}
+
/**
* The note a mind map node's link points at, or `null` where it points somewhere else entirely.
*
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 205f212e68..54657eace0 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -1,3 +1,4 @@
+import { CANVAS_ATTACHMENT_MIME } from "@triliumnext/commons";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { getImageProvider } from "../../services/image_provider";
@@ -176,6 +177,33 @@ describe("Attachments API (core)", () => {
expect(res.body.url).toContain("viewMode=attachments");
});
+ it("saves an Excalidraw file as a canvas drawing, whatever type the browser sends", async () => {
+ const { noteId } = await createTextNote(api, { title: "Drawing upload target" });
+ const drawing = JSON.stringify({ type: "excalidraw", version: 2, elements: [] });
+
+ const res = await api.post<{ uploaded: boolean }>(
+ `/api/notes/${noteId}/attachments/upload`,
+ {
+ file: {
+ originalname: "Drawing.excalidraw",
+ mimetype: "application/octet-stream",
+ buffer: Buffer.from(drawing)
+ }
+ }
+ );
+ expect(res.body.uploaded).toBe(true);
+
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const [ attachment ] = list.body;
+ expect(attachment).toMatchObject({
+ role: "file", mime: CANVAS_ATTACHMENT_MIME, title: "Drawing.excalidraw"
+ });
+ const blob = await api.get<{ content: string }>(
+ `/api/attachments/${attachment.attachmentId}/blob`
+ );
+ expect(blob.body.content).toBe(drawing);
+ });
+
it("uploads an image file as an image attachment", async () => {
const { noteId } = await createTextNote(api, { title: "Image upload target" });
// Minimal 1x1 transparent PNG.
diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.ts
index 64026ad112..0e27294ae2 100644
--- a/packages/trilium-core/src/routes/api/attachments.ts
+++ b/packages/trilium-core/src/routes/api/attachments.ts
@@ -1,4 +1,6 @@
-import { ConvertAttachmentToNoteResponse, isAcceptedImageMime } from "@triliumnext/commons";
+import {
+ ConvertAttachmentToNoteResponse, getAttachedFileMime, isAcceptedImageMime
+} from "@triliumnext/commons";
import { ValidationError } from "../../errors";
import type { Request } from "../../http_interface";
@@ -88,7 +90,7 @@ async function uploadAttachment(req: Request<{ noteId: string }>) {
} else {
const attachment = note.saveAttachment({
role: "file",
- mime: file.mimetype,
+ mime: getAttachedFileMime(file.originalname, file.mimetype),
title: file.originalname,
content: file.buffer
});
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index 8c0e9e009c..5cb1de957a 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -285,6 +285,10 @@ describe("Files API (core)", () => {
expect(res.body).toEqual({ uploaded: true });
expect(becca.getAttachmentOrThrow(attachmentId).getContent().toString()).toBe("new-att");
expect(await revisionCount(noteId)).toBe(1);
+
+ const drawing = upload("{}", "application/octet-stream", "Drawing.excalidraw");
+ await api.put(`/api/attachments/${attachmentId}/file`, { file: drawing });
+ expect(becca.getAttachmentOrThrow(attachmentId).mime).toBe(CANVAS_ATTACHMENT_MIME);
});
it("reports a request that carries no file instead of writing an empty one", async () => {
diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.ts
index c915150c54..21e9dfc25a 100644
--- a/packages/trilium-core/src/routes/api/files.ts
+++ b/packages/trilium-core/src/routes/api/files.ts
@@ -1,3 +1,5 @@
+import { getAttachedFileMime } from "@triliumnext/commons";
+
import { Request, Response } from "../../http_interface";
import becca from "../../becca/becca";
import type BAttachment from "../../becca/entities/battachment";
@@ -86,7 +88,7 @@ function updateAttachment(req: Request<{ attachmentId: string }>) {
attachment.getNote().saveRevision();
- attachment.mime = file.mimetype.toLowerCase();
+ attachment.mime = getAttachedFileMime(file.originalname, file.mimetype.toLowerCase());
attachment.setContent(file.buffer, { forceSave: true });
return {
diff --git a/packages/trilium-core/src/services/import/single.spec.ts b/packages/trilium-core/src/services/import/single.spec.ts
index c9f079bb3a..dfefea889d 100644
--- a/packages/trilium-core/src/services/import/single.spec.ts
+++ b/packages/trilium-core/src/services/import/single.spec.ts
@@ -1,3 +1,4 @@
+import { CANVAS_ATTACHMENT_MIME } from "@triliumnext/commons";
import { beforeAll, describe, expect, it, vi } from "vitest";
import ExcelJS from "exceljs";
import fs from "fs";
@@ -355,12 +356,19 @@ describe("importAttachment", () => {
await getContext().init(async () => {
single.importAttachment(taskContext, { originalname: "Shot.png", mimetype: "image/png", buffer: imageBuffer }, rootNote);
single.importAttachment(taskContext, { originalname: "notes.unknownext", mimetype: "application/x-custom", buffer: Buffer.from("data") }, rootNote);
+ single.importAttachment(taskContext, {
+ originalname: "Imported.excalidraw",
+ mimetype: "application/octet-stream",
+ buffer: Buffer.from("{}")
+ }, rootNote);
});
expect(saveImageToAttachment).toHaveBeenCalledWith("root", imageBuffer, "Shot.png", true);
const attachment = rootNote.getAttachments().find((a) => a.title === "notes.unknownext");
expect(attachment).toMatchObject({ mime: "application/x-custom", role: "file" });
+ const drawing = rootNote.getAttachments().find((a) => a.title === "Imported.excalidraw");
+ expect(drawing).toMatchObject({ mime: CANVAS_ATTACHMENT_MIME, role: "file" });
} finally {
saveImageToAttachment.mockRestore();
}
diff --git a/packages/trilium-core/src/services/import/single.ts b/packages/trilium-core/src/services/import/single.ts
index 7a1c578d45..df3deed668 100644
--- a/packages/trilium-core/src/services/import/single.ts
+++ b/packages/trilium-core/src/services/import/single.ts
@@ -1,4 +1,4 @@
-import type { NoteType } from "@triliumnext/commons";
+import { getAttachedFileMime, type NoteType } from "@triliumnext/commons";
import type BNote from "../../becca/entities/bnote.js";
import imageService from "../../services/image.js";
@@ -292,7 +292,9 @@ function importHtml(taskContext: TaskContext<"importNotes">, file: File, parentN
}
function importAttachment(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
- const mime = mimeService.getMime(file.originalname) || file.mimetype;
+ const mime = getAttachedFileMime(
+ file.originalname, mimeService.getMime(file.originalname) || file.mimetype
+ );
if (mime.startsWith("image/") && typeof file.buffer !== "string") {
imageService.saveImageToAttachment(parentNote.noteId, file.buffer, file.originalname, taskContext.data?.shrinkImages);