Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: allow an image to be turned into a drawing canvas

Adorian Dorandfa798276bbc
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 290316d120..06eb9ac924 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2846,7 +2846,8 @@
"cannot-copy": "Could not copy the image reference to clipboard.",
"image-copied-to-clipboard": "The image has been copied to clipboard.",
"cannot-copy-image": "Could not copy the image to clipboard.",
- "cannot-download": "Could not download the image."
+ "cannot-download": "Could not download the image.",
+ "cannot-convert-to-drawing": "Could not convert the image to a drawing canvas."
},
"clipboard": {
"cut": "Note(s) have been cut into clipboard.",
@@ -4234,6 +4235,7 @@
"changes": "Changes",
"click-on-the-arrow-or-press-0-to-collapse-expand": "Click on the arrow or press %0 to collapse/expand.",
"collapsible-block": "Collapsible block",
+ "convert-image-to-a-drawing-canvas": "Convert image to a drawing canvas",
"convert-to-link": "Convert to link",
"copy-anchor-reference-link": "Copy anchor reference link",
"copy-formatting": "Copy formatting",
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 48f902ba53..ca49bd9418 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx
@@ -17,7 +17,7 @@ vi.mock("./persistence", () => ({
return {};
},
parseContent: (content: string) => JSON.parse(content),
- getInlineFiles: () => ({})
+ loadDrawingFiles: async () => ({ files: {}, referencedFileIds: new Set() })
}));
const { detailEditor, attachmentEditorMounts, canvasEditorMounts } = vi.hoisted(() => ({
detailEditor: { canEdit: () => true, release: vi.fn() },
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
index 9646242457..3e4a15cc48 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
@@ -20,7 +20,7 @@ import { useEditableEmbed } from "../text/editable_embed";
import { CanvasEditor } from "./Canvas";
import CanvasDrawingMenu from "./CanvasDrawingMenu";
import CanvasEmbedTools from "./CanvasEmbedTools";
-import { getInlineFiles, parseContent, useCanvasDrawingPersistence } from "./persistence";
+import { loadDrawingFiles, parseContent, useCanvasDrawingPersistence } from "./persistence";
interface CanvasDrawingProps {
attachment: FAttachment;
@@ -98,7 +98,7 @@ export async function renderCanvasDrawingPicture(entity: FNote | FAttachment) {
// Follows the theme as the editor does, except in print, which stays light.
exportWithDarkMode: glob.device !== "print" && getEffectiveThemeStyle() === "dark"
},
- files: getInlineFiles(content),
+ files: (await loadDrawingFiles(entity, content)).files,
exportPadding: 5
});
svg.classList.add("canvas-drawing-picture");
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 b74f9a101a..a5825fa5f9 100644
--- a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
@@ -1,6 +1,7 @@
import type { BinaryFileData } from "@excalidraw/excalidraw/types";
import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
+import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
import { parseImageDataUrl } from "../../../services/image_upload";
import type { SavedData } from "../../react/hooks";
@@ -26,9 +27,12 @@ export const CANVAS_EXPORT_TITLE = NOTE_TYPE_IMAGE_ATTACHMENTS.canvas;
* attachment title. The bytes are fetched from the attachment image endpoint and re-encoded as a
* data URL, since Excalidraw renders only from inline data URLs (it has no external-URL provider).
*/
-export async function loadImageAttachments(note: FNote): Promise<{ files: BinaryFileData[]; metadata: ImageAttachmentMetadata[] }> {
- const attachments = await getCanvasImageAttachments(note);
+export async function loadImageAttachments(note: FNote) {
+ return loadImageFiles(await getCanvasImageAttachments(note));
+}
+/** Loads the image `attachments` into Excalidraw {@link BinaryFileData}, keyed by their titles. */
+export async function loadImageFiles(attachments: FAttachment[]) {
const files: BinaryFileData[] = [];
const metadata: ImageAttachmentMetadata[] = [];
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
new file mode 100644
index 0000000000..c84718dca2
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.spec.ts
@@ -0,0 +1,106 @@
+import { CANVAS_ATTACHMENT_MIME, CANVAS_ATTACHMENT_TITLE } from "@triliumnext/commons";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import server from "../../../services/server";
+import toast from "../../../services/toast";
+import { convertImageToDrawing } from "./image_to_drawing";
+
+vi.mock("../../../services/server", () => ({ default: { upload: vi.fn() } }));
+vi.mock("../../../services/toast", () => ({ default: { showError: vi.fn() } }));
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+vi.mock("@excalidraw/excalidraw", () => ({
+ convertToExcalidrawElements: (skeletons: object[]) =>
+ skeletons.map((skeleton) => ({ id: "e1", ...skeleton }))
+}));
+
+const upload = vi.mocked(server.upload);
+
+describe("convertImageToDrawing", () => {
+ let imageType: string;
+ let naturalSize: { width: number; height: number };
+
+ beforeEach(() => {
+ imageType = "image/png";
+ naturalSize = { width: 800, height: 600 };
+ vi.mocked(toast.showError).mockClear();
+ vi.stubGlobal("fetch", vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ blob: async () => new Blob([ "png" ], { type: imageType })
+ })));
+ vi.spyOn(HTMLImageElement.prototype, "decode").mockResolvedValue();
+ vi.spyOn(HTMLImageElement.prototype, "naturalWidth", "get")
+ .mockImplementation(() => naturalSize.width);
+ vi.spyOn(HTMLImageElement.prototype, "naturalHeight", "get")
+ .mockImplementation(() => naturalSize.height);
+ let attachmentCount = 0;
+ upload.mockImplementation(async () => ({
+ uploaded: true,
+ url: `#root/n1?viewMode=attachments&attachmentId=att${++attachmentCount}`
+ }));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ upload.mockReset();
+ });
+
+ it("attaches the image and a drawing that shows it, locked and centered", async () => {
+ expect(await convertImageToDrawing("n1", "api/attachments/i1/image/a.png", "c1"))
+ .toBe("att2");
+
+ expect(fetch).toHaveBeenCalledWith("api/attachments/i1/image/a.png");
+ const requests = upload.mock.calls
+ .map(([ url, , componentId, method ]) => [ url, componentId, method ]);
+ expect(requests).toEqual([
+ [ "notes/n1/attachments/upload?link=true", "c1", "POST" ],
+ [ "notes/n1/attachments/upload?link=true", "c1", "POST" ]
+ ]);
+ const [ [ , image ], [ , drawing ] ] = upload.mock.calls;
+ expect(image.name).toMatch(/^[A-Za-z0-9]{20}\.png$/);
+ expect(image.type).toBe("image/png");
+ expect(drawing.name).toBe(CANVAS_ATTACHMENT_TITLE);
+ expect(drawing.type).toBe(CANVAS_ATTACHMENT_MIME);
+
+ const content = JSON.parse(await drawing.text());
+ expect(content).toEqual({
+ type: "excalidraw",
+ version: 2,
+ elements: [ {
+ id: "e1",
+ type: "image",
+ fileId: image.name,
+ status: "saved",
+ x: -400,
+ y: -300,
+ width: 800,
+ height: 600,
+ locked: true
+ } ],
+ files: {},
+ appState: {}
+ });
+ expect(toast.showError).not.toHaveBeenCalled();
+ });
+
+ it("tells that it failed, and attaches nothing, for what is no picture", async () => {
+ imageType = "text/html";
+ expect(await convertImageToDrawing("n1", "https://example.com/a.png")).toBeNull();
+
+ imageType = "image/png";
+ naturalSize = { width: 0, height: 0 };
+ expect(await convertImageToDrawing("n1", "api/attachments/i1/image/a.png")).toBeNull();
+
+ expect(upload).not.toHaveBeenCalled();
+ expect(toast.showError).toHaveBeenCalledTimes(2);
+ expect(toast.showError).toHaveBeenCalledWith("image.cannot-convert-to-drawing");
+ });
+
+ it("tells that it failed when the server refuses an upload", async () => {
+ upload.mockResolvedValueOnce({ uploaded: false, message: "No." });
+ expect(await convertImageToDrawing("n1", "api/attachments/i1/image/a.png")).toBeNull();
+ expect(upload).toHaveBeenCalledOnce();
+ expect(toast.showError).toHaveBeenCalledOnce();
+ });
+});
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
new file mode 100644
index 0000000000..675d2ca427
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/image_to_drawing.ts
@@ -0,0 +1,81 @@
+import type { FileId } from "@excalidraw/excalidraw/element/types";
+import {
+ CANVAS_ATTACHMENT_MIME, CANVAS_ATTACHMENT_TITLE, EMPTY_CANVAS_CONTENT, imageExtensionForMime,
+ isAcceptedImageMime
+} from "@triliumnext/commons";
+
+import { t } from "../../../services/i18n";
+import server from "../../../services/server";
+import toast from "../../../services/toast";
+import { randomString } from "../../../services/utils";
+
+/**
+ * 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.
+ */
+export async function convertImageToDrawing(noteId: string, src: string, componentId?: string) {
+ try {
+ const image = await fetchImage(src);
+ const { width, height } = await getNaturalSize(image);
+ const fileId = `${randomString(20)}.${imageExtensionForMime(image.type)}`;
+ await upload(noteId, new File([ image ], fileId, { type: image.type }), componentId);
+
+ const { convertToExcalidrawElements } = await import("@excalidraw/excalidraw");
+ const elements = convertToExcalidrawElements([ {
+ type: "image",
+ fileId: fileId as FileId,
+ status: "saved",
+ x: -width / 2,
+ y: -height / 2,
+ width,
+ height,
+ locked: true
+ } ]);
+ const content = JSON.stringify({ ...JSON.parse(EMPTY_CANVAS_CONTENT), elements });
+ const drawing = new File([ content ], CANVAS_ATTACHMENT_TITLE, {
+ type: CANVAS_ATTACHMENT_MIME
+ });
+ return await upload(noteId, drawing, componentId);
+ } catch (e) {
+ console.error(`Could not convert the image '${src}' to a drawing canvas`, e);
+ toast.showError(t("image.cannot-convert-to-drawing"));
+ return null;
+ }
+}
+
+async function fetchImage(src: string) {
+ const response = await fetch(src);
+ const image = await response.blob();
+ if (!response.ok || !isAcceptedImageMime(image.type)) {
+ throw new Error(`Got ${response.status} '${image.type}' instead of an image.`);
+ }
+ return image;
+}
+
+async function getNaturalSize(image: Blob) {
+ const url = URL.createObjectURL(image);
+ try {
+ const element = new Image();
+ element.src = url;
+ await element.decode();
+ const { naturalWidth: width, naturalHeight: height } = element;
+ if (!width || !height) {
+ throw new Error("The image has no natural size.");
+ }
+ return { width, height };
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
+
+/** Attaches `file` to the note as it is, and answers with the ID of the attachment. */
+async function upload(noteId: string, file: File, componentId?: string) {
+ const url = `notes/${noteId}/attachments/upload?link=true`;
+ const response = await server.upload(url, file, componentId, "POST") as { url?: string };
+ const attachmentId = response?.url?.match(/attachmentId=([A-Za-z0-9_]+)/)?.[1];
+ if (!attachmentId) {
+ throw new Error(`The upload of '${file.name}' was refused.`);
+ }
+ return attachmentId;
+}
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 5d2bace414..5e9971dbae 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
@@ -28,11 +28,25 @@ interface FakeElement {
version: number;
}
+interface PlacedElement {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ isDeleted?: boolean;
+}
+
vi.mock("@excalidraw/excalidraw", () => ({
// Mirrors the real behavior closely enough for change tracking: the version of a scene
// is derived from its elements, and an empty scene is always version 0.
getSceneVersion: (elements: FakeElement[]) => elements.reduce((sum, el) => sum + (el.version ?? 0), 0),
exportToSvg: vi.fn(async () => ({ outerHTML: "<svg/>" })),
+ getCommonBounds: (elements: PlacedElement[]) => [
+ Math.min(...elements.map(({ x }) => x)),
+ Math.min(...elements.map(({ y }) => y)),
+ Math.max(...elements.map(({ x, width }) => x + width)),
+ Math.max(...elements.map(({ y, height }) => y + height))
+ ],
CaptureUpdateAction: { IMMEDIATELY: "IMMEDIATELY", NEVER: "NEVER", EVENTUALLY: "EVENTUALLY" }
}));
@@ -213,7 +227,9 @@ describe("useCanvasDrawingPersistence", () => {
let container: HTMLElement;
let drawingProps: ReturnType<typeof useCanvasDrawingPersistence> | undefined;
let sceneElements: FakeElement[];
+ let sceneFiles: Record<string, unknown>;
let appState: Record<string, unknown>;
+ let updateScene: ReturnType<typeof vi.fn>;
function DrawingProbe({ attachment, editor, apiRef }: {
attachment: FAttachment;
@@ -227,6 +243,8 @@ describe("useCanvasDrawingPersistence", () => {
beforeEach(() => {
drawingProps = undefined;
sceneElements = [];
+ sceneFiles = { f1: IMAGE, f2: UNUSED_IMAGE };
+ updateScene = vi.fn();
appState = {
scrollX: 1, scrollY: 2, zoom: { value: 1 }, gridModeEnabled: false,
viewBackgroundColor: "transparent", theme: "light"
@@ -238,6 +256,7 @@ describe("useCanvasDrawingPersistence", () => {
afterEach(() => {
act(() => render(null, container));
container.remove();
+ vi.unstubAllGlobals();
});
function buildAttachment(content: object) {
@@ -258,7 +277,8 @@ describe("useCanvasDrawingPersistence", () => {
const api = {
getSceneElements: () => sceneElements,
getAppState: () => appState,
- getFiles: () => ({ f1: IMAGE, f2: UNUSED_IMAGE })
+ getFiles: () => sceneFiles,
+ updateScene
} as unknown as ExcalidrawImperativeAPI;
const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI | null>;
await act(async () => {
@@ -337,6 +357,76 @@ describe("useCanvasDrawingPersistence", () => {
expect(editor.release).toHaveBeenCalledOnce();
});
+ it("loads the images it refers to from its note and saves them by reference", async () => {
+ const owner = buildNote({ title: "Owner" });
+ const getAttachmentsByRole = vi.fn(async () => [
+ { attachmentId: "img1", title: "f9.png" },
+ { attachmentId: "img2", title: "other.png" }
+ ]);
+ owner.getAttachmentsByRole = getAttachmentsByRole as never;
+ const fetchImage = vi.fn(async () => ({
+ ok: true,
+ blob: async () => new Blob([ "ABC" ], { type: "image/png" })
+ }));
+ vi.stubGlobal("fetch", fetchImage);
+ const loaded = [
+ { id: "i1", type: "image", version: 1, fileId: "f1" },
+ { id: "i9", type: "image", version: 1, fileId: "f9.png" }
+ ];
+ const { attachment } = buildAttachment({ elements: loaded, files: { f1: IMAGE } });
+ const drawing = { ...attachment, ownerId: owner.noteId } as unknown as FAttachment;
+ const editor = buildEditor();
+
+ const initialData = await mount(drawing, editor);
+ expect(getAttachmentsByRole).toHaveBeenCalledWith("image");
+ expect(fetchImage).toHaveBeenCalledExactlyOnceWith("api/attachments/img1/image/f9.png");
+ expect(initialData.files).toEqual({
+ f1: IMAGE,
+ "f9.png": {
+ id: "f9.png", dataURL: "data:image/png;base64,QUJD", mimeType: "image/png",
+ created: expect.any(Number)
+ }
+ });
+
+ sceneElements = loaded;
+ change();
+ sceneElements = [ { ...loaded[0], version: 2 }, loaded[1] ];
+ sceneFiles = initialData.files ?? {};
+ change();
+ const [ getContent ] = editor.scheduleSave.mock.calls[0];
+ expect(JSON.parse(getContent()).files).toEqual({ f1: IMAGE });
+ });
+
+ it("fits a drawing without a saved view in the size that Excalidraw reports", async () => {
+ const TALL = { x: -400, y: -400, width: 800, height: 800 };
+ const LATER = { x: 150, y: 60, width: 10, height: 10 };
+ async function getFits(loaded: PlacedElement[], savedAppState: object = {}) {
+ act(() => render(null, container));
+ updateScene.mockClear();
+ const { attachment } = buildAttachment({ elements: loaded, appState: savedAppState });
+ await mount(attachment, undefined);
+ // The empty scene, then the loaded one before the drawing is laid out, then more.
+ for (const [ elements, width, height ] of [
+ [ [], 1000, 400 ], [ loaded, 0, 0 ], [ [ ...loaded, LATER ], 1000, 400 ],
+ [ [ ...loaded, LATER ], 1000, 400 ]
+ ] as const) {
+ drawingProps?.onChange?.(elements as never, { width, height } as never, {});
+ }
+ return updateScene.mock.calls.map(([ { appState } ]) => appState);
+ }
+
+ expect(await getFits([ TALL ]))
+ .toEqual([ { zoom: { value: 0.5 }, scrollX: 1000, scrollY: 400 } ]);
+ expect(await getFits([ { x: 100, y: 50, width: 800, height: 200 } ]))
+ .toEqual([ { zoom: { value: 1.25 }, scrollX: -100, scrollY: 10 } ]);
+ expect((await getFits([ { x: 0, y: 0, width: 100_000, height: 100 } ]))[0]?.zoom)
+ .toEqual({ value: 0.1 });
+
+ expect(await getFits([ TALL ], { zoom: { value: 2 }, scrollX: 5, scrollY: 6 })).toEqual([]);
+ expect(await getFits([])).toEqual([]);
+ expect(await getFits([ { ...TALL, isDeleted: true } ])).toEqual([]);
+ });
+
it("saves nothing without an editor", async () => {
const loaded = [ { id: "r1", type: "rectangle", version: 3 } ];
const { attachment } = buildAttachment({ elements: loaded });
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
index fd42233103..000fae439b 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -1,6 +1,11 @@
-import { CaptureUpdateAction, exportToSvg, getSceneVersion } from "@excalidraw/excalidraw";
+import {
+ CaptureUpdateAction, exportToSvg, getCommonBounds, getSceneVersion
+} from "@excalidraw/excalidraw";
import { ExcalidrawElement, NonDeletedExcalidrawElement } from "@excalidraw/excalidraw/element/types";
-import { AppState, BinaryFileData, BinaryFiles, ExcalidrawImperativeAPI, ExcalidrawInitialDataState, ExcalidrawProps, LibraryItem } from "@excalidraw/excalidraw/types";
+import {
+ AppState, BinaryFileData, BinaryFiles, ExcalidrawImperativeAPI, ExcalidrawInitialDataState,
+ ExcalidrawProps, LibraryItem, NormalizedZoomValue
+} from "@excalidraw/excalidraw/types";
import { deferred, type DeferredPromise } from "@triliumnext/commons";
import { RefObject } from "preact";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
@@ -9,9 +14,13 @@ import NoteContext from "../../../components/note_context";
import type FAttachment from "../../../entities/fattachment";
import FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
+import froca from "../../../services/froca";
import server from "../../../services/server";
import { SavedData, useEditorSpacedUpdate } from "../../react/hooks";
-import { buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments } from "./image_attachments";
+import { MAX_ZOOM, MIN_ZOOM } from "./CanvasEmbedTools";
+import {
+ buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments, loadImageFiles
+} from "./image_attachments";
interface AttachmentMetadata {
title: string;
@@ -359,6 +368,8 @@ export function useCanvasDrawingPersistence(
const appStateToCompare = useRef<ImportantAppState | null>(null);
// Same guard as the canvas note: the scene is empty until Excalidraw applies `initialData`.
const initialSceneAppliedRef = useRef(true);
+ const referencedFileIds = useRef<ReadonlySet<string>>(new Set());
+ const isFitPendingRef = useRef(false);
const [ initialData ] = useState(async (): Promise<ExcalidrawInitialDataState> => {
const unsavedContent = editor?.getUnsavedContent();
@@ -366,16 +377,20 @@ export function useCanvasDrawingPersistence(
? (await attachment.getBlob())?.content ?? ""
: unsavedContent;
const content = parseContent(blobContent, attachment);
+ const loaded = await loadDrawingFiles(attachment, content);
+ referencedFileIds.current = loaded.referencedFileIds;
const elements = content.elements ?? [];
currentSceneVersion.current = getSceneVersion(elements);
initialSceneAppliedRef.current = currentSceneVersion.current === 0;
+ isFitPendingRef.current = !content.appState?.zoom
+ && elements.some((element) => !element.isDeleted);
return {
elements,
// A drawing shows the background of the note unless one is picked for it.
appState: { viewBackgroundColor: "transparent", ...content.appState, theme },
- files: getInlineFiles(content)
+ files: loaded.files
};
});
@@ -388,8 +403,14 @@ export function useCanvasDrawingPersistence(
excalidrawAPI: (api) => {
apiRef.current = api;
},
- onChange: () => {
+ onChange: (elements, { width, height }) => {
const api = apiRef.current;
+ // Excalidraw reports its size only once the drawing is laid out in the note.
+ const view = isFitPendingRef.current && getFittedView(elements, width, height);
+ if (api && view) {
+ isFitPendingRef.current = false;
+ api.updateScene({ appState: view });
+ }
if (!api || !editor) return;
const sceneVersion = getSceneVersion(api.getSceneElements());
@@ -407,24 +428,73 @@ export function useCanvasDrawingPersistence(
if (sceneVersion === currentSceneVersion.current && !isAppStateChanged) return;
currentSceneVersion.current = sceneVersion;
- editor.scheduleSave(() => serializeDrawing(api));
+ editor.scheduleSave(() => serializeDrawing(api, referencedFileIds.current));
}
};
}
-/** The images kept inline in `content`, keyed by their file ID. */
-export function getInlineFiles(content: CanvasContent): BinaryFiles {
+/**
+ * The view of a drawing `width` by `height` that saved none, such as one converted from an image:
+ * its content fit in the drawing and centered. `null` without content or a size.
+ */
+function getFittedView(
+ elements: readonly ExcalidrawElement[],
+ width: number,
+ height: number
+): Pick<AppState, "zoom" | "scrollX" | "scrollY"> | null {
+ const shown = elements.filter((element) => !element.isDeleted);
+ if (!shown.length || !width || !height) return null;
+
+ const [ minX, minY, maxX, maxY ] = getCommonBounds(shown);
+ const fit = Math.min(width / (maxX - minX), height / (maxY - minY));
+ const zoom = Math.min(Math.max(fit, MIN_ZOOM), MAX_ZOOM);
+ return {
+ zoom: { value: zoom as NormalizedZoomValue },
+ scrollX: width / 2 / zoom - (minX + maxX) / 2,
+ scrollY: height / 2 / zoom - (minY + maxY) / 2
+ };
+}
+
+/**
+ * The images of the canvas drawing in `content`: the ones it keeps inline, and the ones it refers
+ * 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) {
const files: BinaryFiles = {};
for (const file of Object.values(content.files ?? {})) {
files[file.id] = file;
}
- return files;
+
+ const referencedFileIds = new Set<string>();
+ for (const element of content.elements ?? []) {
+ if ("fileId" in element && element.fileId && !files[element.fileId]) {
+ referencedFileIds.add(element.fileId);
+ }
+ }
+
+ if (referencedFileIds.size) {
+ const owner = entity instanceof FNote ? entity : await froca.getNote(entity.ownerId);
+ const images = (await owner?.getAttachmentsByRole(IMAGE_ROLE) ?? [])
+ .filter((attachment) => referencedFileIds.has(attachment.title));
+ for (const file of (await loadImageFiles(images)).files) {
+ files[file.id] = file;
+ }
+ }
+
+ return { files, referencedFileIds };
}
-/** The content of a canvas drawing. Unlike a canvas note, a drawing keeps its images inline. */
-function serializeDrawing(api: ExcalidrawImperativeAPI) {
+/**
+ * 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.
+ */
+function serializeDrawing(api: ExcalidrawImperativeAPI, referencedFileIds: ReadonlySet<string>) {
const elements = api.getSceneElements();
const files = getActiveFiles(elements, api.getFiles());
+ for (const fileId of referencedFileIds) {
+ delete files[fileId];
+ }
return JSON.stringify(buildSceneContent(elements, api.getAppState(), files));
}
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index de29fd3e97..d9f71b2db2 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -35,6 +35,7 @@ import {
} from "../../react/hooks";
import IconPicker from "../../react/IconPicker";
import { setEditorNoteId } from "../../react/NoteStore";
+import { convertImageToDrawing } from "../canvas/image_to_drawing";
import { TypeWidgetProps } from "../type_widget";
import AttachmentSaves, { useNoteEditor } from "./attachment_saves";
import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";
@@ -283,6 +284,9 @@ export default function EditableText({
focusContentEmbed(attachmentId: string) {
focusedAttachmentIdRef.current = attachmentId;
},
+ convertImageToDrawing(src: string) {
+ return convertImageToDrawing(note.noteId, src, parentComponent?.componentId);
+ },
getAttachmentHref,
getNoteId() {
return note.noteId;
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index a5e312c5f3..b4b2c164e3 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -500,6 +500,7 @@ describe("CK config - image actions", () => {
const unsupportedToolbar = (unsupported.image as { toolbar: unknown[] }).toolbar;
expect(unsupportedToolbar).not.toContain("copyImageToClipboard");
expect(unsupportedToolbar).toContain("downloadImage");
+ expect(unsupportedToolbar).toContain("convertImageToDrawing");
imageState.copySupported = true;
const supported = await buildConfig(baseOpts());
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index d3be8278df..8071c575da 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -128,7 +128,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
"imageResize:50",
"imageResize:original",
"|",
- "toggleImageCaption"
+ "toggleImageCaption",
+ "|",
+ "convertImageToDrawing"
],
upload: {
// Derived rather than listed, so what the editor inserts as a picture and what the
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html
index a5c96e9c2a..5dd18b45a9 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html
@@ -101,6 +101,11 @@ class="table">
</tbody>
</table>
</figure>
+<h3>Drawing over an image</h3>
+<p>To draw or write over an image, press the <span class="tn-icon bx bxs-pen"></span> <em>Convert image to a drawing canvas</em> button
+ of its toolbar. The image becomes a drawing canvas that shows all of it,
+ locked in place. See the drawing canvases section of <a class="reference-link"
+ href="#root/_help_nBAXQFj20hS1">Include Note</a>.</p>
<h2>Compression</h2>
<p>Since Trilium isn't really meant to be primary storage for image data,
it attempts to compress and resize (with pretty aggressive settings) uploaded
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 b1835f6503..c5493882bd 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
@@ -204,6 +204,15 @@
href="#root/_help_ZlN4nump6EbW">Slash Commands</a>. The canvas is added
empty and editable, in a <em>Medium</em> box with its title hidden, and takes
the focus, ready for drawing.</li>
+ <li>To draw or write over an image, select the image and press the <span class="tn-icon bx bxs-pen"></span> <em>Convert image to a drawing canvas</em> button
+ of its toolbar. The image is replaced by an editable drawing canvas in
+ a <em>Medium</em> 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.
+ To move or resize it anyway, right-click an empty spot of the canvas and
+ choose <em>Unlock all</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>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,
@@ -224,7 +233,9 @@
small the box is. In the mobile layout, a narrow or short box switches
it to a compact interface. For more room, choose <em>Full</em>, or show
the title and press <span class="tn-icon bx bx-fullscreen"></span> <em>Fullscreen</em>.</li>
- <li>Pictures added to the drawing are stored in the same attachment.</li>
+ <li>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.</li>
<li>In a <a href="#root/_help_CoFPLs3dRlXc">read-only note</a>, the drawing
can be viewed but not changed.</li>
</ul>
diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.ts
index 7de3bae488..3f6e97ccd7 100644
--- a/apps/server/src/services/notes.spec.ts
+++ b/apps/server/src/services/notes.spec.ts
@@ -1,4 +1,5 @@
-import { BAttribute, becca, becca_easy_mocking, checkImageAttachments, collectCanvasImageFileIds, findBookmarks, findLlmChatLinks, findMindMapLinks, saveLinks } from "@triliumnext/core";
+import { CANVAS_ATTACHMENT_MIME } from "@triliumnext/commons";
+import { BAttachment, BAttribute, becca, becca_easy_mocking, checkImageAttachments, collectCanvasImageFileIds, findBookmarks, findLlmChatLinks, findMindMapLinks, saveLinks } from "@triliumnext/core";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { randomString } from "./utils.js";
@@ -285,6 +286,72 @@ describe("checkImageAttachments", () => {
getAttachments.mockRestore();
}
});
+
+ it("keeps the images that an embedded canvas drawing shows 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" }
+ ]
+ });
+ mockAttachmentSaves(note);
+ const [ drawing, shown, removed ] = note.getAttachments();
+ setDrawingContent(drawing, "f1.png");
+ shown.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";
+
+ checkImageAttachments(note, embedOf("drawing1"));
+ expect(drawing.utcDateScheduledForErasureSince).toBeFalsy();
+ expect(shown.utcDateScheduledForErasureSince).toBeNull();
+ expect(removed.utcDateScheduledForErasureSince).toBeTruthy();
+
+ checkImageAttachments(note, "<p>The drawing is gone.</p>");
+ expect(drawing.utcDateScheduledForErasureSince).toBeTruthy();
+ expect(shown.utcDateScheduledForErasureSince).toBeTruthy();
+ });
+
+ it("copies along with a foreign canvas drawing 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" }
+ ]
+ });
+ const [ foreign, ...images ] = source.getAttachments();
+ setDrawingContent(foreign, "f1.png", "f2.png");
+ for (const image of images) {
+ image.getContent = () => new Uint8Array([ 1 ]);
+ }
+
+ const target = buildNote({
+ title: "Target",
+ attachments: [ { title: "f2.png", role: "image", mime: "image/png" } ]
+ });
+ mockAttachmentSaves(target);
+
+ const copies: BAttachment[] = [];
+ const setContent = vi.spyOn(BAttachment.prototype, "setContent")
+ .mockImplementation(function (this: BAttachment) {
+ copies.push(this);
+ });
+ const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ foreign ]);
+
+ try {
+ checkImageAttachments(target, embedOf("foreignDrawing"));
+
+ expect(copies.map(({ ownerId, title }) => ({ ownerId, title }))).toEqual([
+ { ownerId: target.noteId, title: "Canvas.excalidraw" },
+ { ownerId: target.noteId, title: "f1.png" }
+ ]);
+ } finally {
+ getAttachments.mockRestore();
+ setContent.mockRestore();
+ }
+ });
});
describe("Markdown content", () => {
@@ -1122,3 +1189,12 @@ describe("findLlmChatLinks", () => {
function embedOf(attachmentId: string) {
return `<section class="include-note" data-attachment-id="${attachmentId}">` + "</section>";
}
+
+const DRAWING = { title: "Canvas.excalidraw", role: "file", mime: CANVAS_ATTACHMENT_MIME };
+
+/** Gives `drawing` a scene with an image element for each of `fileIds`. */
+function setDrawingContent(drawing: BAttachment, ...fileIds: string[]) {
+ const elements = fileIds.map((fileId) => ({ type: "image", fileId }));
+ const content = JSON.stringify({ type: "excalidraw", version: 2, elements, files: {} });
+ drawing.getContent = () => new TextEncoder().encode(content);
+}
diff --git a/docs/User Guide/User Guide/Note Types/Text/Images.md b/docs/User Guide/User Guide/Note Types/Text/Images.md
index 3c4a730f45..810f801331 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Images.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Images.md
@@ -41,6 +41,10 @@ The first set of options configure the alignment are, in order:
| <span class="tn-icon cke cke-object-inline-right"></span> | Wrap text | ![](3_Images_image.png) | The image will be displayed to the left or the right of the text. |
| <span class="tn-icon cke cke-object-left"></span> | Block align | ![](2_Images_image.png) | Similarly to _Centered image_, the image will be displayed as a block and aligned either to the left or to the right, but not allowing text to flow on either of its sides. |
+### Drawing over an image
+
+To draw or write over an image, press the <span class="tn-icon bx bxs-pen"></span> _Convert image to a drawing canvas_ button of its toolbar. The image becomes a drawing canvas that shows all of it, locked in place. See the drawing canvases section of <a class="reference-link" href="Include%20Note.md">Include Note</a>.
+
## Compression
Since Trilium isn't really meant to be primary storage for image data, it attempts to compress and resize (with pretty aggressive settings) uploaded images before storing them to the database. You may then notice some quality degradation. Basic quality settings is available in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Media_.
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 e1192c6fc7..a1198562ba 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
@@ -120,12 +120,13 @@ An included text note, an included code note and an embedded code file such as a
A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-link" href="../Canvas.md">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a `Canvas.excalidraw` [attachment](../../Basic%20Concepts%20and%20Features/Notes/Attachments.md) of the text note and is saved together with the text.
* 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. To move or resize it anyway, right-click an empty spot of the canvas and choose _Unlock all_. 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.
* 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.
* The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, _Show title_ and _Convert to link_ to its _More actions_ menu.
* 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.
+* 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 can be viewed but not changed.
### Limitations
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 4e12d103cf..f4cb477f06 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -140,6 +140,11 @@ declare global {
* without embeds leave it out.
*/
focusContentEmbed?(attachmentId: string): void;
+ /**
+ * Attaches a drawing canvas that shows the image at `src`, and answers with the ID of its
+ * attachment, or `null` when that fails. Hosts without drawings leave it out.
+ */
+ convertImageToDrawing?(src: string): Promise<string | null>;
/**
* Reads a page's preview metadata through the host. Never rejects: any failure — network
* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` with
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 6c775a2b57..b42a68137e 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -39,6 +39,7 @@ import AutoformatMath from "./plugins/math/autoformat_math.js";
import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";
import CopyLinkUrlButton from "./plugins/copy_link_url.js";
import ImageActions from "./plugins/image_actions.js";
+import ImageToDrawing from "./plugins/image_to_drawing.js";
import ClipboardBareImage from "./plugins/clipboard_bare_image.js";
import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";
import ClipboardPageStyles from "./plugins/clipboard_page_styles.js";
@@ -118,6 +119,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
CopyAnchorLinkButton,
CopyLinkUrlButton,
ImageActions,
+ ImageToDrawing,
ClipboardImageEmbed,
ClipboardBareImage,
ClipboardPageStyles,
diff --git a/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts b/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts
new file mode 100644
index 0000000000..f8bc63378c
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts
@@ -0,0 +1,140 @@
+import {
+ ButtonView,
+ Essentials,
+ Image,
+ ImageBlock,
+ ImageCaption,
+ ImageInline,
+ Paragraph,
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ type ClassicEditor
+} from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
+import ContentEmbed from "./content_embed/content_embed.js";
+import ImageToDrawing from "./image_to_drawing.js";
+
+const SRC = "api/attachments/i1/image/a.png";
+const IMAGE = `<imageBlock src="${SRC}"></imageBlock>`;
+const CAPTIONED_IMAGE = `<imageBlock src="${SRC}"><caption>Sketch</caption></imageBlock>`;
+const EMBED = "<contentEmbed attachmentId=\"d1\" boxSize=\"medium\" editable=\"true\""
+ + " hideTitle=\"true\">";
+
+describe("ImageToDrawing", () => {
+ let editor: ClassicEditor;
+ let calls: string[];
+ let convertImageToDrawing: ReturnType<typeof vi.fn<(src: string) => Promise<string | null>>>;
+
+ beforeEach(async () => {
+ calls = [];
+ convertImageToDrawing = vi.fn(async (src: string) => {
+ calls.push(`convert ${src}`);
+ return "d1";
+ });
+ installGlobMock({
+ getComponentByEl: () => ({
+ convertImageToDrawing,
+ focusContentEmbed: (id: string) => calls.push(`focus ${id}`),
+ loadEmbeddedAttachment: (id: string) => calls.push(`load ${id}`)
+ })
+ });
+ editor = await createTestEditor([
+ Essentials, Paragraph, Image, ImageBlock, ImageInline, ImageCaption, ContentEmbed,
+ ImageToDrawing
+ ]);
+ });
+
+ /** Holds the next conversion until the returned function finishes it with an attachment ID. */
+ function holdConversion() {
+ let finish: (id: string | null) => void = () => undefined;
+ convertImageToDrawing.mockImplementationOnce(() => new Promise((resolve) => {
+ finish = resolve;
+ }));
+ return (id: string | null) => finish(id);
+ }
+
+ it("replaces a block image with an editable, untitled Medium embed in one step", async () => {
+ setModelData(editor.model, `<paragraph>a</paragraph>[${CAPTIONED_IMAGE}]`);
+
+ await editor.execute("convertImageToDrawing");
+
+ expect(getModelData(editor.model)).toBe(
+ `<paragraph>a</paragraph>[${EMBED}<caption>Sketch</caption></contentEmbed>]`
+ );
+ expect(calls).toEqual([ `convert ${SRC}`, "focus d1", "load d1" ]);
+
+ editor.execute("undo");
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(`<paragraph>a</paragraph>${CAPTIONED_IMAGE}`);
+ });
+
+ it("leaves an empty caption behind", async () => {
+ setModelData(editor.model, `[<imageBlock src="${SRC}"><caption></caption></imageBlock>]`);
+
+ await editor.execute("convertImageToDrawing");
+
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(`${EMBED}</contentEmbed>`);
+ });
+
+ it("is enabled for a selected block image only, and not while it converts one", async () => {
+ const command = editor.commands.get("convertImageToDrawing");
+
+ setModelData(editor.model, "<paragraph>[]a</paragraph>");
+ expect(command?.isEnabled).toBe(false);
+
+ setModelData(editor.model,
+ `<paragraph>a[<imageInline src="${SRC}"></imageInline>]</paragraph>`);
+ expect(command?.isEnabled).toBe(false);
+
+ setModelData(editor.model, `[${IMAGE}]`);
+ expect(command?.isEnabled).toBe(true);
+
+ const finish = holdConversion();
+ const conversion = editor.execute("convertImageToDrawing");
+ expect(command?.isEnabled).toBe(false);
+
+ finish(null);
+ await conversion;
+ expect(command?.isEnabled).toBe(true);
+ });
+
+ it("keeps the image when the host fails, and inserts nothing once it is gone", async () => {
+ setModelData(editor.model, `<paragraph>a</paragraph>[${IMAGE}]`);
+ convertImageToDrawing.mockResolvedValueOnce(null);
+ await editor.execute("convertImageToDrawing");
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(`<paragraph>a</paragraph>${IMAGE}`);
+
+ const finish = holdConversion();
+ const conversion = editor.execute("convertImageToDrawing");
+ editor.model.change((writer) => {
+ const image = editor.model.document.getRoot()?.getChild(1);
+ if (image) writer.remove(image);
+ });
+ finish("d1");
+ await conversion;
+
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe("<paragraph>a</paragraph>");
+ expect(calls).not.toContain("focus d1");
+ });
+
+ it("adds a button that runs the command and returns the focus to the editor", async () => {
+ const button = editor.ui.componentFactory.create("convertImageToDrawing") as ButtonView;
+ const focus = vi.spyOn(editor.editing.view, "focus");
+ expect(button.label).toBe("Convert image to a drawing canvas");
+ expect(button.isEnabled).toBe(false);
+
+ setModelData(editor.model, `[${IMAGE}]`);
+ expect(button.isEnabled).toBe(true);
+
+ button.fire("execute");
+ expect(focus).toHaveBeenCalled();
+ await vi.waitFor(() => expect(getModelData(editor.model, { withoutSelection: true }))
+ .toContain("contentEmbed"));
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/image_to_drawing.ts b/packages/ckeditor5/src/plugins/image_to_drawing.ts
new file mode 100644
index 0000000000..51639dba17
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/image_to_drawing.ts
@@ -0,0 +1,118 @@
+import { ButtonView, Command, ImageUtils, Plugin, type ModelElement } from "ckeditor5";
+import bxsPen from "boxicons/svg/solid/bxs-pen.svg?raw";
+
+/**
+ * Adds the `convertImageToDrawing` button to the image toolbar. The host attaches a drawing canvas
+ * that shows the selected block image, which an editable, untitled Medium embed of it replaces.
+ */
+export default class ImageToDrawing extends Plugin {
+
+ static get requires() {
+ return [ ImageUtils ] as const;
+ }
+
+ static get pluginName() {
+ return "ImageToDrawing" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ const t = editor.t;
+ const command = new ConvertImageToDrawingCommand(editor);
+ editor.commands.add("convertImageToDrawing", command);
+
+ editor.ui.componentFactory.add("convertImageToDrawing", (locale) => {
+ const button = new ButtonView(locale);
+ button.set({
+ label: t("Convert image to a drawing canvas"),
+ icon: bxsPen,
+ tooltip: true
+ });
+ button.bind("isEnabled").to(command);
+ this.listenTo(button, "execute", () => {
+ void editor.execute("convertImageToDrawing");
+ // `ContentEmbed` focuses the new drawing only while the editor has the focus.
+ editor.editing.view.focus();
+ });
+ return button;
+ });
+ }
+
+}
+
+/**
+ * Replaces the selected block image with an embed of a drawing canvas that shows it. Resolves once
+ * the embed is in place, or once the host fails to attach the drawing.
+ */
+export class ConvertImageToDrawingCommand extends Command {
+
+ override refresh() {
+ const model = this.editor.model;
+ const image = this.getSelectedBlockImage();
+
+ this.isEnabled = !!image && typeof image.getAttribute("src") === "string"
+ && model.schema.checkChild(model.createPositionBefore(image), "contentEmbed");
+ }
+
+ override async execute() {
+ const editor = this.editor;
+ const image = this.getSelectedBlockImage();
+ const src = image?.getAttribute("src");
+ if (!image || typeof src !== "string") return;
+
+ const host = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
+ this.forceDisabled(CONVERTING);
+ let attachmentId: string | null | undefined;
+ try {
+ attachmentId = await host.convertImageToDrawing?.(src);
+ } finally {
+ this.clearForceDisabled(CONVERTING);
+ }
+ if (!attachmentId || !isInDocument(image)) return;
+
+ host.focusContentEmbed?.(attachmentId);
+ // CKEditor's renderer draws a figure that replaces another in the same render twice, so
+ // the embed goes in and the image out in two changes, of one batch for a single undo.
+ const model = editor.model;
+ const { embed, batch } = model.change((writer) => {
+ const embed = writer.createElement("contentEmbed", {
+ attachmentId,
+ boxSize: "medium",
+ hideTitle: true,
+ editable: true
+ });
+ const caption = getCaption(image);
+ if (caption && !caption.isEmpty) {
+ writer.append(writer.cloneElement(caption), embed);
+ }
+ writer.insert(embed, writer.createPositionAfter(image));
+ return { embed, batch: writer.batch };
+ });
+ model.enqueueChange(batch, (writer) => {
+ writer.remove(image);
+ writer.setSelection(embed, "on");
+ });
+ }
+
+ private getSelectedBlockImage() {
+ const selection = this.editor.model.document.selection;
+ const image = this.editor.plugins.get(ImageUtils).getClosestSelectedImageElement(selection);
+ return image?.is("element", "imageBlock") ? image : null;
+ }
+
+}
+
+const CONVERTING = "converting";
+
+function getCaption(image: ModelElement) {
+ for (const child of image.getChildren()) {
+ if (child.is("element", "caption")) return child;
+ }
+ return null;
+}
+
+/** Whether `element` is still in the document, rather than removed while the host worked. */
+function isInDocument(element: ModelElement) {
+ const root = element.root;
+ return root.is("rootElement") && root.rootName !== "$graveyard";
+}
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 1b4a17ecc2..46eefb1434 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, 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, 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";
@@ -23,7 +23,7 @@ import { evaluateTemplateSafe } from "./safe_template.js";
import { sanitizeHtml } from "./sanitizer.js";
import { getSql } from "./sql/index.js";
import type TaskContext from "./task_context.js";
-import { decodeBase64 } from "./utils/binary.js";
+import { decodeBase64, decodeUtf8 } from "./utils/binary.js";
import date_utils from "./utils/date.js";
import { isValidEntityId, newEntityId, replaceAll, toMap, unescapeHtml } from "./utils/index.js";
import ws from "./ws.js";
@@ -496,7 +496,8 @@ function writeExtractedText(blobId: string | undefined, extractedText: string, i
export function checkImageAttachments(note: BNote, content: string) {
// Canvas references images by the Excalidraw fileId stored as the attachment *title* in its
// scene JSON, so orphans are detected by title; every other type references them by attachmentId
- // embedded in the content (an image URL or attachment link).
+ // embedded in the content (an image URL or attachment link), and by title from the scenes of
+ // the canvas drawings it embeds.
const isCanvas = note.type === "canvas";
const foundAttachmentIds = new Set<string>();
/**
@@ -505,7 +506,6 @@ export function checkImageAttachments(note: BNote, content: string) {
* reached any other way was put there by hand and takes the role that says so.
*/
const previewPictureIds = new Set<string>();
- const foundCanvasFileIds = isCanvas ? collectCanvasImageFileIds(content) : new Set<string>();
if (!isCanvas) {
let match;
@@ -546,6 +546,9 @@ export function checkImageAttachments(note: BNote, content: string) {
}
const attachments = note.getAttachments();
+ const foundFileIds = isCanvas
+ ? collectCanvasImageFileIds(content)
+ : collectDrawingImageFileIds(attachments, foundAttachmentIds);
for (const attachment of attachments) {
// Only attachments that live in the note content are auto-scheduled for erasure when nothing
@@ -572,9 +575,8 @@ export function checkImageAttachments(note: BNote, content: string) {
continue;
}
- const attachmentInContent = isCanvas
- ? foundCanvasFileIds.has(attachment.title)
- : !!attachment.attachmentId && foundAttachmentIds.has(attachment.attachmentId);
+ const attachmentInContent = foundFileIds.has(attachment.title)
+ || (!!attachment.attachmentId && foundAttachmentIds.has(attachment.attachmentId));
if (attachment.utcDateScheduledForErasureSince && attachmentInContent) {
attachment.utcDateScheduledForErasureSince = null;
@@ -632,6 +634,8 @@ 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);
+
// 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
// own, but a deduplicated role (a link preview's favicon, one per site rather than one per
@@ -682,6 +686,44 @@ 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>();
+ for (const attachment of attachments) {
+ if (attachment.mime !== CANVAS_ATTACHMENT_MIME
+ || !foundAttachmentIds.has(attachment.attachmentId ?? "")) {
+ continue;
+ }
+
+ for (const fileId of collectCanvasImageFileIds(decodeUtf8(attachment.getContent()))) {
+ fileIds.add(fileId);
+ }
+ }
+ return fileIds;
+}
+
+/**
+ * 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.
+ */
+function copyDrawingImages(note: BNote, drawing: BAttachment) {
+ const owner = becca.getNote(drawing.ownerId);
+ if (drawing.mime !== CANVAS_ATTACHMENT_MIME || !owner) {
+ return;
+ }
+
+ const fileIds = collectCanvasImageFileIds(decodeUtf8(drawing.getContent()));
+ for (const image of owner.getAttachments()) {
+ if (!fileIds.has(image.title) || note.getAttachmentByTitle(image.title)) {
+ continue;
+ }
+
+ const copy = image.copy();
+ copy.ownerId = note.noteId;
+ copy.setContent(image.getContent(), { forceSave: true });
+ }
+}
+
function findImageLinks(content: string, foundLinks: FoundLink[]) {
const re = /src="[^"]*api\/images\/([a-zA-Z0-9_]+)\//g;
let match;