Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/canvas: improve performance
Adorian Doran989199a36a74
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 3bbcec68c4..2cf558ddd0 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -134,6 +134,8 @@ export interface RenderOptions {/** Saves the changes that rendered content makes to attachments of the note that shows it. */export interface AttachmentEditor {+ /** The ID of the component that sends the saves, which their entity changes include. */+ readonly componentId?: string;/** Whether the rendered content can change `attachment`. */canEdit(attachment: FAttachment): boolean;/** The content of the attachment that is not saved yet, or `undefined`. */@@ -563,6 +565,8 @@ function getCodeMime(entity: FNote | FAttachment) {/** Saves the changes that rendered content makes to one note or attachment. */export interface ContentEditor {+ /** The ID of the component that sends the saves, which their entity changes include. */+ componentId?: string;/** Whether the rendered content can change the note or attachment. */canEdit(): boolean;getUnsavedContent(): string | undefined;@@ -585,6 +589,7 @@ export function bindAttachmentEditor(attachment: FAttachment): ContentEditor {return {+ componentId: editor.componentId,canEdit: () => editor.canEdit(attachment),getUnsavedContent: () => editor.getUnsavedContent(attachment.attachmentId),scheduleSave: (getContent, onSaved) => editor.scheduleSave(attachment, getContent, onSaved),diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsxindex 5b34f1b568..42c595277f 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx@@ -25,7 +25,9 @@ import LoadResults from "../../../services/load_results";import server from "../../../services/server";import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";+import type { SavedData } from "../../react/hooks";import type { EmbedHostHistory } from "../text/embed_history";+import { CANVAS_EXPORT_TITLE } from "./image_attachments";import useCanvasPersistence, {saveDrawingPicture, useCanvasDrawingPersistence} from "./persistence";@@ -75,11 +77,12 @@ type PersistenceProps = ReturnType<typeof useCanvasPersistence>;let props: PersistenceProps | undefined;-function Probe({ note, apiRef }: {+function Probe({ note, apiRef, isReadOnly = false }: {note: FNote;apiRef: RefObject<ExcalidrawImperativeAPI | null>;+ isReadOnly?: boolean;}) {- props = useCanvasPersistence(note, null, apiRef, "light", false);+ props = useCanvasPersistence(note, null, apiRef, "light", isReadOnly);return null;}@@ -268,6 +271,127 @@ describe("useCanvasPersistence content loading (#10279)", () => {});});+describe("useCanvasPersistence saves", () => {+ const PICTURE_TIME = "2026-10-27 10:00:00.000Z";+ let container: HTMLElement;+ let puts: { url: string; data: SavedData }[];+ let post: ReturnType<typeof vi.spyOn>;+ let sceneElements: FakeElement[];++ beforeEach(() => {+ vi.useFakeTimers();+ props = undefined;+ puts = [];+ sceneElements = [];+ server.put = vi.fn(async (url: string, data: SavedData) => {+ puts.push({ url, data });+ return {};+ }) as typeof server.put;+ post = vi.spyOn(server, "post").mockResolvedValue(undefined);+ vi.mocked(exportToSvg).mockClear();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ act(() => render(null, container));+ container.remove();+ post.mockRestore();+ vi.useRealTimers();+ });++ /** A canvas note modified at `modified`, whose picture was saved at `pictureTime`, if any. */+ function buildNoteWithPicture(modified: string, pictureTime?: string) {+ const { note, elements } = buildCanvasNote([ "a1" ]);+ note.getMetadata = (async () => ({ utcDateModified: modified })) as never;+ note.getAttachmentsByRole = (async (role: string) => role === "image" && pictureTime+ ? [ { title: CANVAS_EXPORT_TITLE, utcDateModified: pictureTime } ]+ : []) as never;+ return { note, elements };+ }++ async function mount(note: FNote, isReadOnly = false) {+ const { api } = buildApi(() => sceneElements);+ const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI | null>;+ await act(async () => {+ render(<Probe note={note} apiRef={apiRef} isReadOnly={isReadOnly} />, container);+ });+ await act(async () => {});+ await resolvedInitialData();+ }++ async function waitFor(ms: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+ }++ function change(appState: object = {}) {+ props?.onChange?.([], appState as never, {} as never);+ }++ it("saves the scene alone, and its picture once the saves pause", async () => {+ const { note, elements } = buildNoteWithPicture(PICTURE_TIME, PICTURE_TIME);+ await mount(note);+ sceneElements = elements;+ change();++ sceneElements = [ { ...elements[0], version: 99 } ];+ change();+ await waitFor(1500);+ expect(puts).toHaveLength(1);+ expect(puts[0].data.attachments).toEqual([]);+ expect(exportToSvg).not.toHaveBeenCalled();++ await waitFor(5000);+ expect(vi.mocked(exportToSvg).mock.calls.map(([ { elements } ]) => elements))+ .toEqual([ sceneElements ]);+ expect(post).toHaveBeenCalledExactlyOnceWith(+ `notes/${note.noteId}/attachments?matchBy=title`,+ { role: "image", mime: "image/svg+xml", title: CANVAS_EXPORT_TITLE, content: "<svg/>" }+ );+ });++ it("holds the save while the pointer is down", async () => {+ const { note, elements } = buildNoteWithPicture(PICTURE_TIME, PICTURE_TIME);+ await mount(note);+ sceneElements = elements;+ change();++ sceneElements = [ { ...elements[0], version: 99 } ];+ change({ cursorButton: "down" });+ sceneElements = [ { ...elements[0], version: 100 } ];+ change({ cursorButton: "down" });+ await waitFor(1500);+ expect(puts).toEqual([]);++ change({ cursorButton: "up" });+ await waitFor(1500);+ expect(puts).toHaveLength(1);+ });++ it("draws a missing or older picture once the note loads, unless read-only", async () => {+ const postedNoteIds = () => post.mock.calls.map(([ url ]) => String(url).split("/")[1]);+ const stale = buildNoteWithPicture("2026-10-27 11:00:00.000Z", PICTURE_TIME).note;+ await mount(stale);+ await waitFor(5000);+ expect(postedNoteIds()).toEqual([ stale.noteId ]);+ expect(vi.mocked(exportToSvg).mock.calls[0]?.[0].elements)+ .toMatchObject([ { id: "a1" } ]);++ // The notes that the canvas loads next.+ await mount(buildNoteWithPicture(PICTURE_TIME, PICTURE_TIME).note);+ await mount(buildNoteWithPicture("2026-10-27 11:00:00.000Z", PICTURE_TIME).note, true);+ await waitFor(5000);+ expect(postedNoteIds()).toEqual([ stale.noteId ]);++ const unpictured = buildNoteWithPicture(PICTURE_TIME).note;+ await mount(unpictured);+ await waitFor(5000);+ expect(postedNoteIds()).toEqual([ stale.noteId, unpictured.noteId ]);+ });+});+describe("useCanvasDrawingPersistence", () => {const IMAGE = { id: "f1", dataURL: "data:image/png;base64,AA==", mimeType: "image/png" };const UNUSED_IMAGE = { ...IMAGE, id: "f2" };@@ -278,6 +402,8 @@ describe("useCanvasDrawingPersistence", () => {let appState: Record<string, unknown>;let updateScene: ReturnType<typeof vi.fn>;let parent: Component;+ /** The note that owns the drawings, with a picture saved after them. */+ let owner: FNote;function DrawingProbe({ attachment, editor, apiRef, options }: {attachment: FAttachment;@@ -295,6 +421,10 @@ describe("useCanvasDrawingPersistence", () => {sceneFiles = { f1: IMAGE, f2: UNUSED_IMAGE };updateScene = vi.fn();parent = new Component();+ owner = buildNote({ title: "Owner" });+ owner.getAttachmentsByRole = (async () => [+ { title: "a1.svg", utcDateModified: "2026-01-02 00:00:00.000Z" }+ ]) as never;appState = {scrollX: 1, scrollY: 2, zoom: { value: 1 }, gridModeEnabled: false,viewBackgroundColor: "transparent", theme: "light"@@ -307,11 +437,16 @@ describe("useCanvasDrawingPersistence", () => {act(() => render(null, container));container.remove();vi.unstubAllGlobals();+ vi.useRealTimers();});function buildAttachment(content: object) {const getBlob = vi.fn(async () => ({ content: JSON.stringify(content) }));- return { attachment: { attachmentId: "a1", getBlob } as unknown as FAttachment, getBlob };+ const attachment = {+ attachmentId: "a1", ownerId: owner.noteId, utcDateModified: "2026-01-01 00:00:00.000Z",+ getBlob+ } as unknown as FAttachment;+ return { attachment, getBlob };}function buildEditor(unsavedContent?: string) {@@ -359,10 +494,10 @@ describe("useCanvasDrawingPersistence", () => {drawingProps?.onChange?.([], appState as never, {});}- /** Reports a save of the attachment `a1` made elsewhere, and waits until it shows. */- async function reportSave(row: object = { attachmentId: "a1" }) {+ /** Reports a save of the attachment `a1` made by `componentId`, and waits until it shows. */+ async function reportSave(row: object = { attachmentId: "a1" }, componentId = "other") {const loadResults = new LoadResults([]);- loadResults.addAttachmentRow(row as never, "otherComponent");+ loadResults.addAttachmentRow(row as never, componentId);await act(async () => {await parent.handleEvent("entitiesReloaded", { loadResults });await new Promise((resolve) => setTimeout(resolve));@@ -430,15 +565,25 @@ describe("useCanvasDrawingPersistence", () => {}});- // Once saved, the drawing saves its picture, drawn with the images Excalidraw holds.+ // Once the saves pause, the drawing saves its picture, drawn with the images loaded in+ // Excalidraw.const post = vi.spyOn(server, "post").mockResolvedValue(undefined);vi.mocked(exportToSvg).mockClear().mockResolvedValueOnce(svgOf("picture"));+ vi.useFakeTimers();await act(async () => onSaved(getContent()));- expect(vi.mocked(exportToSvg).mock.calls[0]?.[0].files).toBe(sceneFiles);- expect(post).toHaveBeenCalledExactlyOnceWith(- "notes/undefined/attachments?matchBy=title",+ await act(async () => {+ await vi.advanceTimersByTimeAsync(29000);+ });+ expect(exportToSvg).not.toHaveBeenCalled();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ vi.useRealTimers();+ await vi.waitFor(() => expect(post).toHaveBeenCalledExactlyOnceWith(+ `notes/${owner.noteId}/attachments?matchBy=title`,expect.objectContaining({ title: "a1.svg" })- );+ ));+ expect(vi.mocked(exportToSvg).mock.calls[0]?.[0].files).toBe(sceneFiles);post.mockRestore();appState = { ...appState, viewBackgroundColor: "#ffc9c9" };@@ -450,6 +595,74 @@ describe("useCanvasDrawingPersistence", () => {expect(editor.release).toHaveBeenCalledOnce();});+ it("holds the save while the pointer is down", async () => {+ const loaded = [ { id: "r1", type: "rectangle", version: 3 } ];+ const { attachment } = buildAttachment({ elements: loaded });+ const editor = buildEditor();+ await mount(attachment, editor);+ change();+ sceneElements = loaded;+ change();++ appState = { ...appState, cursorButton: "down" };+ sceneElements = [ { ...loaded[0], version: 4 } ];+ change();+ sceneElements = [ { ...loaded[0], version: 5 } ];+ change();+ expect(editor.scheduleSave).not.toHaveBeenCalled();++ appState = { ...appState, cursorButton: "up" };+ change();+ expect(editor.scheduleSave).toHaveBeenCalledOnce();+ });++ it("loads the saves of other components only, not those of its own editor", async () => {+ const loaded = [ { id: "r1", type: "rectangle", version: 3 } ];+ const { attachment, getBlob } = buildAttachment({ elements: loaded });+ await mount(attachment, { ...buildEditor(), componentId: "textNote" });+ change();+ sceneElements = loaded;+ change();+ getBlob.mockClear();++ await reportSave({ attachmentId: "a1" }, "textNote");+ expect(getBlob).not.toHaveBeenCalled();+ await reportSave();+ expect(getBlob).toHaveBeenCalledOnce();+ });++ it("draws a picture older than the drawing once it loads, if it can save one", async () => {+ vi.useFakeTimers();+ const post = vi.spyOn(server, "post").mockResolvedValue(undefined);+ const loaded = { elements: [ { id: "r1", type: "rectangle", version: 3 } ] };+ async function load(content: object, editor: ContentEditor | undefined) {+ act(() => render(null, container));+ await mount(buildAttachment(content).attachment, editor);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30000);+ });+ }++ // None for a current picture. For an older one, none without an editor, for an empty+ // drawing, or while the editor has changes to save.+ await load(loaded, buildEditor());+ owner.getAttachmentsByRole = (async () => [+ { title: "a1.svg", utcDateModified: "2025-12-31 00:00:00.000Z" }+ ]) as never;+ await load(loaded, undefined);+ await load({ elements: [] }, buildEditor());+ await load(loaded, buildEditor(JSON.stringify(loaded)));+ expect(post).not.toHaveBeenCalled();++ vi.mocked(exportToSvg).mockResolvedValueOnce(svgOf("picture"));+ await load(loaded, buildEditor());+ expect(post).toHaveBeenCalledExactlyOnceWith(+ `notes/${owner.noteId}/attachments?matchBy=title`,+ expect.objectContaining({ title: "a1.svg" })+ );+ post.mockRestore();+ });+it("saves nothing for the content as Excalidraw restores it, only the edits", async () => {// A text element placed with nothing typed into it yet, as another view saved it.const saved = [@@ -704,7 +917,8 @@ describe("useCanvasDrawingPersistence", () => {const owner = buildNote({ title: "Owner" });const getAttachmentsByRole = vi.fn(async () => [{ attachmentId: "img1", title: "f9.png" },- { attachmentId: "img2", title: "other.png" }+ { attachmentId: "img2", title: "other.png" },+ { attachmentId: "pic1", title: "a1.svg", utcDateModified: "2026-01-02 00:00:00.000Z" }]);owner.getAttachmentsByRole = getAttachmentsByRole as never;const fetchImage = vi.fn(async () => ({diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex bed6aa4acd..6ebcea228c 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -15,6 +15,7 @@ import type FAttachment from "../../../entities/fattachment";import FNote from "../../../entities/fnote";import type { ContentEditor } from "../../../services/content_renderer";import froca from "../../../services/froca";+import options from "../../../services/options";import server from "../../../services/server";import {SavedData, useEditorSpacedUpdate, useTriliumEvent, useWhenShown@@ -26,6 +27,7 @@ import { type DrawingView, getBoundedView, getFittedView } from "./drawing_view"import {buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments, loadImageFiles} from "./image_attachments";+import { schedulePicture } from "./picture_schedule";interface AttachmentMetadata {title: string;@@ -41,6 +43,20 @@ export interface CanvasContent {/** Subset of the app state that should be persisted whenever they change. This explicitly excludes transient state like the current selection or zoom level. */type ImportantAppState = Pick<AppState, "gridModeEnabled" | "viewBackgroundColor">;+/** The part of a scene that its picture shows. */+type PictureScene = Pick<DrawingScene, "elements" | "appState">;++/**+ * How long the saves of a canvas note pause before its picture is drawn, in ms. Previews in the app+ * show the picture.+ */+const NOTE_PICTURE_DELAY = 5000;+/**+ * How long the saves of a canvas drawing pause before its picture is drawn, in ms. Only shared+ * pages show the picture.+ */+const DRAWING_PICTURE_DELAY = 30000;+export default function useCanvasPersistence(note: FNote, noteContext: NoteContext | null | undefined, apiRef: RefObject<ExcalidrawImperativeAPI | null>, theme: AppState["theme"], isReadOnly: boolean): Partial<ExcalidrawProps> {const libraryChanged = useRef(false);@@ -92,6 +108,7 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte// 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);+ const canSavePicture = !isReadOnly && !options.is("databaseReadonly");async function loadInitialContent(newContent: string) {const runId = ++initialLoadRunRef.current;@@ -131,6 +148,9 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteContefiles,libraryItems: libraryResult.libraryItems});+ if (canSavePicture) {+ void refreshNotePicture(note, { elements, appState: content.appState }, files);+ }} catch (err) {console.error("Failed to prepare initial canvas data", err);if (initialLoadRunRef.current !== runId) return;@@ -171,6 +191,14 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteapi.addFiles(files);}persistedImageFileIds.current = new Set(metadata.map((m) => m.fileId));++ if (canSavePicture) {+ const allFiles: BinaryFiles = {};+ for (const file of [ ...Object.values(content.files ?? {}), ...files ]) {+ allFiles[file.id] = file;+ }+ void refreshNotePicture(note, content, allFiles);+ }});// Initialize tracking state after loading to prevent redundant updates from initial onChange events@@ -218,13 +246,22 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteasync getData() {const api = apiRef.current;if (!api) return;- const { content, svg, activeFiles } = await getData(api, appStateToCompare);- const attachments: SavedData["attachments"] = [{ role: IMAGE_ROLE, title: CANVAS_EXPORT_TITLE, mime: "image/svg+xml", content: svg, position: 0 }];+ const elements = api.getSceneElements();+ const appState = api.getAppState();+ const files = api.getFiles();+ appStateToCompare.current = getImportantAppState(appState);++ // Images are persisted as attachments (keyed by fileId), not inline, so the content+ // stays small. Elements keep their `fileId`; the bytes are reattached on load. Kept as+ // an empty object for shape compatibility with loadData() and legacy content.+ const content = buildSceneContent(elements, appState, {});+ const attachments: SavedData["attachments"] = [];// Persist newly inserted images as attachments. `content` carries only the fileId- // references (see getData), so the bytes live here. Removed images are not deleted from+ // references, so the bytes live here. Removed images are not deleted from// the client: the server's saveLinks/checkImageAttachments scans the saved scene JSON and// schedules now-unreferenced image attachments for erasure (same as the spreadsheet).+ const activeFiles = getActiveFiles(elements, files);for (const attachment of buildNewImageAttachments(activeFiles, persistedImageFileIds.current)) {attachments.push(attachment);persistedImageFileIds.current.add(attachment.title);@@ -282,13 +319,16 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte}}- return {- content: JSON.stringify(content),- attachments- };+ const data = { content: JSON.stringify(content), attachments };+ savedScenes.set(data, { noteId: note.noteId, scene: content, files });+ return data;},- dataSaved() {+ dataSaved(data) {libraryChanged.current = false;+ const saved = savedScenes.get(data);+ if (saved) {+ scheduleNotePicture(saved.noteId, saved.scene, saved.files);+ }}});@@ -304,7 +344,7 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteloadContentRef.current(api, pendingContent);}},- onChange: () => {+ onChange: (_elements, appState) => {if (!apiRef.current || isReadOnly) return;const oldSceneVersion = currentSceneVersion.current;const newSceneVersion = getSceneVersion(apiRef.current.getSceneElements());@@ -333,7 +373,8 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte}}- if (hasChanges) {+ // Excalidraw reports each move of a drag: the save waits until the pointer is up.+ if (hasChanges && appState.cursorButton !== "down") {spacedUpdate.resetUpdateTimer();spacedUpdate.scheduleUpdate();currentSceneVersion.current = newSceneVersion;@@ -408,6 +449,10 @@ export function useCanvasDrawingPersistence(isLoadedSceneEmptyRef.current = !elements.some((element) => !element.isDeleted);isFitPendingRef.current = !initialView && !content.appState?.zoom&& !isLoadedSceneEmptyRef.current;+ // With unsaved changes, their save schedules the picture.+ if (editor?.canEdit() && unsavedContent === undefined && !isLoadedSceneEmptyRef.current) {+ void refreshDrawingPicture(attachment, blobContent, loaded.files);+ }return {elements,@@ -500,8 +545,9 @@ export function useCanvasDrawingPersistence(appStateToCompare.current = appState;}+ // This drawing already shows the saves that `editor` makes.useTriliumEvent("entitiesReloaded", ({ loadResults }) => {- const isSaved = loadResults.getAttachmentRows().some((row) =>+ const isSaved = loadResults.getAttachmentRows(editor?.componentId).some((row) =>row.attachmentId === attachment.attachmentId && !row.isDeleted);if (isSaved) {void loadSavedDrawing();@@ -530,7 +576,7 @@ export function useCanvasDrawingPersistence(read: () => readDrawing(attachment, editor),write: (scene) => editor?.scheduleSave(() => serializeDrawing(scene, referencedFileIds.current),- (content) => saveDrawingPicture(attachment, content, scene.files)+ (content) => scheduleDrawingPicture(attachment, content, scene.files))});onSceneShown?.();@@ -547,6 +593,9 @@ export function useCanvasDrawingPersistence(}drawingMount?.record();+ // Excalidraw reports each move of a drag: the save waits until the pointer is up.+ if (state.cursorButton === "down") return;+const appState = getImportantAppState(api.getAppState());const previousAppState = appStateToCompare.current;appStateToCompare.current = appState;@@ -562,7 +611,7 @@ export function useCanvasDrawingPersistence(appState: api.getAppState(),files: api.getFiles()}, referencedFileIds.current),- (content) => saveDrawingPicture(attachment, content, api.getFiles())+ (content) => scheduleDrawingPicture(attachment, content, api.getFiles()));}};@@ -606,7 +655,7 @@ export async function loadDrawingFiles(* shared pages show it, or `null` for an empty drawing.*/export async function exportDrawingPicture(- scene: CanvasContent,+ scene: PictureScene,files: BinaryFiles,isDark: boolean) {@@ -804,36 +853,72 @@ export function parseContent(newContent: string, entity: FNote | FAttachment): Creturn content;}-async function getData(api: ExcalidrawImperativeAPI, appStateToCompare: RefObject<Partial<ImportantAppState> | null>) {- const elements = api.getSceneElements();- const appState = api.getAppState();+/** The scene that each save of a canvas note sends, which its picture is drawn from. */+const savedScenes = new WeakMap<+ SavedData, { noteId: string; scene: PictureScene; files: BinaryFiles }+>();- /**- * A file is not deleted, even though removed from canvas. Therefore, we only keep- * files that are referenced by an element. Maybe this will change with a new excalidraw version?- */- const files = api.getFiles();- // parallel svg export to combat bitrot and enable rendering image for note inclusion, preview, and share- const svg = await exportToSvg({- elements,- appState,- exportPadding: 5, // 5 px padding- files- });- const svgString = svg.outerHTML;+/** Schedules the picture of the canvas note `noteId`, drawn from `scene`, for a pause in saves. */+function scheduleNotePicture(noteId: string, scene: PictureScene, files: BinaryFiles) {+ schedulePicture(noteId, () => saveNotePicture(noteId, scene, files), NOTE_PICTURE_DELAY);+}- appStateToCompare.current = getImportantAppState(appState);+/** Saves the picture of the canvas note `noteId`, which previews and shared pages show. */+async function saveNotePicture(noteId: string, scene: PictureScene, files: BinaryFiles) {+ try {+ const picture = await exportDrawingPicture(scene, files, false);+ await server.post(`notes/${noteId}/attachments?matchBy=title`, {+ role: IMAGE_ROLE,+ mime: "image/svg+xml",+ title: CANVAS_EXPORT_TITLE,+ content: picture?.outerHTML ?? EMPTY_PICTURE+ });+ } catch (e) {+ console.error(`Could not save the picture of the canvas note '${noteId}'`, e);+ }+}- // Images are persisted as attachments (keyed by fileId), not inline, so the content stays- // small. Elements keep their `fileId`; the bytes are reattached on load. Kept as an empty- // object for shape compatibility with loadData() and legacy content.- const content = buildSceneContent(elements, appState, {});+/** Schedules a picture of `scene`, loaded from `note`, when the saved one is missing or older. */+async function refreshNotePicture(note: FNote, scene: PictureScene, files: BinaryFiles) {+ if (!(scene.elements ?? []).some((element) => !element.isDeleted)) return;+ try {+ const picture = await getPicture(note, CANVAS_EXPORT_TITLE);+ if (!picture || picture.utcDateModified < (await note.getMetadata()).utcDateModified) {+ scheduleNotePicture(note.noteId, scene, files);+ }+ } catch (e) {+ console.error(`Could not check the picture of the canvas note '${note.noteId}'`, e);+ }+}- return {- content,- svg: svgString,- activeFiles: getActiveFiles(elements, files)- };+/** Schedules the picture of `drawing`, drawn from its saved `content`, for when its saves pause. */+function scheduleDrawingPicture(drawing: FAttachment, content: string, files: BinaryFiles) {+ schedulePicture(+ drawing.attachmentId,+ () => saveDrawingPicture(drawing, content, files),+ DRAWING_PICTURE_DELAY+ );+}++/** Schedules a picture of `drawing`, saved as `content`, when the saved one is missing or older. */+async function refreshDrawingPicture(drawing: FAttachment, content: string, files: BinaryFiles) {+ try {+ const owner = await froca.getNote(drawing.ownerId);+ if (!owner) return;+ const picture = await getPicture(owner, getDrawingPictureTitle(drawing.attachmentId));+ if (!picture || picture.utcDateModified < drawing.utcDateModified) {+ scheduleDrawingPicture(drawing, content, files);+ }+ } catch (e) {+ const { attachmentId } = drawing;+ console.error(`Could not check the picture of the canvas drawing '${attachmentId}'`, e);+ }+}++/** The image attachment `title` of `owner`, the picture of a drawing, or `undefined`. */+async function getPicture(owner: FNote, title: string) {+ return (await owner.getAttachmentsByRole(IMAGE_ROLE))+ .find((attachment) => attachment.title === title);}/** The scene as the content of a canvas note or of a canvas drawing stores it. */diff --git a/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.ts b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.tsnew file mode 100644index 0000000000..a9a365b7c2--- /dev/null+++ b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.ts@@ -0,0 +1,84 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++describe("schedulePicture", () => {+ let schedulePicture: typeof import("./picture_schedule").schedulePicture;++ beforeEach(async () => {+ vi.useFakeTimers();+ // A new module, without the input and the pictures of the other tests.+ vi.resetModules();+ ({ schedulePicture } = await import("./picture_schedule"));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("draws once the delay passes without another picture of the same drawing", async () => {+ const first = vi.fn(async () => {});+ const second = vi.fn(async () => {});+ const other = vi.fn(async () => {});++ schedulePicture("d1", first, 1000);+ schedulePicture("d2", other, 1000);+ await vi.advanceTimersByTimeAsync(600);+ schedulePicture("d1", second, 1000);+ await vi.advanceTimersByTimeAsync(600);+ expect(other).toHaveBeenCalledOnce();+ expect(second).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(400);+ expect(second).toHaveBeenCalledOnce();+ expect(first).not.toHaveBeenCalled();+ });++ it("waits until the user gives no input for a while, as during panning", async () => {+ const draw = vi.fn(async () => {});+ schedulePicture("d1", draw, 1000);++ await vi.advanceTimersByTimeAsync(900);+ document.dispatchEvent(new Event("wheel"));+ await vi.advanceTimersByTimeAsync(1950);+ expect(draw).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(50);+ expect(draw).toHaveBeenCalledOnce();+ });++ it("draws the waiting pictures once the page is hidden", async () => {+ const draw = vi.fn(async () => {});+ schedulePicture("d1", draw, 30000);++ const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");+ document.dispatchEvent(new Event("visibilitychange"));+ visibility.mockRestore();+ await vi.advanceTimersByTimeAsync(0);+ expect(draw).toHaveBeenCalledOnce();++ await vi.advanceTimersByTimeAsync(30000);+ expect(draw).toHaveBeenCalledOnce();+ });++ it("draws the pictures of a drawing one after the other, also after a failed one", async () => {+ const order: string[] = [];+ let finishFirst = () => {};+ schedulePicture("d1", () => new Promise<void>((resolve, reject) => {+ order.push("first started");+ finishFirst = () => {+ order.push("first failed");+ reject(new Error("offline"));+ };+ }), 100);+ await vi.advanceTimersByTimeAsync(100);++ schedulePicture("d1", async () => {+ order.push("second started");+ }, 100);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual([ "first started" ]);++ finishFirst();+ await vi.advanceTimersByTimeAsync(0);+ expect(order).toEqual([ "first started", "first failed", "second started" ]);+ });+});diff --git a/apps/client/src/widgets/type_widgets/canvas/picture_schedule.ts b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.tsnew file mode 100644index 0000000000..ff0b8cfcd4--- /dev/null+++ b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.ts@@ -0,0 +1,82 @@+/** A picture of a drawing that waits to be drawn. */+interface PendingPicture {+ draw: () => Promise<void>;+ timer: ReturnType<typeof setTimeout>;+}++/** How long the user gives no input before a picture is drawn, in ms. */+const INPUT_PAUSE = 2000;+const INPUT_EVENTS = [ "pointerdown", "pointermove", "wheel", "keydown" ];++const pendingPictures = new Map<string, PendingPicture>();+/** The latest draw of each drawing, which the next draw of the drawing waits for. */+const runningDraws = new Map<string, Promise<void>>();+let lastInputTime = 0;+let isWatchingPage = false;++/**+ * Draws the picture of the drawing `key` with `draw` once `delay` ms pass without another call for+ * `key` and the user pauses their input, or once the page is hidden. A later call replaces the+ * `draw` that waits. Drawing blocks the main thread for the whole scene, so it waits until the+ * user is idle.+ */+export function schedulePicture(key: string, draw: () => Promise<void>, delay: number) {+ const pending = pendingPictures.get(key);+ if (pending) {+ clearTimeout(pending.timer);+ }+ pendingPictures.set(key, { draw, timer: setTimeout(() => drawWhenIdle(key), delay) });+ watchPage();+}++/** Draws the picture of `key` that waits, or waits until the user's input pauses. */+function drawWhenIdle(key: string) {+ const pending = pendingPictures.get(key);+ if (!pending) return;++ const wait = lastInputTime + INPUT_PAUSE - Date.now();+ if (wait > 0) {+ pending.timer = setTimeout(() => drawWhenIdle(key), wait);+ } else {+ drawPicture(key);+ }+}++/** Starts the draw of `key` that waits, once the running draw of `key` ends. */+function drawPicture(key: string) {+ const pending = pendingPictures.get(key);+ if (!pending) return;+ pendingPictures.delete(key);+ clearTimeout(pending.timer);++ // `draw` reports its own failures.+ const draw = (runningDraws.get(key) ?? Promise.resolve()).then(pending.draw).catch(() => {});+ runningDraws.set(key, draw);+ void draw.then(() => {+ if (runningDraws.get(key) === draw) {+ runningDraws.delete(key);+ }+ });+}++/**+ * Records the time of the user's input, and draws the pictures that wait once the page is hidden,+ * since a hidden page can close.+ */+function watchPage() {+ if (isWatchingPage) return;+ isWatchingPage = true;++ const noteInput = () => {+ lastInputTime = Date.now();+ };+ for (const type of INPUT_EVENTS) {+ document.addEventListener(type, noteInput, { capture: true, passive: true });+ }+ document.addEventListener("visibilitychange", () => {+ if (document.visibilityState !== "hidden") return;+ for (const key of [ ...pendingPictures.keys() ]) {+ drawPicture(key);+ }+ });+}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 94b8906436..a5d21b87b4 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -93,7 +93,7 @@ export default function EditableText({? watchEditorBlocks(block, onBlockChange): undefined));const [ attachmentSaves ] = useState(() =>- new AttachmentSaves(() => spacedUpdate.scheduleUpdate()));+ new AttachmentSaves(() => spacedUpdate.scheduleUpdate(), parentComponent?.componentId));const [ inlineSourceSaves ] = useState(() =>new InlineSourceSaves(() => spacedUpdate.scheduleUpdate()));const [ embedHistories ] = useState(() => new EmbedHistories(() => editorRef.current));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.tsindex b8c77516da..9ad92c0319 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@@ -6,7 +6,9 @@ import Component from "../../../components/component";import type NoteContext from "../../../components/note_context";import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";-import type { AttachmentEditor, NoteEditor } from "../../../services/content_renderer";+import {+ type AttachmentEditor, bindAttachmentEditor, type NoteEditor+} from "../../../services/content_renderer";import { ParentComponent } from "../../react/react_utils";import AttachmentSaves, {InlineSourceSaves, NoteSaves, useAttachmentEditor, useNoteEditor@@ -153,6 +155,10 @@ describe("useAttachmentEditor", () => {render(h(ParentComponent.Provider, { value: component }, h(Probe, {})), container);});expect(editor?.canEdit(drawing)).toBe(true);+ // Its saves send this component ID, so a drawing can skip the changes they report.+ expect(editor?.componentId).toBe(component.componentId);+ expect(editor && bindAttachmentEditor(editor, drawing).componentId)+ .toBe(component.componentId);editor?.scheduleSave(drawing, () => "first");await act(async () => {diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.tsindex 00b5c70722..ec794a4f0d 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts@@ -115,8 +115,11 @@ export default class AttachmentSavesimplements AttachmentEditor {private noteId: string | undefined;- /** @param scheduleUpdate schedules a save of the text note. */- constructor(private scheduleUpdate: () => void) {+ /**+ * @param scheduleUpdate schedules a save of the text note.+ * @param componentId the component that sends the saves.+ */+ constructor(private scheduleUpdate: () => void, readonly componentId?: string) {super();}@@ -262,7 +265,8 @@ export function useAttachmentEditor(): AttachmentEditor {const parentComponent = useContext(ParentComponent);const [ saves ] = useState(() => {- const saves = new AttachmentSaves(() => spacedUpdate.scheduleUpdate());+ const saves = new AttachmentSaves(+ () => spacedUpdate.scheduleUpdate(), parentComponent?.componentId);saves.setNoteId(note.noteId);return saves;});