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: reduce JSON size by rounding coordinates to three decimals
Adorian Doran0a5775856c54
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsxindex 1c5d35112b..f4652478de 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx@@ -11,6 +11,7 @@* switches on an already-initialized instance) may use `updateScene`.*/import { exportToSvg, restoreElements } from "@excalidraw/excalidraw";+import type { ExcalidrawElement } from "@excalidraw/excalidraw/element/types";import { ExcalidrawImperativeAPI, ExcalidrawInitialDataState } from "@excalidraw/excalidraw/types";import type { HostHistoryStep } from "@triliumnext/codemirror";import { type RefObject, render } from "preact";@@ -29,7 +30,7 @@ import type { SavedData } from "../../react/hooks";import type { EmbedHostHistory } from "../text/embed_history";import { CANVAS_EXPORT_TITLE } from "./image_attachments";import useCanvasPersistence, {- saveDrawingPicture, useCanvasDrawingPersistence+ roundStroke, saveDrawingPicture, useCanvasDrawingPersistence} from "./persistence";interface FakeElement {@@ -73,6 +74,26 @@ vi.mock("@excalidraw/excalidraw", () => ({vi.stubGlobal("logError", vi.fn());vi.stubGlobal("logInfo", vi.fn());+/** A pen stroke as Excalidraw keeps it, at the precision of the pointer events of the pen. */+const PEN_STROKE = {+ id: "s1", type: "freedraw", version: 7, versionNonce: 11,+ x: 197.3699951171875, y: 33.61000061035156,+ width: 1.3700103759765625, height: 41.64099884033203,+ points: [+ [ 0, 0 ], [ 0.031005859375, 2.4990005493164062 ], [ 1.3700103759765625, 41.64099884033203 ]+ ],+ pressures: [ 0.4892578125, 0.51171875, 0.3017578125 ],+ lastCommittedPoint: [ 1.3700103759765625, 41.64099884033203 ]+};+/** `PEN_STROKE` as a save keeps it. */+const SAVED_PEN_STROKE = {+ ...PEN_STROKE,+ x: 197.37, y: 33.61, width: 1.37, height: 41.641,+ points: [ [ 0, 0 ], [ 0.031, 2.499 ], [ 1.37, 41.641 ] ],+ pressures: [ 0.489, 0.512, 0.302 ],+ lastCommittedPoint: null+};+type PersistenceProps = ReturnType<typeof useCanvasPersistence>;let props: PersistenceProps | undefined;@@ -352,6 +373,19 @@ describe("useCanvasPersistence saves", () => {);});+ it("saves a pen stroke to 3 decimals", async () => {+ const { note, elements } = buildNoteWithPicture(PICTURE_TIME, PICTURE_TIME);+ await mount(note);+ sceneElements = elements;+ change();++ sceneElements = [ ...elements, PEN_STROKE ];+ change();+ await waitFor(1500);+ expect(JSON.parse(puts[0]?.data.content ?? "null")?.elements)+ .toEqual([ ...elements, SAVED_PEN_STROKE ]);+ });+it("holds the save while the pointer is down, also a save that waits", async () => {const { note, elements } = buildNoteWithPicture(PICTURE_TIME, PICTURE_TIME);await mount(note);@@ -622,6 +656,18 @@ describe("useCanvasDrawingPersistence", () => {expect(editor.release).toHaveBeenCalledOnce();});+ it("saves a pen stroke to 3 decimals", async () => {+ const { attachment } = buildAttachment({ elements: [] });+ const editor = buildEditor();+ await mount(attachment, editor);+ change();++ sceneElements = [ PEN_STROKE ];+ change();+ const [ getContent ] = editor.scheduleSave.mock.calls[0] ?? [];+ expect(JSON.parse(getContent?.() ?? "null")?.elements).toEqual([ SAVED_PEN_STROKE ]);+ });+it("postpones the save at each change and holds it while the pointer is down", async () => {const loaded = [ { id: "r1", type: "rectangle", version: 3 } ];const { attachment } = buildAttachment({ elements: loaded });@@ -1274,6 +1320,24 @@ describe("saveDrawingPicture", () => {});});+describe("roundStroke", () => {+ it("rounds a pen stroke to 3 decimals once for each version, and keeps other elements", () => {+ const stroke = { ...PEN_STROKE } as unknown as ExcalidrawElement;+ const saved = roundStroke(stroke);+ expect(saved).toEqual(SAVED_PEN_STROKE);+ expect(roundStroke(stroke)).toBe(saved);++ // Excalidraw changes an element in place, with a new version.+ Object.assign(stroke, { version: 8, versionNonce: 12, x: 10.12345 });+ expect(roundStroke(stroke)).toEqual({+ ...SAVED_PEN_STROKE, version: 8, versionNonce: 12, x: 10.123+ });++ const rectangle = { id: "r1", type: "rectangle", x: 1.23456 } as ExcalidrawElement;+ expect(roundStroke(rectangle)).toBe(rectangle);+ });+});+/** An empty SVG element for `exportToSvg()` to draw. */function svgOf(id: string) {const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex 37b45f41f1..07051e42da 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -1,7 +1,9 @@import {CaptureUpdateAction, exportToSvg, getSceneVersion, restoreElements} from "@excalidraw/excalidraw";-import { ExcalidrawElement, NonDeletedExcalidrawElement } from "@excalidraw/excalidraw/element/types";+import {+ ExcalidrawElement, ExcalidrawFreeDrawElement, NonDeletedExcalidrawElement+} from "@excalidraw/excalidraw/element/types";import {AppState, BinaryFileData, BinaryFiles, ExcalidrawImperativeAPI, ExcalidrawInitialDataState,ExcalidrawProps, LibraryItem@@ -46,6 +48,9 @@ type ImportantAppState = Pick<AppState, "gridModeEnabled" | "viewBackgroundColor/** The part of a scene that its picture shows. */type PictureScene = Pick<DrawingScene, "elements" | "appState">;+/** A point of a pen stroke, relative to the stroke. */+type StrokePoint = ExcalidrawFreeDrawElement["points"][number];+/*** How long the saves of a canvas note pause before its picture is drawn, in ms. Previews in the app* show the picture.@@ -965,7 +970,7 @@ function buildSceneContent(return {type: "excalidraw",version: 2,- elements,+ elements: elements.map(roundStroke),files,appState: {scrollX: appState.scrollX,@@ -977,6 +982,43 @@ function buildSceneContent(};}+/** The saved copy of each pen stroke, with the version of the stroke that it copies. */+const roundedStrokes = new WeakMap<ExcalidrawElement, {+ version: number;+ versionNonce: number;+ stroke: ExcalidrawFreeDrawElement;+}>();++/**+ * `element`, with the coordinates and the pressures of a pen stroke rounded to thousandths.+ * Excalidraw keeps the full precision of the pointer events, which adds about half to the size of+ * a handwritten scene. Excalidraw changes an element in place, so the copy is kept by version.+ */+export function roundStroke(element: ExcalidrawElement): ExcalidrawElement {+ if (element.type !== "freedraw") return element;+ const rounded = roundedStrokes.get(element);+ if (rounded?.version === element.version && rounded.versionNonce === element.versionNonce) {+ return rounded.stroke;+ }++ const round = (value: number) => Math.round(value * 1000) / 1000;+ const stroke: ExcalidrawFreeDrawElement = {+ ...element,+ x: round(element.x),+ y: round(element.y),+ width: round(element.width),+ height: round(element.height),+ points: element.points.map(([ x, y ]) => [ round(x), round(y) ] as StrokePoint),+ pressures: element.pressures.map(round),+ // Excalidraw clears it when it loads a scene.+ lastCommittedPoint: null+ };+ roundedStrokes.set(element, {+ version: element.version, versionNonce: element.versionNonce, stroke+ });+ return stroke;+}+/** The files that an element of the scene uses. */function getActiveFiles(elements: readonly NonDeletedExcalidrawElement[], files: BinaryFiles) {const activeFiles: Record<string, BinaryFileData> = {};