Skip to content

Build your personal knowledge base with Trilium Notes

fix(canvas): don't let Excalidraw's init reset wipe the loaded scene (closes #10279)

Elian Doran57523087aa91
diff --git a/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx b/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx
index 46a4dc9394..8b9eb14ec6 100644
--- a/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx
@@ -66,7 +66,6 @@ export default function Canvas({ note, noteContext }: TypeWidgetProps) {
<div className="canvas-render" onWheel={onWheel}>
<div className="excalidraw-wrapper" {...noteDrop}>
<Excalidraw
- excalidrawAPI={api => apiRef.current = api}
theme={colorScheme}
viewModeEnabled={isReadOnly || options.is("databaseReadonly")}
zenModeEnabled={false}
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
new file mode 100644
index 0000000000..4911b7839b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
@@ -0,0 +1,199 @@
+/**
+ * Regression tests for https://github.com/TriliumNext/Trilium/issues/10279
+ * ("Canvas view empty (history view works)").
+ *
+ * Excalidraw's async mount initialization resets the scene when it completes, and it hands
+ * out its imperative API *before* that reset lands. Content loaded via `updateScene` in that
+ * window is wiped — and the wipe then looks like a user edit (scene version change) and gets
+ * saved over the note, corrupting it. The first content must therefore be routed through the
+ * `initialData` promise (applied *by* the init reset), and `onChange` must never treat the
+ * still-empty initializing scene as a change worth saving. Only subsequent loads (note
+ * switches on an already-initialized instance) may use `updateScene`.
+ */
+import { ExcalidrawImperativeAPI, ExcalidrawInitialDataState } from "@excalidraw/excalidraw/types";
+import { type RefObject, render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../entities/fnote";
+import server from "../../../services/server";
+import { buildNote } from "../../../test/easy-froca";
+import useCanvasPersistence from "./persistence";
+
+interface FakeElement {
+ id: string;
+ type: string;
+ version: number;
+}
+
+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/>" }))
+}));
+
+vi.stubGlobal("logError", vi.fn());
+vi.stubGlobal("logInfo", vi.fn());
+
+type PersistenceProps = ReturnType<typeof useCanvasPersistence>;
+
+let props: PersistenceProps | undefined;
+
+function Probe({ note, apiRef }: { note: FNote; apiRef: RefObject<ExcalidrawImperativeAPI> }) {
+ props = useCanvasPersistence(note, null, apiRef, "light", false);
+ return null;
+}
+
+function buildCanvasNote(elementIds: string[]) {
+ const elements = elementIds.map((id, i) => ({ id, type: "rectangle", version: 10 + i }));
+ const note = buildNote({
+ title: "Canvas",
+ type: "canvas",
+ content: JSON.stringify({ type: "excalidraw", version: 2, elements, files: {}, appState: {} })
+ });
+ note.getAttachmentsByRole = async () => [];
+ return { note, elements };
+}
+
+function buildApi(sceneElements: () => FakeElement[]) {
+ const updateScene = vi.fn();
+ const api = {
+ updateScene,
+ addFiles: vi.fn(),
+ history: { clear: vi.fn() },
+ getSceneElements: vi.fn(sceneElements),
+ getAppState: vi.fn(() => ({})),
+ getFiles: vi.fn(() => ({})),
+ updateLibrary: vi.fn(async () => [])
+ } as unknown as ExcalidrawImperativeAPI;
+ return { api, updateScene };
+}
+
+async function resolvedInitialData() {
+ return await (props?.initialData as Promise<ExcalidrawInitialDataState | null>);
+}
+
+function loadedElementIds(updateScene: ReturnType<typeof vi.fn>, callIndex = 0) {
+ const { elements } = updateScene.mock.calls[callIndex][0] as { elements: FakeElement[] };
+ return elements.map((el) => el.id);
+}
+
+describe("useCanvasPersistence content loading (#10279)", () => {
+ let container: HTMLElement;
+ let puts: { url: string; content: string }[];
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ props = undefined;
+ puts = [];
+ server.put = vi.fn(async (url: string, data: { content: string }) => {
+ puts.push({ url, content: data.content });
+ return {};
+ }) as typeof server.put;
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.useRealTimers();
+ });
+
+ async function mount(note: FNote, apiRef: RefObject<ExcalidrawImperativeAPI>) {
+ await act(async () => {
+ render(<Probe note={note} apiRef={apiRef} />, container);
+ });
+ // The blob resolves on a microtask after the first effect flush; a second act
+ // cycle lets useNoteBlob's state update land and deliver the content.
+ await act(async () => {});
+ }
+
+ it("routes the first content through initialData, never through updateScene", async () => {
+ const { note } = buildCanvasNote([ "a1", "a2" ]);
+ const { api, updateScene } = buildApi(() => []);
+ const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI>;
+
+ await mount(note, apiRef);
+
+ const initialData = await resolvedInitialData();
+ expect(initialData?.elements?.map((el) => el.id)).toEqual([ "a1", "a2" ]);
+ // Loading via updateScene in the pre-initialization window is what got wiped.
+ expect(updateScene).not.toHaveBeenCalled();
+ });
+
+ it("does not save the still-empty scene before the initial content is applied (the corruption path)", async () => {
+ const { note, elements } = buildCanvasNote([ "a1", "a2" ]);
+ let sceneElements: FakeElement[] = [];
+ const { api } = buildApi(() => sceneElements);
+ const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI>;
+
+ await mount(note, apiRef);
+ await resolvedInitialData();
+
+ // Excalidraw fires onChange during initialization while the scene is still empty
+ // (this is the 25 -> 0 wipe observed in the field). It must not schedule a save.
+ props?.onChange?.([], {} as never, {} as never);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(puts).toEqual([]);
+
+ // Initialization completes: the initial content lands in the scene. Still no save —
+ // this is a load, not a user edit.
+ sceneElements = elements;
+ props?.onChange?.([], {} as never, {} as never);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(puts).toEqual([]);
+
+ // A real user edit afterwards is saved normally, with the full scene.
+ sceneElements = [ { ...elements[0], version: 99 }, elements[1] ];
+ props?.onChange?.([], {} as never, {} as never);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(puts).toHaveLength(1);
+ expect(puts[0].url).toBe(`notes/${note.noteId}/data`);
+ const saved = JSON.parse(puts[0].content) as { elements: FakeElement[] };
+ expect(saved.elements.map((el) => el.id)).toEqual([ "a1", "a2" ]);
+ });
+
+ it("loads a subsequent note via updateScene once initialData is consumed", async () => {
+ const { note: noteA } = buildCanvasNote([ "a1" ]);
+ const { note: noteB } = buildCanvasNote([ "b1" ]);
+ const { api, updateScene } = buildApi(() => []);
+ const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI>;
+
+ await mount(noteA, apiRef);
+ await resolvedInitialData();
+
+ await mount(noteB, apiRef);
+
+ expect(updateScene).toHaveBeenCalledTimes(1);
+ expect(loadedElementIds(updateScene)).toEqual([ "b1" ]);
+ });
+
+ it("stashes a subsequent note's content while the API is unavailable and replays it on arrival", async () => {
+ const { note: noteA } = buildCanvasNote([ "a1" ]);
+ const { note: noteB } = buildCanvasNote([ "b1" ]);
+ const { api, updateScene } = buildApi(() => []);
+ const apiRef = { current: null } as RefObject<ExcalidrawImperativeAPI>;
+
+ await mount(noteA, apiRef);
+ await resolvedInitialData();
+
+ // The user switches notes at a moment the imperative API is (still) unavailable.
+ await mount(noteB, apiRef);
+ expect(updateScene).not.toHaveBeenCalled();
+
+ await act(async () => {
+ props?.excalidrawAPI?.(api);
+ });
+
+ expect(updateScene).toHaveBeenCalledTimes(1);
+ expect(loadedElementIds(updateScene)).toEqual([ "b1" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
index 61b44a82ad..f3a509cc5f 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -1,6 +1,7 @@
import { exportToSvg, getSceneVersion } from "@excalidraw/excalidraw";
import { ExcalidrawElement, NonDeletedExcalidrawElement } from "@excalidraw/excalidraw/element/types";
-import { AppState, BinaryFileData, ExcalidrawImperativeAPI, ExcalidrawProps, LibraryItem } from "@excalidraw/excalidraw/types";
+import { AppState, BinaryFileData, BinaryFiles, ExcalidrawImperativeAPI, ExcalidrawInitialDataState, ExcalidrawProps, LibraryItem } from "@excalidraw/excalidraw/types";
+import { deferred, type DeferredPromise } from "@triliumnext/commons";
import { RefObject } from "preact";
import { useRef } from "preact/hooks";
@@ -53,62 +54,148 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
const appStateToCompare = useRef<Partial<ImportantAppState>>({});
- const spacedUpdate = useEditorSpacedUpdate({
- note,
- noteContext,
- noteType: "canvas",
- onContentChange(newContent) {
- const api = apiRef.current;
- if (!api) return;
-
- libraryCache.current = [];
- attachmentMetadata.current = [];
- persistedImageFileIds.current = new Set();
+ // The first content load must go through Excalidraw's `initialData` promise, not
+ // `updateScene`: Excalidraw's async mount initialization RESETS the scene when it
+ // completes, and it hands out the imperative API before that reset lands. Anything
+ // loaded via `updateScene` in that window is wiped — and the wipe then looks like a
+ // user edit and gets saved over the note (#10279). Excalidraw awaits this promise and
+ // applies its value as part of that very reset, so the first load cannot be clobbered.
+ const initialDataRef = useRef<DeferredPromise<ExcalidrawInitialDataState | null>>();
+ if (!initialDataRef.current) {
+ initialDataRef.current = deferred<ExcalidrawInitialDataState | null>();
+ }
+ const initialData = initialDataRef.current;
+
+ // Whether `initialData` has been resolved; until then every incoming content belongs to
+ // the initial load (latest one wins via the run counter below).
+ const initialDataResolvedRef = useRef(false);
+ const initialLoadRunRef = useRef(0);
+
+ // False from resolving `initialData` with a non-empty scene until Excalidraw has actually
+ // applied it. In that window the scene is still empty, so `onChange` must not interpret
+ // it as "the user deleted everything" and schedule a save.
+ const initialSceneAppliedRef = useRef(true);
+
+ async function loadInitialContent(newContent: string) {
+ const runId = ++initialLoadRunRef.current;
+ const loadedNoteId = note.noteId;
+ activeNoteIdRef.current = loadedNoteId;
+
+ const content = parseContent(newContent, note);
+
+ // Legacy notes carry inline images in `content.files` (a fileId-keyed record);
+ // current notes store them as attachments. Both go into `initialData.files`.
+ const files: BinaryFiles = {};
+ for (const file of Object.values(content.files ?? {})) {
+ files[file.id] = file;
+ }
- // The note this load run belongs to; async results below are ignored if it's superseded.
- const loadedNoteId = note.noteId;
- activeNoteIdRef.current = loadedNoteId;
+ try {
+ const [ imageResult, libraryResult ] = await Promise.all([ loadImageAttachments(note), loadLibrary(note) ]);
+ if (initialLoadRunRef.current !== runId) return; // superseded by a newer load
- // load saved content into excalidraw canvas
- let content: CanvasContent = {
- elements: [],
- files: [],
- appState: {}
- };
- if (newContent) {
- try {
- content = JSON.parse(newContent) as CanvasContent;
- } catch (err) {
- console.error("Error parsing content. Probably note.type changed. Starting with empty canvas", note, err);
- }
+ for (const file of imageResult.files) {
+ files[file.id] = file;
}
+ persistedImageFileIds.current = new Set(imageResult.metadata.map((m) => m.fileId));
- loadData(api, content, theme);
+ libraryCache.current = libraryResult.libraryItems;
+ attachmentMetadata.current = libraryResult.metadata;
- // Images live as attachments (titled with their fileId); fetch them, rebuild their
- // data URLs and inject them so elements referencing those fileIds render. Legacy notes
- // that still carry inline images in `content.files` were already loaded by loadData().
- loadImageAttachments(note).then(({ files, metadata }) => {
- if (activeNoteIdRef.current !== loadedNoteId) return; // note switched mid-load
- if (files.length > 0) {
- api.addFiles(files);
- }
- persistedImageFileIds.current = new Set(metadata.map((m) => m.fileId));
+ const expectedSceneVersion = getSceneVersion(content.elements ?? []);
+ currentSceneVersion.current = expectedSceneVersion;
+ initialSceneAppliedRef.current = expectedSceneVersion === 0;
+ initialDataResolvedRef.current = true;
+
+ initialData.resolve({
+ elements: content.elements ?? [],
+ appState: { ...content.appState, theme },
+ files,
+ libraryItems: libraryResult.libraryItems
+ });
+ } catch (err) {
+ console.error("Failed to prepare initial canvas data", err);
+ if (initialLoadRunRef.current !== runId) return;
+ initialDataResolvedRef.current = true;
+ initialSceneAppliedRef.current = true;
+ // Resolve anyway so Excalidraw does not stay on its loading screen forever.
+ initialData.resolve({
+ elements: content.elements ?? [],
+ appState: { ...content.appState, theme },
+ files
});
+ }
+ }
- // Initialize tracking state after loading to prevent redundant updates from initial onChange events
- currentSceneVersion.current = getSceneVersion(api.getSceneElements());
+ // Content that arrived after the initial load but before the imperative API was
+ // available (defensive; replayed by the `excalidrawAPI` callback below).
+ const pendingContentRef = useRef<string | null>(null);
- // load the library state
- loadLibrary(note).then(({ libraryItems, metadata }) => {
- if (activeNoteIdRef.current !== loadedNoteId) return; // note switched mid-load
- // Update the library and save to independent variables
- api.updateLibrary({ libraryItems, merge: false });
+ function loadContent(api: ExcalidrawImperativeAPI, newContent: string) {
+ libraryCache.current = [];
+ attachmentMetadata.current = [];
+ persistedImageFileIds.current = new Set();
- // save state of library to compare it to the new state later.
- libraryCache.current = libraryItems;
- attachmentMetadata.current = metadata;
- });
+ // The note this load run belongs to; async results below are ignored if it's superseded.
+ const loadedNoteId = note.noteId;
+ activeNoteIdRef.current = loadedNoteId;
+
+ const content = parseContent(newContent, note);
+
+ loadData(api, content, theme);
+
+ // Images live as attachments (titled with their fileId); fetch them, rebuild their
+ // data URLs and inject them so elements referencing those fileIds render. Legacy notes
+ // that still carry inline images in `content.files` were already loaded by loadData().
+ loadImageAttachments(note).then(({ files, metadata }) => {
+ if (activeNoteIdRef.current !== loadedNoteId) return; // note switched mid-load
+ if (files.length > 0) {
+ api.addFiles(files);
+ }
+ persistedImageFileIds.current = new Set(metadata.map((m) => m.fileId));
+ });
+
+ // Initialize tracking state after loading to prevent redundant updates from initial onChange events
+ currentSceneVersion.current = getSceneVersion(api.getSceneElements());
+
+ // load the library state
+ loadLibrary(note).then(({ libraryItems, metadata }) => {
+ if (activeNoteIdRef.current !== loadedNoteId) return; // note switched mid-load
+ // Update the library and save to independent variables
+ api.updateLibrary({ libraryItems, merge: false });
+
+ // save state of library to compare it to the new state later.
+ libraryCache.current = libraryItems;
+ attachmentMetadata.current = metadata;
+ });
+ }
+
+ // Latest-render closure over `note`/`theme` for the replay: `excalidrawAPI` fires only once
+ // per Excalidraw mount, so it must not load through the closure it captured back then if
+ // the user switched notes before the API arrived.
+ const loadContentRef = useRef(loadContent);
+ loadContentRef.current = loadContent;
+
+ const spacedUpdate = useEditorSpacedUpdate({
+ note,
+ noteContext,
+ noteType: "canvas",
+ onContentChange(newContent) {
+ // The first content belongs to Excalidraw's mount initialization and must be
+ // routed through `initialData` (see above), never through `updateScene`.
+ if (!initialDataResolvedRef.current) {
+ void loadInitialContent(newContent); // errors handled internally
+ return;
+ }
+
+ const api = apiRef.current;
+ if (!api) {
+ pendingContentRef.current = newContent;
+ return;
+ }
+
+ pendingContentRef.current = null;
+ loadContent(api, newContent);
},
async getData() {
const api = apiRef.current;
@@ -188,11 +275,32 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
});
return {
+ initialData,
+ excalidrawAPI: (api) => {
+ const pendingContent = pendingContentRef.current;
+ apiRef.current = api;
+
+ // Flush content that arrived while the API was unavailable (#10279).
+ if (pendingContent !== null) {
+ pendingContentRef.current = null;
+ loadContentRef.current(api, pendingContent);
+ }
+ },
onChange: () => {
if (!apiRef.current || isReadOnly) return;
const oldSceneVersion = currentSceneVersion.current;
const newSceneVersion = getSceneVersion(apiRef.current.getSceneElements());
+ // Excalidraw's mount initialization has not applied `initialData` yet: the scene
+ // is still empty, and saving it would wipe the note. A non-zero version is the
+ // signal that the initial content has landed.
+ if (!initialSceneAppliedRef.current) {
+ if (newSceneVersion === 0) {
+ return;
+ }
+ initialSceneAppliedRef.current = true;
+ }
+
let hasChanges = (newSceneVersion !== oldSceneVersion);
// There are cases where the scene version does not change, but appState did.
@@ -233,6 +341,22 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
};
}
+function parseContent(newContent: string, note: FNote): CanvasContent {
+ let content: CanvasContent = {
+ elements: [],
+ files: [],
+ appState: {}
+ };
+ if (newContent) {
+ try {
+ content = JSON.parse(newContent) as CanvasContent;
+ } catch (err) {
+ console.error("Error parsing content. Probably note.type changed. Starting with empty canvas", note, err);
+ }
+ }
+ return content;
+}
+
async function getData(api: ExcalidrawImperativeAPI, appStateToCompare: RefObject<Partial<ImportantAppState>>) {
const elements = api.getSceneElements();
const appState = api.getAppState();