Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): import OneNote images, file attachments and ink

Elian Doran803b4b964b4e
diff --git a/apps/server/src/services/import/onenote/converter.spec.ts b/apps/server/src/services/import/onenote/converter.spec.ts
index b16077ae67..572ea1c5b5 100644
--- a/apps/server/src/services/import/onenote/converter.spec.ts
+++ b/apps/server/src/services/import/onenote/converter.spec.ts
@@ -198,6 +198,22 @@ const ALIGNMENT_SAMPLE = `<html lang="en-US">
</body>
</html>`;
+// Real OneNote source (debug-captured): an inline image and a file attachment, both served from
+// authenticated Graph `/resources/{id}/$value` URLs. The image carries an extra full-resolution
+// `data-fullres-src`; the attachment is an <object> the sanitizer would otherwise drop entirely.
+const RESOURCE_SAMPLE = `<html lang="en-US">
+ <body data-absolute-enabled="true" style="font-family:Calibri;font-size:11pt">
+ <div style="position:absolute;left:48px;top:115px;width:624px">
+ <object data-attachment="HelloWorld.txt" type="text/plain" data="https://graph.microsoft.com/v1.0/users('me')/onenote/resources/0-aaa!1-BBB!sccc/$value" />
+ <br />
+ </div>
+ <div style="position:absolute;left:569px;top:116px;width:624px">
+ <img width="480" height="441" src="https://graph.microsoft.com/v1.0/users('me')/onenote/resources/0-ddd!1-BBB!sccc/$value" data-src-type="image/png" data-fullres-src="https://graph.microsoft.com/v1.0/users('me')/onenote/resources/0-eee!1-BBB!sccc/$value" data-fullres-src-type="image/png" />
+ <br />
+ </div>
+ </body>
+</html>`;
+
// Real OneNote source (debug-captured): OneNote puts the list marker type on each <li> and wraps
// item text in a margin-0 <p>. The marker type belongs on the <ul>/<ol> (CKEditor's representation),
// and OneNote's lower-alpha/upper-alpha map to CKEditor's lower-latin/upper-latin.
@@ -401,6 +417,26 @@ describe("convertPageHtml", () => {
expect(out).toContain("πŸŽ¬πŸ“š Movie and book");
});
+ it("normalizes OneNote resource references so the importer can rewrite them", () => {
+ const out = converter.convertPageHtml(RESOURCE_SAMPLE);
+ const root = parse(out);
+
+ // The <object> attachment (which the sanitizer would drop) becomes a marker anchor carrying the
+ // Graph URL, mime and filename.
+ const anchor = root.querySelector("a.onenote-attachment");
+ expect(anchor?.getAttribute("href")).toContain("/resources/0-aaa!1-BBB!sccc/$value");
+ expect(anchor?.getAttribute("data-mime")).toBe("text/plain");
+ expect(anchor?.textContent).toBe("HelloWorld.txt");
+ expect(out).not.toContain("<object");
+
+ // The image keeps its display-resolution src but sheds the extra full-resolution data-* URLs.
+ const img = root.querySelector("img");
+ expect(img?.getAttribute("src")).toContain("/resources/0-ddd!1-BBB!sccc/$value");
+ expect(out).not.toContain("data-fullres-src");
+ expect(out).not.toContain("data-src-type");
+ expect(out).not.toContain("0-eee"); // the full-resolution resource id is gone
+ });
+
it("converts inline-style formatting (bold/italic/underline) to semantic tags", () => {
const out = converter.convertPageHtml(FORMATTING_SAMPLE);
expect(out).toContain("<strong>Bold text.</strong>");
diff --git a/apps/server/src/services/import/onenote/converter.ts b/apps/server/src/services/import/onenote/converter.ts
index 4212d3acb1..910bbbdc44 100644
--- a/apps/server/src/services/import/onenote/converter.ts
+++ b/apps/server/src/services/import/onenote/converter.ts
@@ -21,9 +21,16 @@
* No fetch option recovers it; the only indentation Graph keeps is list nesting (ol/ul/li).
*/
-import { sanitize } from "@triliumnext/core";
+import { sanitize, utils } from "@triliumnext/core";
import { HTMLElement, parse } from "node-html-parser";
+/**
+ * The marker class the importer keys on to find OneNote file attachments (see importer.ts). The href
+ * carries the Graph resource URL (a placeholder the importer swaps for a local attachment link) and
+ * `data-mime` the original content type.
+ */
+export const ONENOTE_ATTACHMENT_CLASS = "onenote-attachment";
+
/** Block containers whose direct <br> children are spacing artifacts rather than soft breaks. */
const BLOCK_CONTAINERS = new Set(["body", "div", "section", "article", "blockquote", "td", "th", "ol", "ul", "dl"]);
@@ -99,6 +106,7 @@ export function convertPageHtml(rawHtml: string): string {
const scope = root.querySelector("body") ?? root;
sortPositionedOutlines(scope);
+ convertResourceReferences(scope);
convertTags(scope);
convertInlineFormatting(scope);
normalizeNamedColors(scope);
@@ -135,6 +143,38 @@ function sortPositionedOutlines(scope: HTMLElement) {
}
}
+/**
+ * OneNote references binary resources by authenticated Graph URLs that Trilium can't load directly
+ * (e.g. `…/onenote/resources/{id}/$value`). Normalize them into a form the importer can recognize and
+ * rewrite once the bytes are downloaded:
+ * - file attachments arrive as `<object data-attachment="name" type="mime" data="url">`, a tag the
+ * sanitizer drops entirely; turn each into an `<a class="onenote-attachment">` carrying the URL
+ * (href), mime (data-mime) and filename (text);
+ * - images keep their (display-resolution) `src` but shed OneNote's extra `data-*` URLs β€” chiefly the
+ * full-resolution variant, a second authenticated URL that would never load.
+ * The importer downloads each URL and swaps in a local attachment reference (see importer.ts).
+ */
+function convertResourceReferences(scope: HTMLElement) {
+ for (const object of scope.querySelectorAll("object[data-attachment]")) {
+ const url = object.getAttribute("data") ?? "";
+ const name = object.getAttribute("data-attachment") || "attachment";
+ const mime = object.getAttribute("type") || "application/octet-stream";
+ object.insertAdjacentHTML(
+ "beforebegin",
+ `<a class="${ONENOTE_ATTACHMENT_CLASS}" data-mime="${utils.escapeHtml(mime)}" href="${utils.escapeHtml(url)}">${utils.escapeHtml(name)}</a>`
+ );
+ object.remove();
+ }
+
+ for (const img of scope.querySelectorAll("img")) {
+ for (const attr of Object.keys(img.attributes)) {
+ if (attr.startsWith("data-")) {
+ img.removeAttribute(attr);
+ }
+ }
+ }
+}
+
/**
* OneNote represents note tags as a `data-tag` attribute on a <p> β€” a comma-separated list of
* `shape[:status]` values (e.g. `to-do:completed`, `important`, `movie-to-see,book-to-read`).
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 0eedff7c5a..29976bf629 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -68,15 +68,68 @@ export async function listPages(accessToken: string, sectionId: string): Promise
}));
}
-/** Returns the raw HTML body of a page (a full HTML document as produced by the OneNote API). */
-export async function getPageContent(accessToken: string, pageId: string): Promise<string> {
- const response = await fetch(`${GRAPH_BASE}/me/onenote/pages/${pageId}/content`, {
+/**
+ * Returns a page's content, split into its HTML body and (optional) InkML.
+ *
+ * We request `includeInkML=true` so handwriting/drawings β€” which the default HTML output drops,
+ * leaving only `<!-- InkNode is not supported -->` comments β€” come back as a separate InkML part. With
+ * that flag the response is a MIME multipart envelope (one `text/html` part, one
+ * `application/inkml+xml` part), which parsePageContent splits apart. Pages without ink may still come
+ * back as plain HTML, which the parser handles by returning the whole body as `html`.
+ */
+export async function getPageContent(accessToken: string, pageId: string): Promise<{ html: string; inkml: string }> {
+ const response = await fetch(`${GRAPH_BASE}/me/onenote/pages/${pageId}/content?includeInkML=true`, {
headers: { Authorization: `Bearer ${accessToken}` }
});
if (!response.ok) {
throw new Error(`Failed to fetch OneNote page content (HTTP ${response.status})`);
}
- return response.text();
+ return parsePageContent(await response.text());
+}
+
+/**
+ * Splits a OneNote page response into its HTML and InkML parts. A page fetched with
+ * `includeInkML=true` comes back as a MIME multipart body whose first line is the boundary; each part
+ * carries header lines (including `Content-Type`), then a blank line, then the body. A non-multipart
+ * response (no leading `--` boundary) is returned verbatim as the HTML part.
+ */
+export function parsePageContent(raw: string): { html: string; inkml: string } {
+ const normalized = raw.replace(/\r\n/g, "\n");
+ const boundary = normalized.slice(0, normalized.indexOf("\n")).trim();
+ if (!boundary.startsWith("--")) {
+ return { html: raw.trim(), inkml: "" };
+ }
+
+ let html = "";
+ let inkml = "";
+ for (const part of normalized.split(boundary)) {
+ const separator = part.indexOf("\n\n");
+ if (separator < 0) {
+ continue;
+ }
+ const headers = part.slice(0, separator).toLowerCase();
+ const body = part.slice(separator + 2).trim();
+ if (headers.includes("text/html")) {
+ html = body;
+ } else if (headers.includes("application/inkml+xml")) {
+ inkml = body;
+ }
+ }
+ return { html, inkml };
+}
+
+/**
+ * Downloads a binary resource (image or file attachment) referenced from page HTML. The URL is an
+ * absolute Graph `…/resources/{id}/$value` link, so it is fetched directly rather than relative to the
+ * API base. Returns the raw bytes plus the server-reported content type.
+ */
+export async function getResource(accessToken: string, url: string): Promise<{ content: Uint8Array; contentType: string }> {
+ const response = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
+ if (!response.ok) {
+ throw new Error(`Failed to fetch OneNote resource (HTTP ${response.status})`);
+ }
+ const buffer = new Uint8Array(await response.arrayBuffer());
+ return { content: buffer, contentType: response.headers.get("content-type") ?? "application/octet-stream" };
}
interface RawNotebook {
@@ -125,5 +178,6 @@ export default {
getAccount,
listNotebooks,
listPages,
- getPageContent
+ getPageContent,
+ getResource
};
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 7994a21805..b76fd2a2c5 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -5,11 +5,13 @@
* client-side import toasts apply unchanged.
*/
-import { becca, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";
+import { becca, type BNote, binary_utils, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";
+import { parse } from "node-html-parser";
import sql from "../../sql.js";
-import converter from "./converter.js";
+import converter, { ONENOTE_ATTACHMENT_CLASS } from "./converter.js";
import graph from "./graph.js";
+import { inkmlToSvg } from "./inkml.js";
export interface SectionSelection {
id: string;
@@ -22,6 +24,22 @@ interface FetchedPage {
html: string;
/** The unmodified HTML returned by the Graph API, kept only when debug mode is on. */
rawHtml: string;
+ /** The unmodified InkML (handwriting) returned by the Graph API, kept only when debug mode is on. */
+ rawInkml: string;
+ /** The page's handwriting/drawing rendered to an SVG, embedded as an inline image (null if none). */
+ inkSvg: string | null;
+ /** Binary resources (images, file attachments) referenced by the page, downloaded up front. */
+ resources: DownloadedResource[];
+}
+
+interface DownloadedResource {
+ /** The Graph resource URL as it still appears in the converted HTML; used to match references. */
+ url: string;
+ kind: "image" | "file";
+ /** Original filename for attachments; a base name (no extension) for images. */
+ title: string;
+ mime: string;
+ content: Uint8Array;
}
interface FetchedSection {
@@ -40,8 +58,10 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
const pages = await graph.listPages(accessToken, section.id);
const fetchedPages: FetchedPage[] = [];
for (const page of pages) {
- const rawHtml = await graph.getPageContent(accessToken, page.id);
- fetchedPages.push({ title: page.title, html: converter.convertPageHtml(rawHtml), rawHtml });
+ const { html: rawHtml, inkml } = await graph.getPageContent(accessToken, page.id);
+ const html = converter.convertPageHtml(rawHtml);
+ const resources = await downloadPageResources(accessToken, html);
+ fetchedPages.push({ title: page.title, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources });
taskContext.increaseProgressCount();
}
fetched.push({ title: section.title, notebookTitle: section.notebookTitle, pages: fetchedPages });
@@ -85,8 +105,23 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
isProtected
});
- // Debug aid: keep the unmodified Graph HTML alongside the converted note so the two can
- // be compared when diagnosing conversion issues.
+ // Resources and ink both need the page note to exist (attachments hang off it), so build
+ // the final content once: swap Graph URLs for local attachment references, then append the
+ // page's handwriting/drawing as an inline SVG image.
+ let content = page.html;
+ if (page.resources.length > 0) {
+ content = rewritePageResources(pageNote, content, page.resources);
+ }
+ if (page.inkSvg) {
+ content += renderInkFigure(pageNote, page.inkSvg);
+ }
+ if (content !== page.html) {
+ pageNote.setContent(content);
+ void noteService.asyncPostProcessContent(pageNote, content);
+ }
+
+ // Debug aid: keep the unmodified Graph HTML (and InkML, when present) alongside the
+ // converted note so the two can be compared when diagnosing conversion issues.
if (debug) {
pageNote.saveAttachment({
role: "file",
@@ -94,6 +129,14 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
title: "OneNote source.html",
content: page.rawHtml
});
+ if (page.rawInkml) {
+ pageNote.saveAttachment({
+ role: "file",
+ mime: "application/inkml+xml",
+ title: "OneNote ink.inkml",
+ content: page.rawInkml
+ });
+ }
}
}
}
@@ -101,4 +144,95 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
return rootNote.noteId;
}
+/**
+ * Saves a page's rendered ink SVG as an image attachment on the note and returns the `<figure>` markup
+ * that embeds it inline. Returns an empty string if the attachment could not be created.
+ */
+function renderInkFigure(note: BNote, svg: string): string {
+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, binary_utils.encodeUtf8(svg), "OneNote ink.svg", false);
+ if (!attachmentId) {
+ return "";
+ }
+ return `<figure class="image"><img src="api/attachments/${attachmentId}/image/${encodeURIComponent(title)}"></figure>`;
+}
+
+/**
+ * Finds the Graph resource URLs a converted page references (image `src`, attachment-link `href`) and
+ * downloads each once. Failures are logged and skipped so one missing resource doesn't abort the whole
+ * import; the reference is simply left untouched.
+ */
+async function downloadPageResources(accessToken: string, html: string): Promise<DownloadedResource[]> {
+ const root = parse(html);
+
+ const refs = new Map<string, Omit<DownloadedResource, "content">>();
+ for (const img of root.querySelectorAll("img")) {
+ const url = img.getAttribute("src") ?? "";
+ if (isGraphResourceUrl(url) && !refs.has(url)) {
+ refs.set(url, { url, kind: "image", title: "image", mime: "" });
+ }
+ }
+ for (const anchor of root.querySelectorAll(`a.${ONENOTE_ATTACHMENT_CLASS}`)) {
+ const url = anchor.getAttribute("href") ?? "";
+ if (isGraphResourceUrl(url) && !refs.has(url)) {
+ const title = anchor.textContent.trim() || "attachment";
+ refs.set(url, { url, kind: "file", title, mime: anchor.getAttribute("data-mime") || "" });
+ }
+ }
+
+ const resources: DownloadedResource[] = [];
+ for (const ref of refs.values()) {
+ try {
+ const { content, contentType } = await graph.getResource(accessToken, ref.url);
+ resources.push({ ...ref, mime: ref.mime || contentType, content });
+ } catch (e: unknown) {
+ getLog().error(`OneNote import: could not download resource ${ref.url}: ${e instanceof Error ? e.message : e}`);
+ }
+ }
+ return resources;
+}
+
+/**
+ * Re-parses the converted page and swaps each downloaded Graph URL for a local Trilium reference:
+ * images become attachment-backed `<img src="api/attachments/…">`, file attachments become Trilium
+ * reference links. References whose download failed are left as-is.
+ */
+function rewritePageResources(note: BNote, html: string, resources: DownloadedResource[]): string {
+ const byUrl = new Map(resources.map((resource) => [resource.url, resource]));
+ const root = parse(html);
+
+ for (const img of root.querySelectorAll("img")) {
+ const resource = byUrl.get(img.getAttribute("src") ?? "");
+ if (!resource) {
+ continue;
+ }
+ const originalName = resource.title.includes(".") ? resource.title : `${resource.title}.${extensionForMime(resource.mime)}`;
+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, resource.content, originalName, false);
+ if (attachmentId) {
+ img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);
+ }
+ }
+
+ for (const anchor of root.querySelectorAll(`a.${ONENOTE_ATTACHMENT_CLASS}`)) {
+ const resource = byUrl.get(anchor.getAttribute("href") ?? "");
+ if (!resource) {
+ continue;
+ }
+ const attachment = note.saveAttachment({ role: "file", mime: resource.mime || "application/octet-stream", title: resource.title, content: resource.content });
+ anchor.setAttribute("class", "reference-link");
+ anchor.removeAttribute("data-mime");
+ anchor.setAttribute("href", `#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}`);
+ }
+
+ return root.toString();
+}
+
+function isGraphResourceUrl(url: string): boolean {
+ return url.startsWith("https://graph.microsoft.com/") && url.includes("/resources/");
+}
+
+/** Derives a file extension from a content type (e.g. `image/png` β†’ `png`, `image/svg+xml` β†’ `svg`). */
+function extensionForMime(mime: string): string {
+ return mime.split("/")[1]?.split("+")[0] || "png";
+}
+
export default { importSelection };
diff --git a/apps/server/src/services/import/onenote/inkml.spec.ts b/apps/server/src/services/import/onenote/inkml.spec.ts
new file mode 100644
index 0000000000..ecdbab42c5
--- /dev/null
+++ b/apps/server/src/services/import/onenote/inkml.spec.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from "vitest";
+
+import { parsePageContent } from "./graph.js";
+import { inkmlToSvg } from "./inkml.js";
+
+/** A minimal OneNote-style InkML document with one red brush and a multi-point trace. */
+const INKML = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">
+ <inkml:definitions>
+ <inkml:brush xml:id="br0">
+ <inkml:brushProperty name="color" value="#FF0000"/>
+ <inkml:brushProperty name="width" value="120"/>
+ <inkml:brushProperty name="transparency" value="0"/>
+ </inkml:brush>
+ </inkml:definitions>
+ <inkml:trace brushRef="#br0">100 100, 200 150, 300 100</inkml:trace>
+</inkml:ink>`;
+
+describe("inkmlToSvg", () => {
+ it("renders a trace as an SVG path using its brush color and width", () => {
+ const svg = inkmlToSvg(INKML);
+ expect(svg).toBeTruthy();
+ expect(svg).toContain("<svg");
+ expect(svg).toContain("viewBox=");
+ expect(svg).toContain("<path");
+ expect(svg).toContain(`stroke="#FF0000"`);
+ expect(svg).toContain(`stroke-width="120"`);
+ // The path should move to the first point and line to the rest.
+ expect(svg).toMatch(/d="M \d+ \d+ L \d+ \d+ L \d+ \d+"/);
+ });
+
+ it("caps the displayed size while keeping the true coordinate space in the viewBox", () => {
+ const svg = inkmlToSvg(INKML) ?? "";
+ const width = Number(svg.match(/width="(\d+)"/)?.[1]);
+ expect(width).toBeLessThanOrEqual(800);
+ // 300 - 100 + 2*padding(10) = 220 wide in coordinate units.
+ expect(svg).toContain("viewBox=\"0 0 220");
+ });
+
+ it("renders a single-point trace as a circle", () => {
+ const dot = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">
+ <inkml:trace>50 60</inkml:trace>
+ </inkml:ink>`;
+ const svg = inkmlToSvg(dot) ?? "";
+ expect(svg).toContain("<circle");
+ expect(svg).not.toContain("<path");
+ });
+
+ it("works without namespace prefixes and falls back to a default brush", () => {
+ const plain = `<ink><trace>0 0, 10 10</trace></ink>`;
+ const svg = inkmlToSvg(plain) ?? "";
+ expect(svg).toContain("<path");
+ expect(svg).toContain(`stroke="#000000"`);
+ });
+
+ it("returns null for empty input or ink with no traces", () => {
+ expect(inkmlToSvg("")).toBeNull();
+ expect(inkmlToSvg(" ")).toBeNull();
+ expect(inkmlToSvg(`<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML"></inkml:ink>`)).toBeNull();
+ });
+});
+
+describe("parsePageContent", () => {
+ it("splits a MIME multipart response into its HTML and InkML parts", () => {
+ const boundary = "--MIMEBoundary123";
+ const raw = [
+ boundary,
+ "Content-Type: text/html",
+ "",
+ "<html><body><p>Hello</p></body></html>",
+ boundary,
+ "Content-Type: application/inkml+xml",
+ "",
+ "<inkml:ink></inkml:ink>",
+ `${boundary}--`
+ ].join("\r\n");
+
+ const { html, inkml } = parsePageContent(raw);
+ expect(html).toBe("<html><body><p>Hello</p></body></html>");
+ expect(inkml).toBe("<inkml:ink></inkml:ink>");
+ });
+
+ it("returns a non-multipart response verbatim as the HTML part", () => {
+ const { html, inkml } = parsePageContent("<html><body><p>No ink here</p></body></html>");
+ expect(html).toBe("<html><body><p>No ink here</p></body></html>");
+ expect(inkml).toBe("");
+ });
+});
diff --git a/apps/server/src/services/import/onenote/inkml.ts b/apps/server/src/services/import/onenote/inkml.ts
new file mode 100644
index 0000000000..6cf5e0ae05
--- /dev/null
+++ b/apps/server/src/services/import/onenote/inkml.ts
@@ -0,0 +1,170 @@
+/**
+ * Converts OneNote InkML (handwriting / drawing strokes) into a single SVG image.
+ *
+ * OneNote returns a page's ink separately from its HTML (see graph.parsePageContent): the default
+ * HTML output drops the strokes, leaving only `<!-- InkNode is not supported -->` placeholders, while
+ * the actual strokes arrive as an InkML part when the page is fetched with `includeInkML=true`. We
+ * render those strokes to one SVG so they can be embedded as an inline image in the imported note.
+ *
+ * OneNote hands back all of a page's ink as a single positionless blob, so the SVG necessarily lands
+ * as one image (in reading order, after the page text) rather than overlaid at the strokes' original
+ * canvas coordinates β€” the same limitation Obsidian's importer has.
+ *
+ * Ported from Obsidian's MIT-licensed OneNote importer
+ * (https://github.com/obsidianmd/obsidian-importer β€” src/formats/onenote/inkml.ts), adapted to parse
+ * with node-html-parser (server-side) instead of the browser DOMParser, and to strip OneNote's XML
+ * namespace prefixes.
+ */
+
+import { HTMLElement, parse } from "node-html-parser";
+
+/** Padding around the rendered strokes, in coordinate units. */
+const PADDING = 10;
+
+/** Cap the SVG's displayed size so a high-resolution ink canvas doesn't render as a giant image. */
+const MAX_DISPLAY_SIZE = 800;
+
+interface Brush {
+ color: string;
+ width: number;
+ transparency: number;
+}
+
+interface Trace {
+ coords: number[][];
+ brush: Brush;
+}
+
+const DEFAULT_BRUSH: Brush = { color: "#000000", width: 70, transparency: 0 };
+
+export function inkmlToSvg(inkml: string): string | null {
+ if (!inkml || inkml.trim().length === 0) {
+ return null;
+ }
+
+ const root = parse(cleanInkml(stripNamespaces(inkml)), { lowerCaseTagName: true });
+ const brushes = parseBrushes(root);
+ const traces = parseTraces(root, brushes);
+ if (traces.length === 0) {
+ return null;
+ }
+
+ const { minX, minY, maxX, maxY } = boundingBox(traces);
+ if (!Number.isFinite(minX)) {
+ return null;
+ }
+
+ const width = maxX - minX + PADDING * 2;
+ const height = maxY - minY + PADDING * 2;
+ const scale = Math.min(1, MAX_DISPLAY_SIZE / Math.max(width, height, 1));
+
+ const shapes = traces.flatMap((trace) => traceToSvg(trace, minX, minY)).join("");
+ return (
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(width * scale)}" height="${Math.round(height * scale)}" ` +
+ `viewBox="0 0 ${width} ${height}">${shapes}</svg>`
+ );
+}
+
+/** Strips XML namespace prefixes from element names (`<inkml:trace>` β†’ `<trace>`) for plain-name querying. */
+function stripNamespaces(xml: string): string {
+ return xml.replace(/<(\/?)[a-zA-Z][\w.-]*:/g, "<$1");
+}
+
+/** Drops any trailing junk after the closing `</ink>` tag (the MIME split usually handles this already). */
+function cleanInkml(content: string): string {
+ const match = content.match(/<\/ink>/);
+ return match && match.index !== undefined ? content.slice(0, match.index + match[0].length) : content;
+}
+
+function parseBrushes(root: HTMLElement): Map<string, Brush> {
+ const brushes = new Map<string, Brush>();
+ for (const el of root.querySelectorAll("brush")) {
+ const id = el.getAttribute("xml:id") ?? el.getAttribute("id");
+ if (!id) {
+ continue;
+ }
+ const brush: Brush = { ...DEFAULT_BRUSH };
+ for (const prop of el.querySelectorAll("brushproperty")) {
+ const name = prop.getAttribute("name");
+ const value = prop.getAttribute("value");
+ if (!name || value == null) {
+ continue;
+ }
+ if (name === "color") {
+ brush.color = value;
+ } else if (name === "width") {
+ brush.width = Number.parseFloat(value) || brush.width;
+ } else if (name === "transparency") {
+ brush.transparency = Number.parseFloat(value) || 0;
+ }
+ }
+ brushes.set(id, brush);
+ }
+ return brushes;
+}
+
+function parseTraces(root: HTMLElement, brushes: Map<string, Brush>): Trace[] {
+ const traces: Trace[] = [];
+ for (const el of root.querySelectorAll("trace")) {
+ let ref = el.getAttribute("brushref") ?? "";
+ if (ref.startsWith("#")) {
+ ref = ref.slice(1);
+ }
+ const coords = parseCoords(el.textContent ?? "");
+ if (coords.length > 0) {
+ traces.push({ coords, brush: brushes.get(ref) ?? DEFAULT_BRUSH });
+ }
+ }
+ return traces;
+}
+
+/** Parses a trace's `x y` (comma-separated) coordinate list, scaling fractional values for precision. */
+function parseCoords(text: string): number[][] {
+ return text
+ .replace(/\n/g, "")
+ .split(",")
+ .map((coord) =>
+ coord
+ .trim()
+ .split(/\s+/)
+ .filter((part) => part.length > 0)
+ .map((axis) => {
+ const num = Number.parseFloat(axis);
+ return Number.isInteger(num) ? Math.round(num) : Math.round(num * 10000);
+ })
+ )
+ .filter((coord) => coord.length >= 2 && coord.every(Number.isFinite));
+}
+
+function boundingBox(traces: Trace[]): { minX: number; minY: number; maxX: number; maxY: number } {
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const trace of traces) {
+ for (const [x, y] of trace.coords) {
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ maxX = Math.max(maxX, x);
+ maxY = Math.max(maxY, y);
+ }
+ }
+ return { minX, minY, maxX, maxY };
+}
+
+function traceToSvg(trace: Trace, minX: number, minY: number): string[] {
+ const { color, width, transparency } = trace.brush;
+ const opacity = 1 - transparency;
+ const opacityAttr = opacity < 1 ? ` opacity="${opacity.toFixed(2)}"` : "";
+ const point = (coord: number[]) => [coord[0] - minX + PADDING, coord[1] - minY + PADDING];
+
+ if (trace.coords.length === 1) {
+ const [x, y] = point(trace.coords[0]);
+ return [`<circle cx="${x}" cy="${y}" r="${width / 2}" fill="${color}"${opacityAttr}/>`];
+ }
+
+ const path = trace.coords.map((coord, index) => `${index === 0 ? "M" : "L"} ${point(coord).join(" ")}`).join(" ");
+ return [`<path d="${path}" stroke="${color}" stroke-width="${width}" fill="none" stroke-linecap="round" stroke-linejoin="round"${opacityAttr}/>`];
+}
+
+export default { inkmlToSvg };