Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): resolve Notion page-to-page links

Elian Doran2736f9175c6b
diff --git a/packages/trilium-core/src/services/import/notion/converter.spec.ts b/packages/trilium-core/src/services/import/notion/converter.spec.ts
index 8f700f82e5..f638b872ea 100644
--- a/packages/trilium-core/src/services/import/notion/converter.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/converter.spec.ts
@@ -210,6 +210,15 @@ describe("convertNotionHtml — code blocks", () => {
});
});
+describe("convertNotionHtml — link-to-page blocks", () => {
+ it("unwraps a link-to-page figure into a paragraph link (href left for the importer to resolve)", () => {
+ const input = `<div style="display:contents" dir="ltr"><figure id="386c5eca" class="link-to-page"><a href="Formatting%20test/Subpage%20386c5eca1b8b802a90d8d891c7e62cd5.html">Subpage</a></figure></div>`;
+ expect(convertNotionHtml(input)).toBe(
+ `<p><a href="Formatting%20test/Subpage%20386c5eca1b8b802a90d8d891c7e62cd5.html">Subpage</a></p>`
+ );
+ });
+});
+
describe("convertNotionHtml — date mentions", () => {
it("strips the @ prefix Notion puts on inline <time> date mentions", () => {
expect(convertNotionHtml(`<p><time>@June 21, 2026</time></p>`)).toBe(`<p><time>June 21, 2026</time></p>`);
diff --git a/packages/trilium-core/src/services/import/notion/converter.ts b/packages/trilium-core/src/services/import/notion/converter.ts
index 1eb7ebc00b..11d3cd1893 100644
--- a/packages/trilium-core/src/services/import/notion/converter.ts
+++ b/packages/trilium-core/src/services/import/notion/converter.ts
@@ -24,6 +24,7 @@ export function convertNotionHtml(html: string): string {
convertCodeBlocks(root);
convertCallouts(root);
convertBookmarks(root);
+ convertLinkToPage(root);
return root.toString();
}
@@ -381,6 +382,24 @@ function convertBookmarks(root: HTMLElement) {
}
// #endregion
+// #region Link-to-page blocks
+/**
+ * Notion's "link to page" block is `<figure class="link-to-page"><a href="…page.html">Title</a></figure>`.
+ * Reduce it to a paragraph holding the link; the href still points at the target page's exported file,
+ * which the importer resolves to a Trilium internal/reference link once every page has a note.
+ */
+function convertLinkToPage(root: HTMLElement) {
+ for (const figure of root.querySelectorAll("figure.link-to-page")) {
+ const anchor = figure.querySelector("a");
+ if (!anchor) {
+ continue;
+ }
+ figure.insertAdjacentHTML("beforebegin", `<p>${anchor.toString()}</p>`);
+ figure.remove();
+ }
+}
+// #endregion
+
// #region Shared helpers
function isDisplayContents(node: HTMLElement): boolean {
return isTag(node, "div") && (node.getAttribute("style") ?? "").replace(/\s/g, "").includes("display:contents");
diff --git a/packages/trilium-core/src/services/import/notion/importer.spec.ts b/packages/trilium-core/src/services/import/notion/importer.spec.ts
index 3ae3e0eae2..7e52e704fa 100644
--- a/packages/trilium-core/src/services/import/notion/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { resolveResourcePath } from "./importer.js";
+import { type LinkTarget, resolveResourcePath, rewriteLinks } from "./importer.js";
describe("resolveResourcePath", () => {
it("resolves an image path relative to the page's directory in the zip", () => {
@@ -17,3 +17,30 @@ describe("resolveResourcePath", () => {
.toBe("a/c/img with space.png");
});
});
+
+describe("rewriteLinks", () => {
+ const resolveSubpage = (notionId: string): LinkTarget | null =>
+ notionId === "386c5eca1b8b802a90d8d891c7e62cd5" ? { noteId: "noteABC", title: "Subpage" } : null;
+
+ it("turns an internal page link whose text is the page title into a reference link", () => {
+ const input = `<p><a href="Formatting%20test/Subpage%20386c5eca1b8b802a90d8d891c7e62cd5.html">Subpage</a></p>`;
+ expect(rewriteLinks(input, resolveSubpage)).toBe(
+ `<p><a href="#root/noteABC" class="reference-link">Subpage</a></p>`
+ );
+ });
+
+ it("keeps a plain internal link (preserving custom text) when the text isn't the title", () => {
+ const input = `<p>See <a href="Subpage%20386c5eca1b8b802a90d8d891c7e62cd5.html">this page</a>.</p>`;
+ expect(rewriteLinks(input, resolveSubpage)).toBe(
+ `<p>See <a href="#root/noteABC">this page</a>.</p>`
+ );
+ });
+
+ it("leaves external links and unresolved internal links untouched", () => {
+ const external = `<p><a href="https://triliumnotes.org/">Trilium</a></p>`;
+ expect(rewriteLinks(external, resolveSubpage)).toBe(external);
+
+ const unknown = `<p><a href="Other%20ffffffffffffffffffffffffffffffff.html">Other</a></p>`;
+ expect(rewriteLinks(unknown, resolveSubpage)).toBe(unknown);
+ });
+});
diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
index b5e56b2529..ecc084ef93 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -117,8 +117,12 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<
rootNote.addLabel("iconClass", "bx bx-import");
const noteIdByPageId = new Map<string, string>();
+ const targetByPageId = new Map<string, LinkTarget>();
+ const created: { note: BNote; content: string; page: ParsedPage }[] = [];
const ordered = [...pages].sort((a, b) => a.parentIds.length - b.parentIds.length);
+ // First pass: create every note (so cross-page links can resolve in the second pass) and save its
+ // referenced images as attachments. Content is only rewritten/saved once, in the second pass.
for (const page of ordered) {
const parentPageId = page.parentIds[page.parentIds.length - 1];
const targetParentId = (parentPageId && noteIdByPageId.get(parentPageId)) || rootNote.noteId;
@@ -132,12 +136,19 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<
isProtected
});
noteIdByPageId.set(page.id, note.noteId);
+ targetByPageId.set(page.id, { noteId: note.noteId, title: page.title });
- // Save referenced images as attachments and point their <img> at them. Done after creation, since
- // attachments hang off the note; re-saves the content only when an image was actually rewritten.
- const rewritten = rewriteImages(note, page.content, page.path, resources);
- if (rewritten !== page.content) {
- note.setContent(rewritten);
+ // Attachments hang off the note, so this must run after creation; it returns the content with the
+ // <img> srcs pointing at the saved attachments.
+ created.push({ note, content: rewriteImages(note, page.content, page.path, resources), page });
+ taskContext.increaseProgressCount();
+ }
+
+ // Second pass: now that every page has a note, resolve cross-page links and persist the final content.
+ for (const { note, content, page } of created) {
+ const finalContent = rewriteLinks(content, (notionId) => targetByPageId.get(notionId) ?? null);
+ if (finalContent !== page.content) {
+ note.setContent(finalContent);
}
// Preserve Notion's original timestamps. Must run after the content save above, which would
@@ -145,8 +156,6 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<
if (page.utcDateCreated || page.utcDateModified) {
note.setDateCreatedAndModified(page.utcDateCreated, page.utcDateModified ?? page.utcDateCreated);
}
-
- taskContext.increaseProgressCount();
}
return rootNote;
@@ -181,6 +190,61 @@ function rewriteImages(note: BNote, content: string, pagePath: string, resources
return changed ? root.toString() : content;
}
+/** A resolved import target: the note created for a Notion page, plus that page's title. */
+export interface LinkTarget {
+ noteId: string;
+ title: string;
+}
+
+/**
+ * Resolves Notion page-to-page links. Notion exports an internal link as an `<a>` whose href points at
+ * the target page's exported HTML file (e.g. `Folder/Subpage 386c…cd5.html`), with the 32-hex Notion id
+ * embedded in the filename. Rewrites each link whose target was imported to `#root/<noteId>`; when the
+ * link text is the target page's title it becomes a Trilium reference link (the live-title chip),
+ * otherwise the original text is kept on a plain internal link. External/unresolved links are untouched.
+ */
+export function rewriteLinks(html: string, resolve: (notionId: string) => LinkTarget | null): string {
+ const root = parse(html);
+ let changed = false;
+
+ for (const anchor of root.querySelectorAll("a")) {
+ const notionId = internalPageId(anchor.getAttribute("href"));
+ if (!notionId) {
+ continue;
+ }
+ const target = resolve(notionId);
+ if (!target) {
+ continue;
+ }
+
+ anchor.setAttribute("href", `#root/${target.noteId}`);
+ if (anchor.textContent.trim() === target.title.trim()) {
+ anchor.setAttribute("class", "reference-link");
+ }
+ changed = true;
+ }
+
+ return changed ? root.toString() : html;
+}
+
+/** Extracts the target page's Notion id from an internal `.html` link href, or null if it isn't one. */
+function internalPageId(href: string | undefined): string | null {
+ if (!href) {
+ return null;
+ }
+ let decoded = href;
+ try {
+ decoded = decodeURIComponent(href);
+ } catch {
+ // Leave malformed percent-encoding as-is rather than throwing.
+ }
+ const path = decoded.split(/[?#]/)[0];
+ if (!path.toLowerCase().endsWith(".html")) {
+ return null;
+ }
+ return getNotionId(decoded) ?? null;
+}
+
/**
* Resolves an `<img src>` (zip-relative, percent-encoded) against the page's directory in the zip,
* returning a normalized path that matches the keys collected in {@link parseZip}.