Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doranebcf146e124b
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index c6dd0b9852..dd2b12ebe9 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -1045,8 +1045,8 @@ export function useElementSize(ref: RefObject<HTMLElement | null>) {
/**
* Returns a function that runs a callback at once while the element of `ref` is shown, and
* otherwise once it is shown again, for example when its tab is selected. While the element is
- * hidden, only the last callback runs. Without an element, or with one that is not in the page
- * yet, the callback runs at once.
+ * hidden, only the last callback runs, so a stale result must be dropped before it is passed.
+ * Without an element, or with one that is not in the page yet, the callback runs at once.
*/
export function useWhenShown(ref: RefObject<Element | null> | undefined) {
const waitingRef =
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 d851583399..5b34f1b568 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
@@ -634,6 +634,51 @@ describe("useCanvasDrawingPersistence", () => {
}));
});
+ it("waits for an action that the user starts while the images of a save load", async () => {
+ const owner = buildNote({ title: "Owner" });
+ owner.getAttachmentsByRole = vi.fn(async () => [
+ { attachmentId: "img9", title: "f9.png" }
+ ]) as never;
+ let loadImage = () => {};
+ const isImageLoaded = new Promise<void>((resolve) => {
+ loadImage = resolve;
+ });
+ vi.stubGlobal("fetch", vi.fn(async () => {
+ await isImageLoaded;
+ return { ok: true, blob: async () => new Blob([ "ABC" ], { type: "image/png" }) };
+ }));
+ const loaded = [ { id: "r1", type: "rectangle", version: 3, versionNonce: 1 } ];
+ const { attachment, getBlob } = buildAttachment({ elements: loaded });
+ const drawing = { ...attachment, ownerId: owner.noteId } as unknown as FAttachment;
+ sceneFiles = {};
+ showUpdatedElements();
+ await mount(drawing, buildEditor());
+ change();
+ sceneElements = loaded;
+ change();
+
+ const image = { id: "i9", type: "image", version: 1, versionNonce: 2, fileId: "f9.png" };
+ const saved = [ loaded[0], image ];
+ getBlob.mockResolvedValue({ content: JSON.stringify({ elements: saved }) });
+ await reportSave();
+ appState = { ...appState, editingTextElement: { id: "t1" } };
+ await act(async () => {
+ loadImage();
+ // `FileReader` reads the image over several turns.
+ for (let turn = 0; turn < 5; turn++) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ });
+ expect(updateScene).not.toHaveBeenCalled();
+
+ appState = { ...appState, editingTextElement: null };
+ await act(async () => {
+ change();
+ });
+ await vi.waitFor(() => expect(updateScene).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ elements: saved })));
+ });
+
it("shows a save that lands while the drawing loads once Excalidraw shows it", async () => {
const loaded = [ { id: "r1", type: "rectangle", version: 3, versionNonce: 1 } ];
const { attachment, getBlob } = 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 9f6a7e61b0..bed6aa4acd 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -458,10 +458,13 @@ export function useCanvasDrawingPersistence(
const isCurrent = () => request === showRequestRef.current && apiRef.current === api
&& editor?.getUnsavedContent() === undefined;
if (!api || !isCurrent()) return;
- if (isInteracting(api.getAppState())) {
+ // The save waits until the user ends the change in progress.
+ const isUserChanging = () => {
+ if (!isInteracting(api.getAppState())) return false;
isSaveWaitingRef.current = true;
- return;
- }
+ return true;
+ };
+ if (isUserChanging()) return;
const content = parseContent(savedContent, attachment);
const elements = restoreLoadedElements(content.elements);
@@ -483,7 +486,7 @@ export function useCanvasDrawingPersistence(
elements: elements.filter((element) =>
"fileId" in element && element.fileId && !shownFiles[element.fileId])
});
- if (!isCurrent()) return;
+ if (!isCurrent() || isUserChanging()) return;
referencedFileIds.current = new Set([
...referencedFileIds.current, ...loaded.referencedFileIds
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
index f271d3ea88..883224147f 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -641,6 +641,54 @@ describe("CodeEmbed", () => {
expect(view.state.doc.toString()).toBe("new");
});
+ it("shows the latest content once shown, when hidden fetches land out of order", async () => {
+ const container = document.body.appendChild(document.createElement("div"));
+ const attachment = buildAttachment("script.py");
+ const { figure } = await mount(attachment, buildEditor(), {
+ content: "a",
+ isEditable: true,
+ container
+ });
+ const view = await findView(figure);
+ const resizeCallbacks: ((entries: unknown[]) => void)[] = [];
+ const { ResizeObserver } = globalThis;
+ globalThis.ResizeObserver = class {
+ constructor(callback: (entries: unknown[]) => void) {
+ resizeCallbacks.push(callback);
+ }
+ observe() {}
+ disconnect() {}
+ } as unknown as typeof ResizeObserver;
+
+ try {
+ container.style.display = "none";
+ const resolvers: ((blob: FBlob) => void)[] = [];
+ attachment.getBlob = () => new Promise((resolve) => resolvers.push(resolve));
+ const saved = new LoadResults([]);
+ saved.addAttachmentRow({ attachmentId: attachment.attachmentId } as never, "any");
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", { loadResults: saved });
+ await parent.handleEvent("entitiesReloaded", { loadResults: saved });
+ });
+ await act(async () => {
+ resolvers[1](buildBlob("new"));
+ });
+ await act(async () => {
+ resolvers[0](buildBlob("old"));
+ });
+ expect(view.state.doc.toString()).toBe("a");
+
+ container.style.display = "";
+ await act(async () => {
+ for (const callback of resizeCallbacks) callback([]);
+ });
+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("new"));
+ } finally {
+ globalThis.ResizeObserver = ResizeObserver;
+ container.remove();
+ }
+ });
+
it("shows how the saving goes in the title row of its embed while it edits", async () => {
const listeners = new Set<() => void>();
let state: SaveState = "unsaved";
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index 13b4846ea0..a80fa0c9ad 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -276,11 +276,14 @@ export function useSavedContent(
const rows = loadResults.getAttachmentRows();
if (rows.some((row) => row.attachmentId === entity.attachmentId)) {
const requestId = ++requestIdRef.current;
- void entity.getBlob().then((blob) => whenShown(() => {
- if (requestId === requestIdRef.current) {
- setAttachmentContent(blob?.content);
- }
- }));
+ void entity.getBlob().then((blob) => {
+ if (requestId !== requestIdRef.current) return;
+ whenShown(() => {
+ if (requestId === requestIdRef.current) {
+ setAttachmentContent(blob?.content);
+ }
+ });
+ });
}
});
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
index cbd4a3c86a..7218447787 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
@@ -262,6 +262,55 @@ describe("TextEmbed", () => {
.toBe("<div><p>Newer</p></div>");
});
+ it("shows the newest content once shown, when hidden reads land out of order", async () => {
+ const note = buildTextNote("hidden");
+ const { figure } = await mount(note, buildEditor());
+ await settle();
+ const host = figure.parentElement;
+ if (!host) throw new Error("Expected the host editor.");
+ const resizeCallbacks: (() => void)[] = [];
+ const { ResizeObserver } = globalThis;
+ globalThis.ResizeObserver = class {
+ constructor(callback: () => void) {
+ resizeCallbacks.push(callback);
+ }
+ observe() {}
+ disconnect() {}
+ } as unknown as typeof ResizeObserver;
+
+ try {
+ host.style.display = "none";
+ let slowRead = () => {};
+ note.getBlob = () => new Promise((resolve) => {
+ slowRead = () => resolve(buildBlob("<p>Older</p>"));
+ });
+ await act(async () => {
+ await reloadNoteContent(note);
+ });
+ note.getBlob = async () => buildBlob("<p>Newer</p>");
+ await act(async () => {
+ await reloadNoteContent(note);
+ });
+ await settle();
+ await act(async () => {
+ slowRead();
+ });
+ await settle();
+ expect(figure.querySelector(".editable-embed-preview")?.innerHTML)
+ .toBe("<div><p>hidden</p></div>");
+
+ host.style.display = "";
+ await act(async () => {
+ for (const callback of resizeCallbacks) callback();
+ });
+ await settle();
+ expect(figure.querySelector(".editable-embed-preview")?.innerHTML)
+ .toBe("<div><p>Newer</p></div>");
+ } finally {
+ globalThis.ResizeObserver = ResizeObserver;
+ }
+ });
+
it("shows a save that landed before it listened for saves", async () => {
const note = buildTextNote("late");
note.getBlob = async () => buildBlob("<p>Saved meanwhile</p>");
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
index 651ef7ad82..e04f9588db 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
@@ -92,8 +92,9 @@ function useShownContent(
const refresh = useCallback(async (isSavedElsewhere = false) => {
const requestId = ++requestIdRef.current;
const blob = await note.getBlob();
+ if (!blob || requestId !== requestIdRef.current) return;
const update = () => {
- if (blob && requestId === requestIdRef.current && !closingSaveRef.current) {
+ if (requestId === requestIdRef.current && !closingSaveRef.current) {
setContent(blob.content);
}
};