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
feat(import): convert Obsidian Excalidraw drawings to canvas notes
Elian Doran971a9ee85612
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.jsonindex 050d118c9c..b2dba727b7 100644--- a/packages/trilium-core/package.json+++ b/packages/trilium-core/package.json@@ -15,6 +15,7 @@"escape-html": "1.0.3","i18next": "26.3.1","js-yaml": "5.1.0",+ "lz-string": "1.5.0","mime-types": "3.0.2","node-html-parser": "8.0.3","sanitize-filename": "1.6.4",diff --git a/packages/trilium-core/src/services/import/obsidian/attachments.ts b/packages/trilium-core/src/services/import/obsidian/attachments.tsindex c9e95d810c..5572dfb67f 100644--- a/packages/trilium-core/src/services/import/obsidian/attachments.ts+++ b/packages/trilium-core/src/services/import/obsidian/attachments.ts@@ -90,14 +90,14 @@ function replaceWithFileLink(element: HTMLElement, note: BNote, resolved: Resolvelement.remove();}-interface ResolvedAttachment {+export interface ResolvedAttachment {path: string;bytes: Uint8Array;mime: string;}/** Resolves a reference name to a bundled attachment: an exact path first, then a unique base-name match. */-function resolveAttachment(index: AttachmentIndex, name: string): ResolvedAttachment | null {+export function resolveAttachment(index: AttachmentIndex, name: string): ResolvedAttachment | null {let path = name;let bytes = index.byPath.get(path);if (!bytes) {@@ -148,7 +148,7 @@ function safeDecode(value: string): string {}}-function isImageMime(mime: string): boolean {+export function isImageMime(mime: string): boolean {return mime.startsWith("image/");}diff --git a/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.ts b/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.tsnew file mode 100644index 0000000000..79bb155c37--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.ts@@ -0,0 +1,76 @@+import LZString from "lz-string";+import { describe, expect, it } from "vitest";++import { isExcalidrawPath, parseExcalidraw } from "./excalidraw.js";++/** Wraps a scene object in an Obsidian Excalidraw-plugin Markdown file with a compressed-json drawing block. */+function compressedFile(scene: object, embeddedFiles = ""): string {+ const compressed = LZString.compressToBase64(JSON.stringify(scene));+ return `---\nexcalidraw-plugin: parsed\ntags: [excalidraw]\n---\n# Excalidraw Data\n## Text Elements\n${embeddedFiles}%%\n## Drawing\n\`\`\`compressed-json\n${compressed}\n\`\`\`\n%%`;+}++const SCENE = {+ type: "excalidraw",+ version: 2,+ source: "https://github.com/zsviczian/obsidian-excalidraw-plugin",+ elements: [{ id: "a", type: "rectangle", x: 0, y: 0 }],+ appState: { viewBackgroundColor: "#fff", gridModeEnabled: false },+ files: {}+};++describe("isExcalidrawPath", () => {+ it("matches only the plugin's `.excalidraw.md` suffix, case-insensitively", () => {+ expect(isExcalidrawPath("Excalidraw/Drawing.excalidraw.md")).toBe(true);+ expect(isExcalidrawPath("Drawing.EXCALIDRAW.MD")).toBe(true);+ expect(isExcalidrawPath("Note.md")).toBe(false);+ expect(isExcalidrawPath("Drawing.excalidraw")).toBe(false);+ });+});++describe("parseExcalidraw", () => {+ it("decompresses a compressed-json drawing into canvas content with `files` emptied", () => {+ const drawing = parseExcalidraw(compressedFile(SCENE));+ if (!drawing) {+ throw new Error("drawing was not parsed");+ }++ const content = JSON.parse(drawing.content);+ // The Trilium canvas shape: type/version/elements/appState carried over, the source key dropped and+ // files emptied (images become attachments, not inline data).+ expect(content).toEqual({+ type: "excalidraw",+ version: 2,+ elements: [{ id: "a", type: "rectangle", x: 0, y: 0 }],+ files: {},+ appState: { viewBackgroundColor: "#fff", gridModeEnabled: false }+ });+ expect(drawing.embeddedFiles.size).toBe(0);+ });++ it("parses an uncompressed `## Drawing` json block", () => {+ const markdown = `## Drawing\n\`\`\`json\n${JSON.stringify(SCENE)}\n\`\`\``;+ const drawing = parseExcalidraw(markdown);+ expect(drawing && JSON.parse(drawing.content).elements).toEqual([{ id: "a", type: "rectangle", x: 0, y: 0 }]);+ });++ it("maps an image element's fileId to its embedded vault file, ignoring unreferenced entries", () => {+ const scene = {+ ...SCENE,+ elements: [{ id: "img", type: "image", fileId: "abc123def456" }]+ };+ const embedded = "## Embedded Files\nabc123def456: [[picture.png|100]]\nffffffffffff: [[unused.png]]\n";+ const drawing = parseExcalidraw(compressedFile(scene, embedded));+ if (!drawing) {+ throw new Error("drawing was not parsed");+ }++ // Only the fileId an element references is kept, and the `|size` alias is stripped to the bare ref.+ expect([...drawing.embeddedFiles]).toEqual([["abc123def456", "picture.png"]]);+ });++ it("returns null when there is no drawing block or the data is corrupt", () => {+ expect(parseExcalidraw("# Just a heading\nNo drawing here.")).toBeNull();+ expect(parseExcalidraw("## Drawing\n```compressed-json\nnot-valid-base64!!\n```")).toBeNull();+ expect(parseExcalidraw("## Drawing\n```json\n{ not json\n```")).toBeNull();+ });+});diff --git a/packages/trilium-core/src/services/import/obsidian/excalidraw.ts b/packages/trilium-core/src/services/import/obsidian/excalidraw.tsnew file mode 100644index 0000000000..43fc773eb8--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/excalidraw.ts@@ -0,0 +1,112 @@+/**+ * Converts an Obsidian Excalidraw-plugin drawing (`*.excalidraw.md`) into a Trilium `canvas` note.+ *+ * The plugin stores a drawing as a Markdown file with the real scene tucked into a `## Drawing` section —+ * either a `compressed-json` fence (LZ-String/base64, the default) or a plain `json` fence. Both decompress /+ * parse to a standard Excalidraw scene (`{ type, version, elements, appState, files }`), which is exactly the+ * shape a Trilium canvas note stores, so the conversion is mostly a matter of extracting and re-emitting it.+ *+ * Embedded images are not inlined in the scene: an image element carries a `fileId` that the file's+ * `## Embedded Files` section maps to a vault file (`<fileId>: [[image.png]]`). The caller resolves those+ * vault files and saves them as `image`-role attachments titled with the `fileId` — the same way the canvas+ * editor persists images — so the scene's `fileId` references resolve on load. The emitted scene therefore+ * keeps `files` empty (the bytes live in attachments).+ */++import LZString from "lz-string";++interface ExcalidrawScene {+ elements?: unknown[];+ appState?: Record<string, unknown>;+}++export interface ExcalidrawDrawing {+ /** The Trilium canvas content JSON (an Excalidraw scene with `files` emptied — images become attachments). */+ content: string;+ /** Excalidraw `fileId` -> the embedded vault file it references (only ids actually used by an element). */+ embeddedFiles: Map<string, string>;+}++/** Whether a vault path is an Obsidian Excalidraw drawing (the plugin names them `*.excalidraw.md`). */+export function isExcalidrawPath(path: string): boolean {+ return /\.excalidraw\.md$/i.test(path);+}++/**+ * Parses an Excalidraw-plugin Markdown file into the canvas content plus its embedded-image references.+ * Returns `null` when no usable drawing can be extracted (no `## Drawing` block, bad compression, invalid+ * JSON), so the caller can fall back to importing the file as an ordinary text note.+ */+export function parseExcalidraw(markdown: string): ExcalidrawDrawing | null {+ const scene = extractScene(markdown);+ if (!scene) {+ return null;+ }++ const elements = Array.isArray(scene.elements) ? scene.elements : [];+ const content = JSON.stringify({+ type: "excalidraw",+ version: 2,+ elements,+ // Images are persisted as attachments (keyed by fileId), not inline, matching the canvas editor.+ files: {},+ appState: scene.appState ?? {}+ });++ return { content, embeddedFiles: collectEmbeddedFiles(markdown, elements) };+}++/** Extracts and parses the Excalidraw scene from the `## Drawing` section (compressed first, then plain JSON). */+function extractScene(markdown: string): ExcalidrawScene | null {+ const compressed = /```compressed-json\r?\n([\s\S]*?)```/.exec(markdown);+ if (compressed) {+ const json = LZString.decompressFromBase64(compressed[1].replace(/[\r\n]/g, ""));+ return json ? safeParseScene(json) : null;+ }+ const plain = /##+\s+Drawing\s*\r?\n```json\r?\n([\s\S]*?)```/.exec(markdown);+ if (plain) {+ return safeParseScene(plain[1]);+ }+ return null;+}++function safeParseScene(json: string): ExcalidrawScene | null {+ try {+ const parsed = JSON.parse(json);+ return parsed && typeof parsed === "object" ? (parsed as ExcalidrawScene) : null;+ } catch {+ return null;+ }+}++/**+ * Reads the `## Embedded Files` section (`<fileId>: [[vault file]]` per line), keeping only the file ids that+ * an image element actually references so no orphan attachments are created. Display aliases / size suffixes+ * (`[[file|alias]]`) are stripped down to the bare vault reference.+ */+function collectEmbeddedFiles(markdown: string, elements: unknown[]): Map<string, string> {+ const usedFileIds = new Set<string>();+ for (const element of elements) {+ if (element && typeof element === "object" && "fileId" in element) {+ const fileId = (element as { fileId?: unknown }).fileId;+ if (typeof fileId === "string") {+ usedFileIds.add(fileId);+ }+ }+ }++ const embeddedFiles = new Map<string, string>();+ if (usedFileIds.size === 0) {+ return embeddedFiles;+ }++ const lineRegex = /^([0-9a-fA-F]{6,}):\s*\[\[(.+?)\]\]\s*$/gm;+ let match: RegExpExecArray | null;+ while ((match = lineRegex.exec(markdown)) !== null) {+ const [, fileId, ref] = match;+ if (usedFileIds.has(fileId)) {+ embeddedFiles.set(fileId, ref.split("|")[0].trim());+ }+ }+ return embeddedFiles;+}diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.tsindex b85f0d10cb..1e4923b458 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -1,4 +1,5 @@import { ZipArchive } from "archiver";+import LZString from "lz-string";import { PassThrough } from "stream";import { describe, expect, it } from "vitest";@@ -23,6 +24,12 @@ async function createZipBuffer(files: Record<string, string | Buffer>): Promise<return Buffer.concat(chunks);}+/** Builds an Obsidian Excalidraw-plugin Markdown file wrapping `scene` in a compressed-json drawing block. */+function excalidrawFile(scene: object, embeddedFiles = ""): string {+ const compressed = LZString.compressToBase64(JSON.stringify(scene));+ return `---\nexcalidraw-plugin: parsed\ntags: [excalidraw]\n---\n# Excalidraw Data\n${embeddedFiles}%%\n## Drawing\n\`\`\`compressed-json\n${compressed}\n\`\`\`\n%%`;+}+/** Runs the Obsidian importer over `files` and returns the import root note. */async function importObsidian(files: Record<string, string | Buffer>, fileName?: string): Promise<BNote> {const buffer = await createZipBuffer(files);@@ -254,6 +261,79 @@ describe("Obsidian importer — integration", () => {expect(decodeUtf8(linker?.getContent() ?? "")).toContain(`href="#root/${target?.noteId}"`);});+ it("converts an Excalidraw-plugin drawing into a canvas note titled without the suffix", async () => {+ const importRoot = await importObsidian({+ "Excalidraw/Drawing.excalidraw.md": excalidrawFile({+ type: "excalidraw",+ version: 2,+ source: "https://github.com/zsviczian/obsidian-excalidraw-plugin",+ elements: [{ id: "rect", type: "rectangle", x: 0, y: 0 }],+ appState: { viewBackgroundColor: "#ffffff" },+ files: {}+ }),+ ".obsidian/app.json": "{}"+ });++ const drawing = importRoot.getChildNotes().find((n) => n.title === "Excalidraw")?.getChildNotes()[0];+ if (!drawing) {+ throw new Error("drawing was not imported");+ }++ // The drawing becomes a canvas note, not a text note, titled without its `.excalidraw.md` suffix.+ expect(drawing.title).toBe("Drawing");+ expect(drawing.type).toBe("canvas");+ expect(drawing.mime).toBe("application/json");++ const content = JSON.parse(decodeUtf8(drawing.getContent()));+ expect(content.type).toBe("excalidraw");+ expect(content.elements).toEqual([{ id: "rect", type: "rectangle", x: 0, y: 0 }]);+ // No `excalidraw-plugin`/`tags` labels leak in from the plugin front matter.+ expect(drawing.getOwnedAttributes()).toHaveLength(0);+ });++ it("saves a drawing's embedded image as an image attachment titled with its Excalidraw fileId", async () => {+ const importRoot = await importObsidian({+ "Drawing.excalidraw.md": excalidrawFile({+ type: "excalidraw",+ elements: [{ id: "img", type: "image", fileId: "abc123def456" }],+ appState: {},+ files: {}+ }, "## Embedded Files\nabc123def456: [[shot.png]]\n"),+ "shot.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png")+ });++ const drawing = importRoot.getChildNotes().find((n) => n.title === "Drawing");+ // The image is stored as an `image`-role attachment whose title is the fileId the scene references,+ // matching how the canvas editor persists images so it renders on load.+ const images = drawing?.getAttachmentsByRole("image");+ expect(images?.map((a) => a.title)).toEqual(["abc123def456"]);+ });++ it("resolves a wikilink that targets an Excalidraw drawing by name", async () => {+ const importRoot = await importObsidian({+ "Note.md": "See [[Drawing]].",+ "Drawing.excalidraw.md": excalidrawFile({ type: "excalidraw", elements: [], appState: {}, files: {} })+ });++ const note = importRoot.getChildNotes().find((n) => n.title === "Note");+ const drawing = importRoot.getChildNotes().find((n) => n.title === "Drawing");+ if (!note || !drawing) {+ throw new Error("notes were not imported");+ }++ expect(decodeUtf8(note.getContent())).toContain(`href="#root/${drawing.noteId}"`);+ expect(note.getRelations().filter((r) => r.name === "internalLink").map((r) => r.value)).toEqual([drawing.noteId]);+ });++ it("falls back to a text note when a `.excalidraw.md` file has no usable drawing data", async () => {+ const importRoot = await importObsidian({ "Broken.excalidraw.md": "Just some text, no drawing block." });++ const note = importRoot.getChildNotes().find((n) => n.title === "Broken");+ // A drawing that can't be decoded is imported as ordinary text rather than dropped.+ expect(note?.type).toBe("text");+ expect(decodeUtf8(note?.getContent() ?? "")).toBe("<p>Just some text, no drawing block.</p>");+ });+it("unwraps unresolvable and ambiguous wikilinks to plain text, recording no relation", async () => {const importRoot = await importObsidian({"Missing.md": "Go to [[Nowhere]].",diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsindex 6f8728e38b..62458c55dd 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -6,6 +6,10 @@* container note holding its notes). The `.obsidian/` config folder and any other dot-prefixed entry are* skipped, and non-Markdown files (attachments, `.canvas`, `.base`, …) are dropped for now.*+ * An Excalidraw-plugin drawing (`*.excalidraw.md`) is the exception to the "Markdown becomes a text note"+ * rule: it's decoded into a Trilium `canvas` note instead, with its embedded images saved as attachments+ * (see {@link ./excalidraw.js}).+ ** A vault can be zipped two ways — its *contents* (so `.obsidian/` sits at the zip root) or its *outer* folder* (so everything is nested under `Vault name/`). The location of `.obsidian/` pins the true vault* root either way, so the redundant wrapper folder is stripped and the import root is named after the vault.@@ -33,7 +37,8 @@ import { basename } from "../../utils/path.js";import { getZipProvider } from "../../zip_provider.js";import { extractFrontmatter } from "../frontmatter.js";import markdownService from "../markdown.js";-import { applyAttachments, buildAttachmentIndex } from "./attachments.js";+import { applyAttachments, type AttachmentIndex, buildAttachmentIndex, isImageMime, resolveAttachment } from "./attachments.js";+import { type ExcalidrawDrawing, isExcalidrawPath, parseExcalidraw } from "./excalidraw.js";import { buildNoteIndex, resolveLinks } from "./links.js";interface VaultNote {@@ -119,6 +124,19 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map// attachments saved. Content is persisted once, in the link pass, to avoid a second write per note.for (const vaultNote of notes) {const parent = ensureFolder(parentFolder(vaultNote.path), rootNote, folderNotes, isProtected);++ // An Obsidian Excalidraw drawing becomes a `canvas` note rather than rendered Markdown. It's still+ // added to `created` (with empty content) so other notes can wikilink to it, but it carries no HTML+ // for the link/attachment passes below. A drawing that can't be parsed falls through to text import.+ if (isExcalidrawPath(vaultNote.path)) {+ const note = createExcalidrawNote(parent, vaultNote, attachmentIndex, isProtected);+ if (note) {+ created.push({ note, path: vaultNote.path.replace(/\.excalidraw\.md$/i, ""), rendered: "", content: "" });+ taskContext.increaseProgressCount();+ continue;+ }+ }+const { body, attributes } = extractFrontmatter(vaultNote.markdown);const rendered = markdownService.renderToHtml(body, vaultNote.title, { obsidian: true });const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: rendered, type: "text", mime: "text/html", isProtected });@@ -155,6 +173,30 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Mapreturn rootNote;}+/**+ * Creates a `canvas` note from an Obsidian Excalidraw drawing, returning it (or `null` when the drawing can't+ * be parsed, so the caller can fall back to a text note). Each image the scene embeds is resolved against the+ * vault attachments and saved as an `image`-role attachment titled with its Excalidraw `fileId`, exactly how+ * the canvas editor stores images, so the scene's `fileId` references render on load.+ */+function createExcalidrawNote(parent: BNote, vaultNote: VaultNote, attachmentIndex: AttachmentIndex, isProtected: boolean): BNote | null {+ const drawing: ExcalidrawDrawing | null = parseExcalidraw(vaultNote.markdown);+ if (!drawing) {+ return null;+ }++ const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: drawing.content, type: "canvas", mime: "application/json", isProtected });++ for (const [fileId, ref] of drawing.embeddedFiles) {+ const resolved = resolveAttachment(attachmentIndex, ref);+ if (resolved && isImageMime(resolved.mime)) {+ note.saveAttachment({ role: "image", mime: resolved.mime, title: fileId, content: resolved.bytes });+ }+ }++ return note;+}+/** Returns (creating on demand, parents first) the container note for `folderPath`; the empty path is the root. */function ensureFolder(folderPath: string, rootNote: BNote, folderNotes: Map<string, BNote>, isProtected: boolean): BNote {if (folderPath === "") {@@ -251,9 +293,16 @@ function isSpecial(path: string): boolean {return /\.(canvas|base)$/i.test(path);}-/** The note title for a Markdown file: its base name without the `.md` extension. */+/**+ * The note title for a Markdown file: its base name without the `.md` extension. An Excalidraw drawing drops+ * its full `.excalidraw.md` suffix so the note is titled like Obsidian shows it (e.g. `Drawing 2026-…`).+ */function noteTitle(path: string): string {- return basename(path).replace(/\.md$/i, "");+ const base = basename(path);+ if (isExcalidrawPath(base)) {+ return base.replace(/\.excalidraw\.md$/i, "");+ }+ return base.replace(/\.md$/i, "");}export default { importObsidian };diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e6d01cec73..a45af4d66d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1632,6 +1632,9 @@ importers:js-yaml:specifier: 5.1.0version: 5.1.0+ lz-string:+ specifier: 1.5.0+ version: 1.5.0mime-types:specifier: 3.0.2version: 3.0.2@@ -10417,6 +10420,10 @@ packages:resolution: {integrity: sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==}engines: {node: '>=12'}+ resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}+ hasBin: true+resolution: {integrity: sha512-yiLHa7cfJcGRFq4FrR4tMlpNHb4Vy4mWnpajlSSIFM5k4Lv8/7BbbDLzCAVogWNl0LlLhizRp1drXv0hK9h0Yw==}os: [darwin]@@ -25043,6 +25050,8 @@ snapshots:+ [email protected]: {}+dependencies:nan: 2.27.0