Skip to content

Build your personal knowledge base with Trilium Notes

client/share pages: add support for displaying drawing canvases

Adorian Doran307fc34e66d2
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index e5e6a8be9c..cb2e612cf0 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -432,12 +432,13 @@ describe("getRenderedContent editable code", () => {
expect(props.preview.textContent).toBe("unsaved");
const getContent = () => "edited";
- props.editor.scheduleSave(getContent);
+ const onSaved = () => {};
+ props.editor.scheduleSave(getContent, onSaved);
props.editor.release();
expect(props.editor.canEdit()).toBe(true);
expect(noteEditor.canEdit).toHaveBeenCalledWith(note);
expect(noteEditor.getUnsavedContent).toHaveBeenCalledWith(note.noteId);
- expect(noteEditor.scheduleSave).toHaveBeenCalledWith(note, getContent);
+ expect(noteEditor.scheduleSave).toHaveBeenCalledWith(note, getContent, onSaved);
expect(noteEditor.release).toHaveBeenCalledWith(note.noteId);
const listener = () => {};
expect(props.editor.getSaveState()).toBe("saving");
@@ -457,10 +458,12 @@ describe("getRenderedContent editable code", () => {
expect(props.entity).toBe(att);
expect(props.content).toBe("{}");
expect(props.mime).toBe("application/json");
- props.editor.scheduleSave(() => "[]");
+ const onSaved = () => {};
+ props.editor.scheduleSave(() => "[]", onSaved);
props.editor.release();
expect(attachmentEditor.getUnsavedContent).toHaveBeenCalledWith(att.attachmentId);
- expect(attachmentEditor.scheduleSave).toHaveBeenCalledWith(att, expect.any(Function));
+ expect(attachmentEditor.scheduleSave)
+ .toHaveBeenCalledWith(att, expect.any(Function), onSaved);
expect(attachmentEditor.release).toHaveBeenCalledWith(att.attachmentId);
});
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 909f7f7147..6b341d89bd 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -118,8 +118,15 @@ export interface AttachmentEditor {
canEdit(attachment: FAttachment): boolean;
/** The content of the attachment that is not saved yet, or `undefined`. */
getUnsavedContent(attachmentId: string): string | undefined;
- /** Schedules a save of `attachment`. The save reads the content from `getContent`. */
- scheduleSave(attachment: FAttachment, getContent: () => string): void;
+ /**
+ * Schedules a save of `attachment`. The save reads the content from `getContent`, and runs
+ * `onSaved` with it once it saves, unless a newer change waits by then.
+ */
+ scheduleSave(
+ attachment: FAttachment,
+ getContent: () => string,
+ onSaved?: (content: string) => void
+ ): void;
/** Reads the unsaved content of the attachment now, before its editor unmounts. */
release(attachmentId: string): void;
}
@@ -130,8 +137,11 @@ export interface NoteEditor {
canEdit(note: FNote): boolean;
/** The content of the note that is not saved yet, or `undefined`. */
getUnsavedContent(noteId: string): string | undefined;
- /** Schedules a save of `note`. The save reads the content from `getContent`. */
- scheduleSave(note: FNote, getContent: () => string): void;
+ /**
+ * Schedules a save of `note`. The save reads the content from `getContent`, and runs `onSaved`
+ * with it once it saves, unless a newer change waits by then.
+ */
+ scheduleSave(note: FNote, getContent: () => string, onSaved?: (content: string) => void): void;
/** Reads the unsaved content of the note now, before its editor unmounts. */
release(noteId: string): void;
/** How the saving of the note goes, or `undefined` before its first change. */
@@ -453,7 +463,7 @@ export interface ContentEditor {
/** Whether the rendered content can change the note or attachment. */
canEdit(): boolean;
getUnsavedContent(): string | undefined;
- scheduleSave(getContent: () => string): void;
+ scheduleSave(getContent: () => string, onSaved?: (content: string) => void): void;
release(): void;
/**
* How the saving goes, for content that saves on its own rather than with the note that shows
@@ -472,7 +482,7 @@ export function bindAttachmentEditor(
return {
canEdit: () => editor.canEdit(attachment),
getUnsavedContent: () => editor.getUnsavedContent(attachment.attachmentId),
- scheduleSave: (getContent) => editor.scheduleSave(attachment, getContent),
+ scheduleSave: (getContent, onSaved) => editor.scheduleSave(attachment, getContent, onSaved),
release: () => editor.release(attachment.attachmentId)
};
}
@@ -490,7 +500,7 @@ function getContentEditor(
return editor && EDITABLE_NOTE_TYPES.has(entity.type) ? {
canEdit: () => editor.canEdit(entity),
getUnsavedContent: () => editor.getUnsavedContent(entity.noteId),
- scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),
+ scheduleSave: (getContent, onSaved) => editor.scheduleSave(entity, getContent, onSaved),
release: () => editor.release(entity.noteId),
getSaveState: () => editor.getSaveState(entity.noteId),
subscribeSaveState: (listener) => editor.subscribeSaveState(listener)
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx
index 3e88325527..d3abdb870c 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx
@@ -40,13 +40,17 @@ vi.mock("./persistence", () => ({
return {};
},
parseContent: (content: string) => JSON.parse(content),
- loadDrawingFiles: async () => ({ files: {}, referencedFileIds: new Set() })
-}));
-const { detailEditor, attachmentEditorMounts, canvasEditorMounts } = vi.hoisted(() => ({
- detailEditor: { canEdit: () => true, release: vi.fn() },
- attachmentEditorMounts: vi.fn(),
- canvasEditorMounts: vi.fn()
+ loadDrawingFiles: async () => ({ files: {}, referencedFileIds: new Set() }),
+ exportDrawingPicture
}));
+const { detailEditor, attachmentEditorMounts, canvasEditorMounts, exportDrawingPicture } =
+ vi.hoisted(() => ({
+ detailEditor: { canEdit: () => true, release: vi.fn() },
+ attachmentEditorMounts: vi.fn(),
+ canvasEditorMounts: vi.fn(),
+ exportDrawingPicture: vi.fn(async (_scene: unknown, _files: unknown, _isDark: boolean) =>
+ document.createElementNS("http://www.w3.org/2000/svg", "svg"))
+ }));
vi.mock("../text/attachment_saves", () => ({
useAttachmentEditor: () => {
useEffect(() => attachmentEditorMounts(), []);
@@ -930,8 +934,6 @@ describe("CanvasDrawing", () => {
describe("renderCanvasDrawingPicture", () => {
it("draws in the dark colors of a dark theme on screen, and in the light ones in print", async () => {
- vi.mocked(exportToSvg).mockImplementation(async () =>
- document.createElementNS("http://www.w3.org/2000/svg", "svg"));
const content = JSON.stringify({ elements: [ { id: "e1" } ], appState: {} });
const drawing = { getBlob: async () => ({ content }) } as never;
const { theme, device } = window.glob;
@@ -946,7 +948,7 @@ describe("renderCanvasDrawingPicture", () => {
window.glob.theme = theme;
expect(picture?.classList.contains("canvas-drawing-picture")).toBe(true);
- expect(vi.mocked(exportToSvg).mock.calls.map(([ { appState } ]) => appState?.exportWithDarkMode))
+ expect(exportDrawingPicture.mock.calls.map(([ , , isDark ]) => isDark))
.toEqual([ true, false, false ]);
});
});
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
index cc0b2c1514..3625cbc427 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
@@ -24,7 +24,9 @@ import { CanvasEditor } from "./Canvas";
import CanvasDrawingMenu from "./CanvasDrawingMenu";
import CanvasEmbedTools, { CanvasTools } from "./CanvasEmbedTools";
import { type DrawingView, getBoundedView, getCenteredView, getFittedView } from "./drawing_view";
-import { loadDrawingFiles, parseContent, useCanvasDrawingPersistence } from "./persistence";
+import {
+ exportDrawingPicture, loadDrawingFiles, parseContent, useCanvasDrawingPersistence
+} from "./persistence";
interface CanvasDrawingProps {
attachment: FAttachment;
@@ -350,23 +352,11 @@ function placePicture({ svg, x, y, width, height }: ScenePicture, view: DrawingV
export async function renderCanvasDrawingPicture(entity: FNote | FAttachment) {
const blob = await entity.getBlob();
const content = parseContent(blob?.content ?? "", entity);
- const elements = (content.elements ?? []).filter((element) => !element.isDeleted);
- if (!elements.length) {
- return null;
- }
-
- const svg = await exportToSvg({
- elements,
- appState: {
- ...content.appState,
- exportBackground: true,
- // Follows the theme as the editor does, except in print, which stays light.
- exportWithDarkMode: glob.device !== "print" && getEffectiveThemeStyle() === "dark"
- },
- files: (await loadDrawingFiles(entity, content)).files,
- exportPadding: 5
- });
- svg.classList.add("canvas-drawing-picture");
+ // Follows the theme as the editor does, except in print, which stays light.
+ const isDark = glob.device !== "print" && getEffectiveThemeStyle() === "dark";
+ const files = (await loadDrawingFiles(entity, content)).files;
+ const svg = await exportDrawingPicture(content, files, isDark);
+ svg?.classList.add("canvas-drawing-picture");
return svg;
}
diff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
index a6a9ab4df6..68edcf6cb5 100644
--- a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
@@ -12,6 +12,7 @@ const {
const { MAX_ZOOM, MIN_ZOOM } = await import("./drawing_view");
const { LIBRARY_SIDEBAR } = await import("./CanvasDrawingMenu");
const { FITTED_MENU_STYLES } = await import("./CanvasDrawing");
+const { DRAWING_DARK_FILTER, IMAGE_DARK_FILTER } = await import("./persistence");
/** The classes of Trilium that `CanvasDrawing.css` selects. Every other class is Excalidraw's. */
const TRILIUM_CLASSES = new Set([
@@ -30,8 +31,8 @@ const CODE_CLASSES = [
/**
* Checks what the canvas drawing relies on beyond Excalidraw's API: the classes and test ids it
- * selects, the translations of its toolbar, and the zoom it copies. A failure after an upgrade of
- * Excalidraw names the parts to review.
+ * selects, the translations of its toolbar, the zoom and the dark filters it copies. A failure
+ * after an upgrade of Excalidraw names the parts to review.
*/
describe("Excalidraw contract of the canvas drawing", () => {
// Vitest resolves the `development` export, so both folders come from `dist`.
@@ -89,6 +90,22 @@ describe("Excalidraw contract of the canvas drawing", () => {
expect(source).toContain("zoomOffsetScrollX=-(appLayerX-appLayerX/nextZoom)");
});
+ it("exports in dark colors with the filters that a saved picture applies", () => {
+ const compact = (text: string) => text.replace(/\s+/g, "");
+ const source = compact(readBundle(developmentDir, [ ".js" ]));
+
+ expect(source).toContain(compact(`var THEME_FILTER = "${DRAWING_DARK_FILTER}";`));
+ expect(source).toContain(compact(`var IMAGE_INVERT_FILTER = "${IMAGE_DARK_FILTER}";`));
+ expect(source).toContain(compact(
+ `if (exportWithDarkMode) { svgRoot.setAttribute("filter", THEME_FILTER); }`));
+ expect(source).toContain(compact(`
+ const use = svgRoot.ownerDocument.createElementNS(SVG_NS, "use");
+ use.setAttribute("href", \`#\${symbolId}\`);
+ if (renderConfig.exportWithDarkMode && fileData.mimeType !== MIME_TYPES.svg) {
+ use.setAttribute("filter", IMAGE_INVERT_FILTER);
+ }`));
+ });
+
it("opens the library in the sidebar that the main menu names", () => {
const source = readBundle(developmentDir, [ ".js" ]).replace(/\s+/g, "");
diff --git a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
index a5825fa5f9..c8315cfba5 100644
--- a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
@@ -97,7 +97,7 @@ async function getCanvasImageAttachments(note: FNote) {
}
/** Reads a blob as a base64 `data:` URL. */
-function blobToDataURL(blob: Blob): Promise<string> {
+export function blobToDataURL(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
diff --git a/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.spec.ts b/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.spec.ts
index 12c18c3f8e..0edc0ac96d 100644
--- a/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.spec.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.spec.ts
@@ -12,6 +12,8 @@ vi.mock("@excalidraw/excalidraw", () => ({
convertToExcalidrawElements: (skeletons: object[]) =>
skeletons.map((skeleton) => ({ id: "e1", ...skeleton }))
}));
+const saveDrawingPicture = vi.hoisted(() => vi.fn(async () => {}));
+vi.mock("./persistence", () => ({ saveDrawingPicture }));
const upload = vi.mocked(server.upload);
const remove = vi.mocked(server.remove);
@@ -46,6 +48,7 @@ describe("convertImageToDrawing", () => {
vi.restoreAllMocks();
upload.mockReset();
remove.mockReset();
+ saveDrawingPicture.mockClear();
});
it("attaches the image and a drawing that shows it, locked and centered", async () => {
@@ -84,6 +87,27 @@ describe("convertImageToDrawing", () => {
appState: {}
});
expect(toast.showError).not.toHaveBeenCalled();
+
+ await vi.waitFor(() => expect(saveDrawingPicture).toHaveBeenCalledOnce());
+ expect(saveDrawingPicture).toHaveBeenCalledWith(
+ { attachmentId: "att2", ownerId: "n1" },
+ await drawing.text(),
+ { [image.name]: {
+ id: image.name,
+ mimeType: "image/png",
+ dataURL: "data:image/png;base64,cG5n",
+ created: expect.any(Number)
+ } }
+ );
+ });
+
+ it("keeps the drawing when its picture cannot be saved", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ saveDrawingPicture.mockRejectedValueOnce(new Error("Offline."));
+
+ expect(await convertImageToDrawing("n1", "api/attachments/i1/image/a.png")).toBe("att2");
+ await vi.waitFor(() => expect(error).toHaveBeenCalledOnce());
+ expect(toast.showError).not.toHaveBeenCalled();
});
it("tells that it failed, and attaches nothing, for what is no picture", async () => {
diff --git a/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.ts b/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.ts
index 6c5d737eb4..092da6fcda 100644
--- a/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.ts
@@ -1,4 +1,5 @@
import type { FileId } from "@excalidraw/excalidraw/element/types";
+import type { BinaryFileData } from "@excalidraw/excalidraw/types";
import {
CANVAS_ATTACHMENT_MIME, CANVAS_ATTACHMENT_TITLE, EMPTY_CANVAS_CONTENT, imageExtensionForMime,
isAcceptedImageMime
@@ -8,11 +9,13 @@ import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
import { randomString } from "../../../services/utils";
+import { blobToDataURL } from "./image_attachments";
/**
* Attaches to the note a canvas drawing that shows the image at `src`, locked at its natural size,
* and answers with the ID of the drawing's attachment, or `null` once a toast tells that it failed.
* The drawing refers to the image by file ID, so the image is attached again, titled with that ID.
+ * The picture of the drawing saves in the background.
*/
export async function convertImageToDrawing(noteId: string, src: string, componentId?: string) {
let imageAttachmentId: string | undefined;
@@ -38,7 +41,11 @@ export async function convertImageToDrawing(noteId: string, src: string, compone
const drawing = new File([ content ], CANVAS_ATTACHMENT_TITLE, {
type: CANVAS_ATTACHMENT_MIME
});
- return await upload(noteId, drawing, componentId);
+ const drawingId = await upload(noteId, drawing, componentId);
+ savePicture({ attachmentId: drawingId, ownerId: noteId }, content, imageFile).catch(
+ (e: unknown) => console.error(`Could not save the picture of '${drawingId}'`, e)
+ );
+ return drawingId;
} catch (e) {
console.error(`Could not convert the image '${src}' to a drawing canvas`, e);
toast.showError(t("image.cannot-convert-to-drawing"));
@@ -50,6 +57,22 @@ export async function convertImageToDrawing(noteId: string, src: string, compone
}
}
+/** Saves the picture of a new drawing, whose only image is `image`, titled with its file ID. */
+async function savePicture(
+ drawing: { attachmentId: string; ownerId: string },
+ content: string,
+ image: File
+) {
+ const { saveDrawingPicture } = await import("./persistence");
+ const file = {
+ id: image.name,
+ mimeType: image.type,
+ dataURL: await blobToDataURL(image),
+ created: Date.now()
+ } as BinaryFileData;
+ await saveDrawingPicture(drawing, content, { [file.id]: file });
+}
+
async function fetchImage(src: string) {
const response = await fetch(src);
const image = await response.blob();
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
index 11f63b0d23..c517855580 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
@@ -10,6 +10,7 @@
* still-empty initializing scene as a change worth saving. Only subsequent loads (note
* switches on an already-initialized instance) may use `updateScene`.
*/
+import { exportToSvg } from "@excalidraw/excalidraw";
import { ExcalidrawImperativeAPI, ExcalidrawInitialDataState } from "@excalidraw/excalidraw/types";
import { type RefObject, render } from "preact";
import { act } from "preact/test-utils";
@@ -20,7 +21,9 @@ import type FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
import server from "../../../services/server";
import { buildNote } from "../../../test/easy-froca";
-import useCanvasPersistence, { useCanvasDrawingPersistence } from "./persistence";
+import useCanvasPersistence, {
+ saveDrawingPicture, useCanvasDrawingPersistence
+} from "./persistence";
interface FakeElement {
id: string;
@@ -346,7 +349,7 @@ describe("useCanvasDrawingPersistence", () => {
sceneElements = [ { ...loaded[0], version: 4 }, loaded[1] ];
change();
expect(editor.scheduleSave).toHaveBeenCalledTimes(1);
- const [ getContent ] = editor.scheduleSave.mock.calls[0];
+ const [ getContent, onSaved ] = editor.scheduleSave.mock.calls[0];
expect(JSON.parse(getContent())).toEqual({
type: "excalidraw",
version: 2,
@@ -358,6 +361,17 @@ describe("useCanvasDrawingPersistence", () => {
}
});
+ // Once saved, the drawing saves its picture, drawn with the images Excalidraw holds.
+ const post = vi.spyOn(server, "post").mockResolvedValue(undefined);
+ vi.mocked(exportToSvg).mockClear().mockResolvedValueOnce(svgOf("picture"));
+ await act(async () => onSaved(getContent()));
+ expect(vi.mocked(exportToSvg).mock.calls[0]?.[0].files).toBe(sceneFiles);
+ expect(post).toHaveBeenCalledExactlyOnceWith(
+ "notes/undefined/attachments?matchBy=title",
+ expect.objectContaining({ title: "a1.svg" })
+ );
+ post.mockRestore();
+
appState = { ...appState, viewBackgroundColor: "#ffc9c9" };
change();
change();
@@ -494,3 +508,108 @@ describe("useCanvasDrawingPersistence", () => {
expect(() => change()).not.toThrow();
});
});
+
+describe("saveDrawingPicture", () => {
+ const drawing = { attachmentId: "d1", ownerId: "n1" };
+ const IMAGE = { id: "f1", dataURL: "data:image/png;base64,AA==", mimeType: "image/png" };
+ const image = { id: "i1", type: "image", fileId: "f1" };
+
+ /** The saved pictures that `post` sent, with their whitespace collapsed. */
+ function getSavedPictures(post: { mock: { calls: unknown[][] } }) {
+ return post.mock.calls.map(([ , data ]) =>
+ (data as { content: string }).content.replace(/\s+/g, " "));
+ }
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.mocked(exportToSvg).mockReset();
+ });
+
+ it("saves the picture of a drawing, titled after it, in the colors of its page", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue(undefined);
+ vi.mocked(exportToSvg).mockResolvedValueOnce(svgOf("picture"));
+ const files = { f1: IMAGE };
+ const content = JSON.stringify({
+ elements: [ image, { id: "gone", type: "line", isDeleted: true } ],
+ appState: { viewBackgroundColor: "#ffc9c9" }
+ });
+
+ await saveDrawingPicture(drawing, content, files as never);
+ expect(exportToSvg).toHaveBeenCalledExactlyOnceWith({
+ elements: [ image ],
+ appState: {
+ viewBackgroundColor: "#ffc9c9", exportBackground: true, exportWithDarkMode: false
+ },
+ files,
+ exportPadding: 5
+ });
+ expect(post).toHaveBeenCalledExactlyOnceWith("notes/n1/attachments?matchBy=title", {
+ role: "image", mime: "image/svg+xml", title: "d1.svg", content: expect.any(String)
+ });
+ // Dark while its page is dark, as Excalidraw's dark export: pictures in it keep their colors.
+ const [ picture ] = getSavedPictures(post);
+ expect(picture).toMatch(/^<svg id="picture" class="trilium-drawing-picture"><style>/);
+ expect(picture).toContain("@media (prefers-color-scheme: dark) { "
+ + "svg.trilium-drawing-picture { filter: invert(93%) hue-rotate(180deg); } "
+ + `svg.trilium-drawing-picture image:not([href^="data:image/svg+xml"]) { `
+ + "filter: invert(100%) hue-rotate(180deg) saturate(1.25); } }</style></svg>");
+
+ // An empty drawing shows nothing.
+ await saveDrawingPicture(drawing, JSON.stringify({ elements: [] }));
+ expect(post.mock.calls[1]?.[1]).toEqual(expect.objectContaining({
+ content: `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`
+ }));
+ });
+
+ it("saves only the picture of the latest content, and none of a malformed one", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue(undefined);
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ let drawFirst: (svg: SVGSVGElement) => void = () => {};
+ vi.mocked(exportToSvg)
+ .mockImplementationOnce(() => new Promise((resolve) => { drawFirst = resolve; }))
+ .mockResolvedValueOnce(svgOf("second"));
+
+ const first = saveDrawingPicture(drawing, JSON.stringify({ elements: [ image ] }), {
+ f1: IMAGE
+ } as never);
+ const second = JSON.stringify({ elements: [ image, { ...image, id: "i2" } ] });
+ await saveDrawingPicture(drawing, second, { f1: IMAGE } as never);
+ drawFirst(svgOf("first"));
+ await first;
+ expect(getSavedPictures(post)).toEqual([ expect.stringMatching(/^<svg id="second"/) ]);
+
+ await saveDrawingPicture(drawing, "{");
+ expect(post).toHaveBeenCalledOnce();
+ expect(error).toHaveBeenCalledOnce();
+ });
+
+ it("loads from the note the images that are not loaded yet", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue(undefined);
+ vi.mocked(exportToSvg).mockResolvedValueOnce(svgOf("picture"));
+ const owner = buildNote({ title: "Owner" });
+ owner.getAttachmentsByRole = (async () => [
+ { attachmentId: "img1", title: "f1" }
+ ]) as never;
+ vi.stubGlobal("fetch", vi.fn(async () => ({
+ ok: true,
+ blob: async () => new Blob([ "ABC" ], { type: "image/png" })
+ })));
+
+ await saveDrawingPicture(
+ { attachmentId: "d1", ownerId: owner.noteId },
+ JSON.stringify({ elements: [ image ] })
+ );
+ expect(vi.mocked(exportToSvg).mock.calls[0]?.[0].files).toEqual({
+ f1: expect.objectContaining({ dataURL: "data:image/png;base64,QUJD" })
+ });
+ expect(post).toHaveBeenCalledOnce();
+ });
+});
+
+/** An empty SVG element for `exportToSvg()` to draw. */
+function svgOf(id: string) {
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ svg.id = id;
+ return svg;
+}
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
index 067ccef572..bf41718000 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -4,7 +4,7 @@ import {
AppState, BinaryFileData, BinaryFiles, ExcalidrawImperativeAPI, ExcalidrawInitialDataState,
ExcalidrawProps, LibraryItem
} from "@excalidraw/excalidraw/types";
-import { deferred, type DeferredPromise } from "@triliumnext/commons";
+import { deferred, type DeferredPromise, getDrawingPictureTitle } from "@triliumnext/commons";
import { RefObject } from "preact";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
@@ -446,7 +446,10 @@ export function useCanvasDrawingPersistence(
if (sceneVersion === currentSceneVersion.current && !isAppStateChanged) return;
currentSceneVersion.current = sceneVersion;
- editor.scheduleSave(() => serializeDrawing(api, referencedFileIds.current));
+ editor.scheduleSave(
+ () => serializeDrawing(api, referencedFileIds.current),
+ (content) => saveDrawingPicture(attachment, content, api.getFiles())
+ );
}
};
}
@@ -456,7 +459,10 @@ export function useCanvasDrawingPersistence(
* to by file ID, which the note that owns `entity` keeps as image attachments titled with that ID.
* `referencedFileIds` lists the latter.
*/
-export async function loadDrawingFiles(entity: FNote | FAttachment, content: CanvasContent) {
+export async function loadDrawingFiles(
+ entity: FNote | Pick<FAttachment, "ownerId">,
+ content: CanvasContent
+) {
const files: BinaryFiles = {};
for (const file of Object.values(content.files ?? {})) {
files[file.id] = file;
@@ -481,6 +487,102 @@ export async function loadDrawingFiles(entity: FNote | FAttachment, content: Can
return { files, referencedFileIds };
}
+/**
+ * The picture of the canvas drawing `scene` with the images `files`, as the list of attachments and
+ * shared pages show it, or `null` for an empty drawing.
+ */
+export async function exportDrawingPicture(
+ scene: CanvasContent,
+ files: BinaryFiles,
+ isDark: boolean
+) {
+ const elements = (scene.elements ?? []).filter((element) => !element.isDeleted);
+ if (!elements.length) {
+ return null;
+ }
+
+ return exportToSvg({
+ elements,
+ appState: { ...scene.appState, exportBackground: true, exportWithDarkMode: isDark },
+ files,
+ exportPadding: 5
+ });
+}
+
+/** The saved content that the latest picture of each canvas drawing comes from, by its ID. */
+const drawnPictureContents = new Map<string, string>();
+
+/** The picture of an empty canvas drawing. */
+const EMPTY_PICTURE = `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`;
+
+/** The filter that Excalidraw draws a drawing in dark colors with. */
+export const DRAWING_DARK_FILTER = "invert(93%) hue-rotate(180deg)";
+/** The filter that keeps the colors of a picture in a drawing drawn with `DRAWING_DARK_FILTER`. */
+export const IMAGE_DARK_FILTER = "invert(100%) hue-rotate(180deg) saturate(1.25)";
+
+/** The class of a saved picture, which scopes its own style. */
+const SAVED_PICTURE_CLASS = "trilium-drawing-picture";
+
+/**
+ * Draws a saved picture in the dark colors of Excalidraw while the page that shows it has a dark
+ * color scheme, with the filters of Excalidraw's dark export: the root inverted, the pictures in
+ * it, except SVG ones, inverted back.
+ */
+const SAVED_PICTURE_STYLE = `@media (prefers-color-scheme: dark) {
+ svg.${SAVED_PICTURE_CLASS} {
+ filter: ${DRAWING_DARK_FILTER};
+ }
+ svg.${SAVED_PICTURE_CLASS} image:not([href^="data:image/svg+xml"]) {
+ filter: ${IMAGE_DARK_FILTER};
+ }
+}`;
+
+/**
+ * Saves the picture of the canvas drawing in `drawing`, drawn from its saved `content`, as the
+ * image attachment that shared pages show in place of the drawing. The picture follows the light
+ * or dark color scheme of the page. `files` are the images of the drawing already loaded; the
+ * others load from the note.
+ */
+export async function saveDrawingPicture(
+ drawing: Pick<FAttachment, "attachmentId" | "ownerId">,
+ content: string,
+ files: BinaryFiles = {}
+) {
+ const { attachmentId, ownerId } = drawing;
+ drawnPictureContents.set(attachmentId, content);
+ try {
+ const scene = JSON.parse(content) as CanvasContent;
+ const isLoaded = (scene.elements ?? []).every((element) =>
+ !("fileId" in element) || !element.fileId || files[element.fileId]);
+ const picture = await exportDrawingPicture(
+ scene,
+ isLoaded ? files : (await loadDrawingFiles(drawing, scene)).files,
+ false
+ );
+ // A newer save draws a picture of its own.
+ if (drawnPictureContents.get(attachmentId) !== content) return;
+
+ if (picture) {
+ const style = picture.ownerDocument.createElementNS(picture.namespaceURI, "style");
+ style.textContent = SAVED_PICTURE_STYLE;
+ picture.classList.add(SAVED_PICTURE_CLASS);
+ picture.prepend(style);
+ }
+ await server.post(`notes/${ownerId}/attachments?matchBy=title`, {
+ role: IMAGE_ROLE,
+ mime: "image/svg+xml",
+ title: getDrawingPictureTitle(attachmentId),
+ content: picture?.outerHTML ?? EMPTY_PICTURE
+ });
+ } catch (e) {
+ console.error(`Could not save the picture of the canvas drawing '${attachmentId}'`, e);
+ } finally {
+ if (drawnPictureContents.get(attachmentId) === content) {
+ drawnPictureContents.delete(attachmentId);
+ }
+ }
+}
+
/**
* The content of a canvas drawing. Unlike a canvas note, a drawing keeps its images inline, except
* the ones it refers to by file ID.
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
index ba4e8a8f31..6edd702d3d 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
@@ -60,18 +60,21 @@ describe("AttachmentSaves", () => {
} ]);
});
- it("keeps a change made while a save runs", () => {
+ it("keeps a change made while a save runs, and reports only the last change saved", () => {
const { saves } = setUp();
- saves.scheduleSave(drawing, () => "saved");
+ const onSaved = vi.fn();
+ saves.scheduleSave(drawing, () => "saved", onSaved);
const sent = saves.collect();
- saves.scheduleSave(drawing, () => "changed meanwhile");
+ saves.scheduleSave(drawing, () => "changed meanwhile", onSaved);
saves.markSaved(sent);
expect(saves.getUnsavedContent("drawing1")).toBe("changed meanwhile");
+ expect(onSaved).not.toHaveBeenCalled();
saves.markSaved(saves.collect());
expect(saves.getUnsavedContent("drawing1")).toBeUndefined();
expect(saves.collect()).toStrictEqual([]);
+ expect(onSaved.mock.calls).toStrictEqual([ [ "changed meanwhile" ] ]);
});
it("ignores a save of other data", () => {
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
index bf2ccf9d39..ba23359fea 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
@@ -23,6 +23,8 @@ interface PendingSave<T> {
getContent?: () => string;
/** The content read when the editor went away. */
content?: string;
+ /** Runs with the content once it saves, unless a newer change waits by then. */
+ onSaved?: (content: string) => void;
/**
* Numbers the change, uniquely among all changes, so that a save drops only the change it
* sent, also when it is retried.
@@ -30,6 +32,14 @@ interface PendingSave<T> {
revision: number;
}
+/** A change that a save sent. */
+interface SentRevision {
+ id: string;
+ revision: number;
+ content: string;
+ onSaved?: (content: string) => void;
+}
+
/**
* The content changes that wait for a save, by the ID of the note or attachment they change.
* `T` is the changed entity, and `I` the item that `collectItems()` builds for each change.
@@ -37,7 +47,7 @@ interface PendingSave<T> {
abstract class PendingSaves<T, I extends object> {
protected pending = new Map<string, PendingSave<T>>();
private lastRevision = 0;
- private sentRevisions = new WeakMap<I, { id: string; revision: number }>();
+ private sentRevisions = new WeakMap<I, SentRevision>();
getUnsavedContent(id: string) {
const save = this.pending.get(id);
@@ -52,26 +62,38 @@ abstract class PendingSaves<T, I extends object> {
}
}
- /** Drops the changes that `items`, as returned by `collectItems()`, saved. */
+ /**
+ * Drops the changes that `items`, as returned by `collectItems()`, saved, and runs the
+ * `onSaved` of each.
+ */
markSaved(items: I[] | undefined) {
for (const item of items ?? []) {
const sent = this.sentRevisions.get(item);
if (sent && this.pending.get(sent.id)?.revision === sent.revision) {
this.pending.delete(sent.id);
+ sent.onSaved?.(sent.content);
}
}
}
- protected schedule(id: string, entity: T, getContent: () => string) {
- this.pending.set(id, { entity, getContent, revision: ++this.lastRevision });
+ protected schedule(
+ id: string,
+ entity: T,
+ getContent: () => string,
+ onSaved?: (content: string) => void
+ ) {
+ this.pending.set(id, { entity, getContent, onSaved, revision: ++this.lastRevision });
}
/** One item for each change, with the content read at the time of the call. */
protected collectItems(toItem: (id: string, entity: T, content: string) => I) {
const items: I[] = [];
for (const [ id, save ] of this.pending) {
- const item = toItem(id, save.entity, readContent(save));
- this.sentRevisions.set(item, { id, revision: save.revision });
+ const content = readContent(save);
+ const item = toItem(id, save.entity, content);
+ this.sentRevisions.set(item, {
+ id, revision: save.revision, content, onSaved: save.onSaved
+ });
items.push(item);
}
@@ -105,8 +127,12 @@ export default class AttachmentSaves
return !!this.noteId && attachment.ownerId === this.noteId;
}
- scheduleSave(attachment: FAttachment, getContent: () => string) {
- this.schedule(attachment.attachmentId, attachment, getContent);
+ scheduleSave(
+ attachment: FAttachment,
+ getContent: () => string,
+ onSaved?: (content: string) => void
+ ) {
+ this.schedule(attachment.attachmentId, attachment, getContent, onSaved);
this.scheduleUpdate();
}
@@ -143,8 +169,8 @@ export class NoteSaves extends PendingSaves<FNote, SavedNote> implements NoteEdi
return note.noteId !== this.getHostNoteId() && note.isContentAvailable();
}
- scheduleSave(note: FNote, getContent: () => string) {
- this.schedule(note.noteId, note, getContent);
+ scheduleSave(note: FNote, getContent: () => string, onSaved?: (content: string) => void) {
+ this.schedule(note.noteId, note, getContent, onSaved);
this.setSaveState(note.noteId, "unsaved");
this.scheduleUpdate();
}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index 03b6ee793e..0574bacc9a 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -72,6 +72,7 @@ class="image">
<li>Rendering for math equations.</li>
<li><a href="#root/_help_nBAXQFj20hS1">Including notes</a> (only if the included
notes are also shared).</li>
+ <li>Drawing canvases, shown as pictures at their own size.</li>
<li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode
and redrawn when the visitor switches it.</li>
</ul>
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 7196adf825..c941e178f0 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
@@ -110,8 +110,9 @@
</ul>
<p>An embed follows its attachment like a link does. Converting the attachment
into a note turns the embed into an included note. In a <a href="#root/_help_R9pX4DGra2Vt">shared note</a>,
- an embedded picture is displayed with its caption, and any other attachment,
- or a picture in a <em>Tiny</em> embed, appears as a link to download it.</p>
+ an embedded picture is displayed with its caption, a drawing canvas as
+ a picture of the drawing, and any other attachment, or a picture in a <em>Tiny</em> embed,
+ appears as a link to download it.</p>
<h2>Converting notes to attachments</h2>
<p><a class="reference-link" href="#root/_help_W8vYD3Q1zjCR">File</a>&nbsp;notes
can be easily converted to attachments of the parent note.</p>
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 d45641c598..d202996ca1 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
@@ -247,13 +247,22 @@
generated code.</li>
<li>In a <a href="#root/_help_CoFPLs3dRlXc">read-only note</a>, the drawing
shows as a still picture too.</li>
+ <li>On a <a href="#root/_help_R9pX4DGra2Vt">shared page</a>, the drawing is
+ shown as a picture at its own size, whatever the size of its box, in light
+ or dark colors to match the page. Each change to the drawing saves this
+ picture as an SVG image attachment of the note, also named with a generated
+ code.</li>
</ul>
<h3>Limitations</h3>
<ul>
<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 its <code>.excalidraw</code> file.</li>
+ list of attachments, the drawing is shown as a picture.</li>
+ <li>A drawing has no picture for shared pages until its first change, except
+ one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file,
+ a shared page shows a link to download the drawing instead.</li>
+ <li>In Safari, the picture of a drawing on a shared page follows the light
+ or dark appearance of the system rather than the theme chosen on the page.</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/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.ts
index 64c5569ecf..8beca3eeb8 100644
--- a/apps/server/src/services/notes.spec.ts
+++ b/apps/server/src/services/notes.spec.ts
@@ -287,17 +287,18 @@ describe("checkImageAttachments", () => {
}
});
- it("keeps the images that an embedded canvas drawing shows while it is embedded", () => {
+ it("keeps the images and the picture of a canvas drawing while it is embedded", () => {
const note = buildNote({
title: "Test",
attachments: [
{ id: "drawing1", ...DRAWING },
{ title: "f1.png", role: "image", mime: "image/png" },
- { title: "f2.png", role: "image", mime: "image/png" }
+ { title: "f2.png", role: "image", mime: "image/png" },
+ { title: "drawing1.svg", role: "image", mime: "image/svg+xml" }
]
});
mockAttachmentSaves(note);
- const [ drawing, shown, removed ] = note.getAttachments();
+ const [ drawing, shown, removed, picture ] = note.getAttachments();
setDrawingContent(drawing, "f1.png");
shown.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";
@@ -305,20 +306,23 @@ describe("checkImageAttachments", () => {
expect(drawing.utcDateScheduledForErasureSince).toBeFalsy();
expect(shown.utcDateScheduledForErasureSince).toBeNull();
expect(removed.utcDateScheduledForErasureSince).toBeTruthy();
+ expect(picture.utcDateScheduledForErasureSince).toBeFalsy();
checkImageAttachments(note, "<p>The drawing is gone.</p>");
expect(drawing.utcDateScheduledForErasureSince).toBeTruthy();
expect(shown.utcDateScheduledForErasureSince).toBeTruthy();
+ expect(picture.utcDateScheduledForErasureSince).toBeTruthy();
});
- it("copies with a foreign drawing the images the note lacks and keeps the rest", () => {
+ it("copies with a foreign drawing its picture and the images the note lacks", () => {
const source = buildNote({
title: "Source",
attachments: [
{ id: "foreignDrawing", ...DRAWING },
{ title: "f1.png", role: "image", mime: "image/png" },
{ title: "f2.png", role: "image", mime: "image/png" },
- { title: "unrelated.png", role: "image", mime: "image/png" }
+ { title: "unrelated.png", role: "image", mime: "image/png" },
+ { title: "foreignDrawing.svg", role: "image", mime: "image/svg+xml" }
]
});
const [ foreign, ...images ] = source.getAttachments();
@@ -338,6 +342,8 @@ describe("checkImageAttachments", () => {
const copies: BAttachment[] = [];
const setContent = vi.spyOn(BAttachment.prototype, "setContent")
.mockImplementation(function (this: BAttachment) {
+ // A saved attachment has an ID.
+ this.attachmentId ??= `copy${copies.length + 1}`;
copies.push(this);
});
const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ foreign ]);
@@ -347,7 +353,8 @@ describe("checkImageAttachments", () => {
expect(copies.map(({ ownerId, title }) => ({ ownerId, title }))).toEqual([
{ ownerId: target.noteId, title: "Canvas.excalidraw" },
- { ownerId: target.noteId, title: "f1.png" }
+ { ownerId: target.noteId, title: "f1.png" },
+ { ownerId: target.noteId, title: "copy1.svg" }
]);
expect(kept.utcDateScheduledForErasureSince).toBeNull();
} finally {
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index e03a7aa09d..ae7916b119 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -34,7 +34,7 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
<tbody>
<tr>
<th><a class="reference-link" href="../Note%20Types/Text.md">Text</a></th>
- <td><ul><li>Table of contents.</li><li>A link next to each heading, shown while the pointer is over the heading. Clicking it shows the address of the section in the address bar of the browser and copies it, to share a link to the section.</li><li>Syntax highlight of code blocks, in the language selected for each block and in the colors of the VS Code light or dark theme, following the page's mode. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
+ <td><ul><li>Table of contents.</li><li>A link next to each heading, shown while the pointer is over the heading. Clicking it shows the address of the section in the address bar of the browser and copies it, to share a link to the section.</li><li>Syntax highlight of code blocks, in the language selected for each block and in the colors of the VS Code light or dark theme, following the page's mode. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Drawing canvases, shown as pictures at their own size.</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
<td>&nbsp;</td>
</tr>
<tr>
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 238167d07b..080ab4c101 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
@@ -52,7 +52,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref
* To show an embed of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> (_Fullscreen)_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> (_Exit fullscreen)_ in the top-right corner, or <kbd>Esc</kbd>.
* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span>_Convert to link_ button in its toolbar. _Convert to link_ also ends the menu that right-clicking the title row of the embed or pressing its <span class="tn-icon bx bx-dots-vertical-rounded"></span>_More actions_ button opens.
-An embed follows its attachment like a link does. Converting the attachment into a note turns the embed into an included note. In a [shared note](../../Advanced%20Usage/Sharing.md), an embedded picture is displayed with its caption, and any other attachment, or a picture in a _Tiny_ embed, appears as a link to download it.
+An embed follows its attachment like a link does. Converting the attachment into a note turns the embed into an included note. In a [shared note](../../Advanced%20Usage/Sharing.md), an embedded picture is displayed with its caption, a drawing canvas as a picture of the drawing, and any other attachment, or a picture in a _Tiny_ embed, appears as a link to download it.
## Converting notes to attachments
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 6294898d60..50abf1fa48 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
@@ -130,9 +130,12 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-
* In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose _Full_, or show the title and press <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_.
* Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.
* In a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), the drawing shows as a still picture too.
+* On a [shared page](../../Advanced%20Usage/Sharing.md), the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.
### 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 its `.excalidraw` file.
+* Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.
+* A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached `.excalidraw` file, a shared page shows a link to download the drawing instead.
+* In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.
* 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/commons/src/lib/notes.ts b/packages/commons/src/lib/notes.ts
index a557bed6c7..a37b248679 100644
--- a/packages/commons/src/lib/notes.ts
+++ b/packages/commons/src/lib/notes.ts
@@ -62,6 +62,15 @@ export const CANVAS_ATTACHMENT_MIME = "application/vnd.excalidraw+json";
/** The title of the attachment a new canvas drawing is saved in. */
export const CANVAS_ATTACHMENT_TITLE = "Canvas.excalidraw";
+/**
+ * The title of the SVG image attachment that holds the picture of the canvas drawing saved in
+ * attachment `attachmentId`. The note that owns the drawing owns the picture, and shared pages show
+ * the picture in place of the drawing.
+ */
+export function getDrawingPictureTitle(attachmentId: string) {
+ return `${attachmentId}.svg`;
+}
+
/** The content of a new, empty canvas drawing. */
export const EMPTY_CANVAS_CONTENT = JSON.stringify({
type: "excalidraw",
diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.ts
index 0820adb7a8..c2b5c0aac6 100644
--- a/packages/trilium-core/src/services/import/zip.spec.ts
+++ b/packages/trilium-core/src/services/import/zip.spec.ts
@@ -12,7 +12,9 @@ import BNote from "../../becca/entities/bnote.js";
import noteService from "../notes.js";
import TaskContext from "../task_context.js";
import sql_init from "../sql_init.js";
-import { isLocalPreviewImageSrc, trimIndentation } from "@triliumnext/commons";
+import {
+ CANVAS_ATTACHMENT_MIME, isLocalPreviewImageSrc, trimIndentation
+} from "@triliumnext/commons";
import { getContext } from "../context.js";
const scriptDir = dirname(fileURLToPath(import.meta.url));
@@ -262,6 +264,40 @@ describe("processNoteContent", () => {
expect(content).not.toContain("embeddedPdf1");
});
+ it("titles the picture of an imported drawing after the new ID of the drawing", async () => {
+ const attachment = (attachmentId: string, title: string, role: string, mime: string) =>
+ ({ attachmentId, title, role, mime, dataFileName: `Sketch_${title}` });
+ const metaFile = {
+ formatVersion: 2,
+ appVersion: "0.0.0",
+ files: [{
+ noteId: "drawingNote1",
+ title: "Sketch",
+ type: "text",
+ mime: "text/html",
+ dataFileName: "Sketch.html",
+ attachments: [
+ attachment("drawing1", "Canvas.excalidraw", "file", CANVAS_ATTACHMENT_MIME),
+ attachment("picture1", "drawing1.svg", "image", "image/svg+xml")
+ ]
+ }]
+ };
+
+ const zipBuffer = await createZipBuffer({
+ "!!!meta.json": JSON.stringify(metaFile),
+ "Sketch.html": `<section class="include-note" data-attachment-id="drawing1"></section>`,
+ "Sketch_Canvas.excalidraw": "{}",
+ "Sketch_drawing1.svg": "<svg></svg>"
+ });
+
+ const { importedNote } = await testImportBuffer(zipBuffer);
+ const drawing = importedNote.getAttachmentByTitle("Canvas.excalidraw");
+
+ expect(drawing?.attachmentId).not.toBe("drawing1");
+ expect(importedNote.getAttachments().map(({ title }) => title).sort())
+ .toEqual([ "Canvas.excalidraw", `${drawing?.attachmentId}.svg` ].sort());
+ });
+
it("restores an embedded mermaid diagram as a note reference, not as a raw attachment", async () => {
// The export points the <img> at the mermaid note's generated `mermaid-export.svg`.
// On the way back in that has to resolve to `api/images/<noteId>` — which re-renders the
diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.ts
index 9955e1920f..4426ef14f2 100644
--- a/packages/trilium-core/src/services/import/zip.ts
+++ b/packages/trilium-core/src/services/import/zip.ts
@@ -1,4 +1,7 @@
-import { ALLOWED_NOTE_TYPES, getImageAttachmentTitle, type NoteType } from "@triliumnext/commons";
+import {
+ ALLOWED_NOTE_TYPES, CANVAS_ATTACHMENT_MIME, getDrawingPictureTitle, getImageAttachmentTitle,
+ type NoteType
+} from "@triliumnext/commons";
import { basename, dirname } from "../utils/path.js";
import { getZipProvider, type ZipSource } from "../zip_provider.js";
@@ -19,7 +22,7 @@ import type TaskContext from "../task_context.js";
import treeService from "../tree.js";
import markdownService from "./markdown.js";
import mimeService from "./mime.js";
-import { AttributeMeta, NoteMeta } from "../../meta.js";
+import { AttachmentMeta, AttributeMeta, NoteMeta } from "../../meta.js";
import { isMarkdownCodeNote } from "../export/rewrite_links.js";
import { sanitizeHtml } from "../sanitizer.js";
import { extractFrontmatter, type FrontmatterAttribute } from "./frontmatter.js";
@@ -135,6 +138,19 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
return attachmentIdMap[origAttachmentId];
}
+ /**
+ * The title of an imported attachment of a note with `attachments`: the picture of a canvas
+ * drawing takes the title that the new ID of its drawing gives it.
+ */
+ function getAttachmentTitle(attachmentMeta: AttachmentMeta, attachments: AttachmentMeta[]) {
+ const drawingId = attachments.find(({ attachmentId, mime }) => attachmentId
+ && mime === CANVAS_ATTACHMENT_MIME
+ && getDrawingPictureTitle(attachmentId) === attachmentMeta.title)?.attachmentId;
+ return drawingId
+ ? getDrawingPictureTitle(getNewAttachmentId(drawingId))
+ : attachmentMeta.title;
+ }
+
function getAttachmentMeta(parentNoteMeta: NoteMeta, dataFileName: string) {
for (const noteMeta of parentNoteMeta.children || []) {
for (const attachmentMeta of noteMeta.attachments || []) {
@@ -604,7 +620,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
const attachment = new BAttachment({
attachmentId: getNewAttachmentId(attachmentMeta.attachmentId),
ownerId: noteId,
- title: attachmentMeta.title,
+ title: getAttachmentTitle(attachmentMeta, noteMeta?.attachments ?? []),
role: attachmentMeta.role,
mime: attachmentMeta.mime,
position: attachmentMeta.position
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 0b54ca5f2e..b3ae99887a 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -1,4 +1,4 @@
-import { type AttachmentRow, attachmentRoleTraits, type AttributeRow, type BranchRow, CANVAS_ATTACHMENT_MIME, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType, parseMindMapNoteLink } from "@triliumnext/commons";
+import { type AttachmentRow, attachmentRoleTraits, type AttributeRow, type BranchRow, CANVAS_ATTACHMENT_MIME, dayjs, getDrawingPictureTitle, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType, parseMindMapNoteLink } from "@triliumnext/commons";
import { t } from "i18next";
import { parse as parseHtml } from "node-html-parser";
@@ -552,7 +552,7 @@ export function checkImageAttachments(note: BNote, content: string) {
.filter((foundAttId) => !existingAttachmentIds.has(foundAttId)));
const foundFileIds = isCanvas
? collectCanvasImageFileIds(content)
- : collectDrawingImageFileIds([ ...attachments, ...unknownAttachments ], foundAttachmentIds);
+ : collectDrawingImageTitles([ ...attachments, ...unknownAttachments ], foundAttachmentIds);
for (const attachment of attachments) {
// Only attachments that live in the note content are auto-scheduled for erasure when nothing
@@ -634,7 +634,7 @@ export function checkImageAttachments(note: BNote, content: string) {
getLog().info(`Copied attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}' to new '${localAttachment.attachmentId}' of note '${note.noteId}'`);
}
- copyDrawingImages(note, unknownAttachment);
+ copyDrawingImages(note, unknownAttachment, localAttachment);
// Replace image links — every one of them. A string first argument to replace() rewrites
// only the first match, which was survivable while each reference had an attachment of its
@@ -686,40 +686,51 @@ export function collectCanvasImageFileIds(content: string): Set<string> {
return fileIds;
}
-/** The file IDs of the images that the canvas drawings among `attachments` in the content show. */
-function collectDrawingImageFileIds(attachments: BAttachment[], foundAttachmentIds: Set<string>) {
- const fileIds = new Set<string>();
+/**
+ * The titles of the image attachments that the canvas drawings among `attachments` in the content
+ * keep: the images they show, titled with their file IDs, and the picture of each drawing.
+ */
+function collectDrawingImageTitles(attachments: BAttachment[], foundAttachmentIds: Set<string>) {
+ const titles = new Set<string>();
for (const attachment of attachments) {
- if (attachment.mime !== CANVAS_ATTACHMENT_MIME
- || !foundAttachmentIds.has(attachment.attachmentId ?? "")) {
+ const { attachmentId } = attachment;
+ if (attachment.mime !== CANVAS_ATTACHMENT_MIME || !attachmentId
+ || !foundAttachmentIds.has(attachmentId)) {
continue;
}
+ titles.add(getDrawingPictureTitle(attachmentId));
for (const fileId of collectCanvasImageFileIds(decodeUtf8(attachment.getContent()))) {
- fileIds.add(fileId);
+ titles.add(fileId);
}
}
- return fileIds;
+ return titles;
}
/**
* Copies to `note` the images that the canvas drawing of another note shows, which its owner keeps
- * titled with their file IDs, unless `note` has attachments of those titles already.
+ * titled with their file IDs, unless `note` has attachments of those titles already. The picture of
+ * the drawing becomes the picture of `copiedDrawing`, its copy in `note`.
*/
-function copyDrawingImages(note: BNote, drawing: BAttachment) {
+function copyDrawingImages(note: BNote, drawing: BAttachment, copiedDrawing: BAttachment) {
const owner = becca.getNote(drawing.ownerId);
if (drawing.mime !== CANVAS_ATTACHMENT_MIME || !owner) {
return;
}
const fileIds = collectCanvasImageFileIds(decodeUtf8(drawing.getContent()));
+ const pictureTitle = getDrawingPictureTitle(drawing.attachmentId ?? "");
for (const image of owner.getAttachments()) {
- if (!fileIds.has(image.title) || note.getAttachmentByTitle(image.title)) {
+ const title = image.title === pictureTitle && copiedDrawing.attachmentId
+ ? getDrawingPictureTitle(copiedDrawing.attachmentId)
+ : fileIds.has(image.title) && image.title;
+ if (!title || note.getAttachmentByTitle(title)) {
continue;
}
const copy = image.copy();
copy.ownerId = note.noteId;
+ copy.title = title;
copy.setContent(image.getContent(), { forceSave: true });
}
}
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 354f1e3abb..69a581ea11 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -1,4 +1,4 @@
-import { trimIndentation } from "@triliumnext/commons";
+import { CANVAS_ATTACHMENT_MIME, trimIndentation } from "@triliumnext/commons";
import {
getChildLinks, getChildLinksLayout, getContentClasses, getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo
} from "@triliumnext/share-theme/model/page";
@@ -699,14 +699,24 @@ describe("content_renderer", () => {
expect(code?.innerHTML).not.toContain("hljs-tag");
});
- it("renders an embedded picture as an image, any other attachment as a download", () => {
+ it("renders a picture or drawing embed as an image, any other embed as a download", () => {
const embed = (id: string) =>
`<section class="include-note" data-attachment-id="${id}">&nbsp;</section>`;
+ const drawing = {
+ role: "file", mime: CANVAS_ATTACHMENT_MIME, title: "Canvas.excalidraw"
+ };
const note = buildShareNote({
- content: embed("embedPic1") + embed("embedPdf1") + embed("embedGone"),
+ content: embed("embedPic1") + embed("embedPdf1") + embed("embedGone")
+ + embed("embedDraw1") + embed("embedDraw2"),
attachments: [
{ id: "embedPic1", role: "image", mime: "image/png", title: "my photo.png" },
- { id: "embedPdf1", role: "file", mime: "application/pdf", title: "report.pdf" }
+ { id: "embedPdf1", role: "file", mime: "application/pdf", title: "report.pdf" },
+ { id: "embedDraw1", ...drawing },
+ {
+ id: "drawPicture", role: "image", mime: "image/svg+xml",
+ title: "embedDraw1.svg"
+ },
+ { id: "embedDraw2", ...drawing }
]
});
@@ -715,6 +725,14 @@ describe("content_renderer", () => {
const src = "api/attachments/embedPic1/image/my%20photo.png";
expect(content).toContain(`<section class="include-note" data-attachment-id="embedPic1">`
+ `<img src="${src}" alt="my photo.png"></section>`);
+ expect(content).toContain(
+ `<section class="include-note" data-attachment-id="embedDraw1">`
+ + `<img src="api/attachments/drawPicture/image/embedDraw1.svg" `
+ + `alt="Canvas.excalidraw"></section>`);
+ expect(content).toContain(
+ `<section class="include-note" data-attachment-id="embedDraw2">`
+ + `<a class="reference-link attachment-link role-file" `
+ + `href="api/attachments/embedDraw2/download">`);
expect(content).toContain(`<section class="include-note" data-attachment-id="embedPdf1">`
+ `<a class="reference-link attachment-link role-file"`);
expect(content).toContain(`href="api/attachments/embedPdf1/download"`);
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 90310cc460..ae8410cb9b 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -1,8 +1,9 @@
import {
- getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl,
- isImageAttachmentRole, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor, readLinkPreviewData,
- renderLinkEmbedHtml, renderLinkMentionHtml, resolveContentEmbed, resolveEnabledMimeTypes,
- SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES, shouldSyntaxHighlight, sliceToBlockReference
+ CANVAS_ATTACHMENT_MIME, getAttachmentEmbedHref, getDrawingPictureTitle, getEmbedKey,
+ getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl, isImageAttachmentRole, MIME_TYPE_AUTO,
+ normalizeMimeTypeForCKEditor, readLinkPreviewData, renderLinkEmbedHtml, renderLinkMentionHtml,
+ resolveContentEmbed, resolveEnabledMimeTypes, SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES,
+ shouldSyntaxHighlight, sliceToBlockReference
} from "@triliumnext/commons";
import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
@@ -621,7 +622,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
const link = renderAttachmentLink(embed.attachmentId, attachment);
embedEl.replaceWith(...parse(link, parseOpts).childNodes);
} else {
- const html = renderAttachmentEmbed(embed.attachmentId, attachment);
+ const html = renderAttachmentEmbed(embed.attachmentId, attachment, getNote);
replaceEmbedContent(embedEl, parse(html, parseOpts).childNodes);
}
continue;
@@ -703,15 +704,23 @@ function replaceEmbedContent(embedEl: HTMLElement, content: ParsedNode[]) {
}
/**
- * What an embedded attachment shows: a picture as an image, anything else as the attachment link
- * that `handleAttachmentLink` then resolves.
+ * What an embedded attachment shows: a picture as an image, a canvas drawing as the picture that
+ * its note keeps of it, at the size of the picture, and anything else, or a drawing without a
+ * picture, as the attachment link that `handleAttachmentLink` then resolves.
*/
-function renderAttachmentEmbed(attachmentId: string, attachment: BAttachment | SAttachment) {
- if (!isImageAttachmentRole(attachment.role)) {
+function renderAttachmentEmbed(
+ attachmentId: string,
+ attachment: BAttachment | SAttachment,
+ getNote: GetNoteFunction
+) {
+ const image = attachment.mime === CANVAS_ATTACHMENT_MIME
+ ? getNote(attachment.ownerId)?.getAttachmentByTitle(getDrawingPictureTitle(attachmentId))
+ : attachment;
+ if (!image?.attachmentId || !isImageAttachmentRole(image.role)) {
return renderAttachmentLink(attachmentId, attachment);
}
- const src = `api/attachments/${attachmentId}/image/${encodeURIComponent(attachment.title)}`;
+ const src = `api/attachments/${image.attachmentId}/image/${encodeURIComponent(image.title)}`;
return `<img src="${src}" alt="${escapeHtml(attachment.title)}">`;
}
diff --git a/packages/trilium-core/src/share/shaca/entities/sattachment.ts b/packages/trilium-core/src/share/shaca/entities/sattachment.ts
index 941b0b0bae..4a1f988c60 100644
--- a/packages/trilium-core/src/share/shaca/entities/sattachment.ts
+++ b/packages/trilium-core/src/share/shaca/entities/sattachment.ts
@@ -10,7 +10,7 @@ import type { SAttachmentRow } from "./rows.js";
import type SNote from "./snote.js";
class SAttachment extends AbstractShacaEntity {
- private attachmentId: string;
+ attachmentId: string;
ownerId: string;
title: string;
role: string;