Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/canvas: add some tests to make sure the implementation is consistent with the future upgrades of Excalidraw

Adorian Doran344232511856
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
index 8bda4f312e..85feb304a1 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
@@ -17,25 +17,27 @@ import {
} from "../text/content_embed_tools";
/** The tools in the order of their buttons. Excalidraw also selects the first nine with 1 to 9. */
-const TOOLS = [
+export const TOOLS = [
"selection", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image",
"eraser", "hand", "frame", "embeddable", "laser"
] as const satisfies readonly ToolType[];
-const LOCK = "lock";
+export const LOCK = "lock";
+/** The commands that click Excalidraw's own `button-undo` and `button-redo`. */
+export const HISTORY_ACTIONS = [ "undo", "redo" ] as const;
/** Excalidraw's zoom step and limits, from its own zoom buttons. */
-const ZOOM_STEP = 0.1;
-const MIN_ZOOM = 0.1;
-const MAX_ZOOM = 30;
+export const ZOOM_STEP = 0.1;
+export const MIN_ZOOM = 0.1;
+export const MAX_ZOOM = 30;
/** The zoom that each zoom button sets, from the current one. */
-const ZOOMS: Record<string, (zoom: number) => number> = {
+export const ZOOMS: Record<string, (zoom: number) => number> = {
zoomOut: (zoom) => zoom - ZOOM_STEP,
resetZoom: () => 1,
zoomIn: (zoom) => zoom + ZOOM_STEP
};
type Tool = typeof TOOLS[number];
-type HistoryAction = "undo" | "redo";
+type HistoryAction = typeof HISTORY_ACTIONS[number];
/** Excalidraw's `t()`, for a key such as `toolBar.rectangle`. */
type Translate = (key: string) => string;
diff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
new file mode 100644
index 0000000000..72d1689695
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
@@ -0,0 +1,96 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join } from "node:path";
+
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@excalidraw/excalidraw", () => ({ useI18n: vi.fn() }));
+
+const {
+ HISTORY_ACTIONS, LOCK, MAX_ZOOM, MIN_ZOOM, TOOLS, ZOOM_STEP, ZOOMS
+} = await import("./CanvasEmbedTools");
+
+/** The classes of Trilium that `CanvasDrawing.css` selects. Every other class is Excalidraw's. */
+const TRILIUM_CLASSES = new Set([
+ "note-detail", "canvas-drawing", "canvas-drawing-editor", "canvas-render",
+ "canvas-drawing-picture", "toolbar-over-panel", "include-note", "include-note-body",
+ "include-note-content", "active"
+]);
+
+/** The classes of Excalidraw that `CanvasDrawing.tsx` and `CanvasEmbedTools.tsx` look up. */
+const CODE_CLASSES = [
+ "excalidraw", "excalidraw-container", "App-menu__left", "App-toolbar-container"
+];
+
+/**
+ * Checks what the canvas drawing relies on beyond Excalidraw's API: the classes and test ids it
+ * selects, the translations of its toolbar, and the zoom it copies. A failure after an upgrade of
+ * Excalidraw names the parts to review.
+ */
+describe("Excalidraw contract of the canvas drawing", () => {
+ const productionDir = dirname(createRequire(import.meta.url).resolve("@excalidraw/excalidraw"));
+ // The minified bundle renames the objects of the translations and the zoom constants.
+ const developmentDir = join(productionDir, "../dev");
+
+ it("renders every class and test id that the drawing selects", () => {
+ const bundle = readBundle(productionDir, [ ".js", ".css" ]);
+ // Vitest gives an empty string for a stylesheet imported with `?raw`.
+ const styles = readFileSync(join(__dirname, "CanvasDrawing.css"), "utf8")
+ .replace(/\/\*[\s\S]*?\*\//g, "");
+ const classes = [ ...styles.matchAll(/\.(-?[_a-zA-Z][\w-]*)/g) ]
+ .map((match) => match[1])
+ .filter((name) => !TRILIUM_CLASSES.has(name));
+ const testIds = [ ...styles.matchAll(/data-testid="([^"]+)"/g) ].map((match) => match[1]);
+ const names = new Set([
+ ...classes,
+ ...CODE_CLASSES,
+ ...testIds,
+ ...HISTORY_ACTIONS.map((id) => `button-${id}`)
+ ]);
+
+ const missing = [ ...names ]
+ .filter((name) => !new RegExp(`(?<![\\w-])${name}(?![\\w-])`).test(bundle));
+ expect(missing, "Gone from Excalidraw, or a Trilium class missing in TRILIUM_CLASSES")
+ .toEqual([]);
+ });
+
+ it("names every button of the toolbar with Excalidraw's own translations", () => {
+ const source = readBundle(developmentDir, [ ".js" ]);
+ const keys = [
+ ...[ ...TOOLS, LOCK ].map((id) => `toolBar.${id}`),
+ ...[ ...HISTORY_ACTIONS, ...Object.keys(ZOOMS) ].map((id) => `buttons.${id}`)
+ ];
+
+ const missing = keys.filter((key) => {
+ const [ section, name ] = key.split(".");
+ return !getEnglishKeys(source, section).has(name);
+ });
+ expect(missing).toEqual([]);
+ });
+
+ it("zooms with the step, the limits and the math that the toolbar copies", () => {
+ const source = readBundle(developmentDir, [ ".js" ]).replace(/\s+/g, "");
+
+ expect(source).toContain(`varZOOM_STEP=${ZOOM_STEP};`);
+ expect(source).toContain(`varMIN_ZOOM=${MIN_ZOOM};`);
+ expect(source).toContain(`varMAX_ZOOM=${MAX_ZOOM};`);
+ // `getZoomState()` keeps the center of the view in place, as `getStateForZoom()` does.
+ expect(source).toContain("viewportX:appState.width/2+appState.offsetLeft");
+ expect(source).toContain("baseScrollX=appState.scrollX+(appLayerX-appLayerX/currentZoom)");
+ expect(source).toContain("zoomOffsetScrollX=-(appLayerX-appLayerX/nextZoom)");
+ });
+});
+
+/** The text of the scripts or stylesheets in `dir`, without its locales and fonts. */
+function readBundle(dir: string, extensions: string[]) {
+ return readdirSync(dir)
+ .filter((file) => extensions.some((extension) => file.endsWith(extension)))
+ .map((file) => readFileSync(join(dir, file), "utf8"))
+ .join("\n");
+}
+
+/** The keys of the English translations in `section`, such as `toolBar`. */
+function getEnglishKeys(source: string, section: string) {
+ const body = source.match(new RegExp(`\\nvar ${section} = \\{([\\s\\S]*?)\\n\\};`))?.[1] ?? "";
+ return new Set([ ...body.matchAll(/^\s+(\w+):/gm) ].map((match) => match[1]));
+}