Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doranf27f076a49e0
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 056f605ed6..83fdc677ea 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
@@ -587,6 +587,36 @@ describe("saveDrawingPicture", () => {
expect(error).toHaveBeenCalledOnce();
});
+ it("writes the pictures of a drawing in order, skipping one replaced as it waits", async () => {
+ let finishFirst: () => void = () => {};
+ const post = vi.spyOn(server, "post")
+ .mockImplementationOnce(() => new Promise((resolve) => {
+ finishFirst = () => resolve(undefined);
+ }))
+ .mockResolvedValue(undefined);
+ vi.mocked(exportToSvg)
+ .mockResolvedValueOnce(svgOf("first"))
+ .mockResolvedValueOnce(svgOf("second"))
+ .mockResolvedValueOnce(svgOf("third"));
+ const save = (count: number) => saveDrawingPicture(drawing, JSON.stringify({
+ elements: Array.from({ length: count }, (_, index) => ({ ...image, id: `i${index}` }))
+ }), { f1: IMAGE } as never);
+
+ const first = save(1);
+ await vi.waitFor(() => expect(post).toHaveBeenCalledOnce());
+ const second = save(2);
+ await vi.waitFor(() => expect(exportToSvg).toHaveBeenCalledTimes(2));
+ await new Promise((resolve) => setTimeout(resolve));
+ expect(post).toHaveBeenCalledOnce();
+
+ const third = save(3);
+ finishFirst();
+ await Promise.all([ first, second, third ]);
+ expect(getSavedPictures(post)).toEqual([
+ expect.stringMatching(/^<svg id="first"/), expect.stringMatching(/^<svg id="third"/)
+ ]);
+ });
+
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"));
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
index 9653896c9b..dcfdd5b1ea 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -511,6 +511,8 @@ export async function exportDrawingPicture(
/** The saved content that the latest picture of each canvas drawing comes from, by its ID. */
const drawnPictureContents = new Map<string, string>();
+/** The last picture write of each canvas drawing, which the next write waits for, by its ID. */
+const pictureWrites = new Map<string, Promise<void>>();
/** The picture of an empty canvas drawing. */
const EMPTY_PICTURE = `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`;
@@ -562,9 +564,6 @@ export async function saveDrawingPicture(
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;
@@ -572,11 +571,17 @@ export async function saveDrawingPicture(
picture.prepend(style);
markBitmaps(picture);
}
- await server.post(`notes/${ownerId}/attachments?matchBy=title`, {
- role: IMAGE_ROLE,
- mime: "image/svg+xml",
- title: getDrawingPictureTitle(attachmentId),
- content: picture?.outerHTML ?? EMPTY_PICTURE
+
+ await queuePictureWrite(attachmentId, async () => {
+ // A newer save draws a picture of its own.
+ if (drawnPictureContents.get(attachmentId) !== content) return;
+
+ 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);
@@ -587,6 +592,20 @@ export async function saveDrawingPicture(
}
}
+/** Runs `write` once the previous picture write of the drawing `attachmentId` is done. */
+async function queuePictureWrite(attachmentId: string, write: () => Promise<void>) {
+ const queued = (pictureWrites.get(attachmentId) ?? Promise.resolve()).then(write);
+ const settled = queued.catch(() => {});
+ pictureWrites.set(attachmentId, settled);
+ try {
+ await queued;
+ } finally {
+ if (pictureWrites.get(attachmentId) === settled) {
+ pictureWrites.delete(attachmentId);
+ }
+ }
+}
+
/**
* Adds `BITMAP_CLASS` to the `<use>` elements of `picture` that place a bitmap. Excalidraw puts each
* image in a `<symbol>`; an SVG image keeps its colors in the dark export.
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 6edd702d3d..5c409bb037 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
@@ -101,15 +101,25 @@ describe("AttachmentSaves", () => {
expect(getContent).toHaveBeenCalledOnce();
});
- it("drops the changes when it saves another note", () => {
+ it("drops the changes when it saves another note, and reports the last one saved after", () => {
const { saves } = setUp();
- saves.scheduleSave(drawing, () => "unsaved");
+ const onSaved = vi.fn();
+ saves.scheduleSave(drawing, () => "first", onSaved);
saves.setNoteId("note1");
- expect(saves.getUnsavedContent("drawing1")).toBe("unsaved");
+ expect(saves.getUnsavedContent("drawing1")).toBe("first");
+ // The previous note saves both changes in the background after the switch.
+ const first = saves.collect();
+ saves.scheduleSave(drawing, () => "second", onSaved);
+ const second = saves.collect();
saves.setNoteId("note2");
expect(saves.getUnsavedContent("drawing1")).toBeUndefined();
+
+ saves.markSaved(first);
+ saves.markSaved(second);
+ saves.markSaved(second);
+ expect(onSaved.mock.calls).toStrictEqual([ [ "second" ] ]);
});
});
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 ba23359fea..9e893da157 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
@@ -23,7 +23,7 @@ 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. */
+ /** Runs with the content once it saves, unless the entity changed again by then. */
onSaved?: (content: string) => void;
/**
* Numbers the change, uniquely among all changes, so that a save drops only the change it
@@ -47,6 +47,8 @@ interface SentRevision {
abstract class PendingSaves<T, I extends object> {
protected pending = new Map<string, PendingSave<T>>();
private lastRevision = 0;
+ /** The revision of the last change to each entity, kept when `pending` drops the change. */
+ private latestRevisions = new Map<string, number>();
private sentRevisions = new WeakMap<I, SentRevision>();
getUnsavedContent(id: string) {
@@ -69,8 +71,9 @@ abstract class PendingSaves<T, I extends object> {
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) {
+ if (sent && this.latestRevisions.get(sent.id) === sent.revision) {
this.pending.delete(sent.id);
+ this.latestRevisions.delete(sent.id);
sent.onSaved?.(sent.content);
}
}
@@ -82,7 +85,9 @@ abstract class PendingSaves<T, I extends object> {
getContent: () => string,
onSaved?: (content: string) => void
) {
- this.pending.set(id, { entity, getContent, onSaved, revision: ++this.lastRevision });
+ const revision = ++this.lastRevision;
+ this.pending.set(id, { entity, getContent, onSaved, revision });
+ this.latestRevisions.set(id, revision);
}
/** One item for each change, with the content read at the time of the call. */
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 5ebb813b36..e98c5801e0 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
@@ -212,8 +212,8 @@
While it is locked, the canvas can be zoomed in on the image but not zoomed
out past it or scrolled beyond its edges. To move or resize the image anyway,
right-click it and choose <em>Unlock</em>. The caption of the image is kept,
- but not its size, alignment or link. Only an image on its own line can
- be converted, not one inside a paragraph. Undo brings the image back.</li>
+ but not its alignment or link. Only an image on its own line can be converted,
+ not one inside a paragraph. Undo brings the image back.</li>
<li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class="tn-icon cke cke-paper-clip"></span><em>Attach file</em> button
becomes a drawing canvas too, in a <em>Medium</em> box titled with the file
name. It starts with <em>Editable</em> off, so the drawing shows but cannot
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 a72572b91e..88d3b7ff0e 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,7 +120,7 @@ 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. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose _Unlock_. The caption of the image is kept, but not its size, alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.
+* To draw or write over an image, select the image and press the <span class="tn-icon bx bxs-pen"></span> _Convert image to a drawing canvas_ button of its toolbar. The image is replaced by an editable drawing canvas in a _Medium_ box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose _Unlock_. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.
* An Excalidraw file (`.excalidraw`) attached with the <span class="tn-icon cke cke-paper-clip"></span>_Attach file_ button becomes a drawing canvas too, in a _Medium_ box titled with the file name. It starts with _Editable_ off, so the drawing shows but cannot be changed until _Editable_ is turned on (see below).
* To draw on a canvas that does not have the focus, click it first. Until then, 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.
* The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class="tn-icon bx bxs-hand"></span> _Hand_ tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts
index 4033cf7ac4..509d75c99e 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts
@@ -43,12 +43,7 @@ function textTopOf(element: Element) {
return range.getBoundingClientRect().top;
}
-/**
- * Measures a tabs block whose first tab shows: the distance of each title from the side of the
- * panel it sits on, how far the first title starts from the start of the panel, how far the text
- * of the second title sits below that of the first, and the corners of the panel and of the first
- * two titles.
- */
+/** Where the titles of a tabs block sit around the panel of its first tab, and their corners. */
function measure(block: Element | null, alignment: TabAlignment) {
expect(block).not.toBeNull();
const titles = [...block?.querySelectorAll(":scope > .trilium-tab > .trilium-tab-title") ?? []];
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index 5cb1de957a..9c5b6e50eb 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -1,4 +1,4 @@
-import { CANVAS_ATTACHMENT_MIME } from "@triliumnext/commons";
+import { CANVAS_ATTACHMENT_MIME, getDrawingPictureTitle } from "@triliumnext/commons";
import ExcelJS from "exceljs";
import { beforeAll, describe, expect, it } from "vitest";
@@ -291,6 +291,28 @@ describe("Files API (core)", () => {
expect(becca.getAttachmentOrThrow(attachmentId).mime).toBe(CANVAS_ATTACHMENT_MIME);
});
+ it("drops the share picture of a drawing whose file it replaces", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has drawing" });
+ const attach = (role: string, mime: string, title: string) =>
+ api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role, mime, title, content: "<svg/>" }
+ });
+ const getTitles = async () =>
+ (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body
+ .map(({ title }) => title)
+ .sort();
+ await attach("file", CANVAS_ATTACHMENT_MIME, "Canvas.excalidraw");
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const drawingId = list.body[0]?.attachmentId ?? "";
+ await attach("image", "image/svg+xml", getDrawingPictureTitle(drawingId));
+ await attach("image", "image/svg+xml", "other.svg");
+ expect(await getTitles()).toHaveLength(3);
+
+ const file = upload("{}", "application/octet-stream", "Drawing.excalidraw");
+ await api.put(`/api/attachments/${drawingId}/file`, { file });
+ expect(await getTitles()).toEqual([ "Canvas.excalidraw", "other.svg" ]);
+ });
+
it("reports a request that carries no file instead of writing an empty one", async () => {
const noteId = await createFileNote();
diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.ts
index 21e9dfc25a..db375fc552 100644
--- a/packages/trilium-core/src/routes/api/files.ts
+++ b/packages/trilium-core/src/routes/api/files.ts
@@ -1,4 +1,4 @@
-import { getAttachedFileMime } from "@triliumnext/commons";
+import { getAttachedFileMime, getDrawingPictureTitle } from "@triliumnext/commons";
import { Request, Response } from "../../http_interface";
import becca from "../../becca/becca";
@@ -86,10 +86,13 @@ function updateAttachment(req: Request<{ attachmentId: string }>) {
};
}
- attachment.getNote().saveRevision();
+ const note = attachment.getNote();
+ note.saveRevision();
attachment.mime = getAttachedFileMime(file.originalname, file.mimetype.toLowerCase());
attachment.setContent(file.buffer, { forceSave: true });
+ // A shared page links the drawing until an edit saves a picture of the new file.
+ note.getAttachmentByTitle(getDrawingPictureTitle(req.params.attachmentId))?.markAsDeleted();
return {
uploaded: true