Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/anytype): keep bookmarks as link-embed previews

Elian Doran355aada7fb38
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.ts
index 5e1e30afe6..d4f5df82d9 100644
--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts
@@ -251,6 +251,64 @@ describe("inline files", () => {
});
});
+describe("bookmarks", () => {
+ /** A bookmark block — Anytype's web-link card, carrying the target site's url/title/description inline. */
+ const bookmarkBlock = (id: string, bookmark: AnytypeBlock["bookmark"]): AnytypeBlock => ({ id, bookmark, childrenIds: [] });
+
+ it("renders a bookmark as a Trilium link-embed, keeping the title, description and favicon/preview file placeholders", () => {
+ const doc = listDoc(["b1"], [
+ bookmarkBlock("b1", {
+ url: "https://triliumnotes.org/",
+ title: "Trilium Notes",
+ description: "An open-source note-taking app.",
+ faviconHash: "favicon-cid",
+ imageHash: "preview-cid",
+ type: "Page",
+ targetObjectId: "bookmark-obj-cid",
+ state: "Done"
+ })
+ ]);
+ const result = parseObject(doc);
+ // The favicon/preview are emitted as raw file-id placeholders; the importer resolves them to data URIs.
+ expect(result.content).toBe(
+ '<section class="link-embed" data-url="https://triliumnotes.org/" data-embed-type="opengraph" data-title="Trilium Notes" data-description="An open-source note-taking app." data-favicon="favicon-cid" data-image="preview-cid"></section>'
+ );
+ // The favicon/preview file ids are surfaced so a collection-scoped export doesn't treat them as members.
+ expect(result.inlineFileIds).toEqual(["favicon-cid", "preview-cid"]);
+ });
+
+ it("omits the optional fields when the bookmark doesn't provide them", () => {
+ const doc = listDoc(["b1"], [bookmarkBlock("b1", { url: "https://example.com/", state: "Done" })]);
+ const result = parseObject(doc);
+ expect(result.content).toBe(
+ '<section class="link-embed" data-url="https://example.com/" data-embed-type="opengraph"></section>'
+ );
+ expect(result.inlineFileIds).toEqual([]);
+ });
+
+ it("escapes the url, title and description", () => {
+ const doc = listDoc(["b1"], [
+ bookmarkBlock("b1", { url: 'https://example.com/?a="1"&b=2', title: 'A & "B" <x>', description: "<script>" })
+ ]);
+ expect(parseObject(doc).content).toBe(
+ '<section class="link-embed" data-url="https://example.com/?a=&quot;1&quot;&amp;b=2" data-embed-type="opengraph" data-title="A &amp; &quot;B&quot; &lt;x&gt;" data-description="&lt;script&gt;"></section>'
+ );
+ });
+
+ it("drops a bookmark with no url (still resolving, or a broken card)", () => {
+ const doc = listDoc(["b1"], [bookmarkBlock("b1", { title: "No url yet", state: "Fetching" })]);
+ expect(parseObject(doc).content).toBe("");
+ });
+
+ it("does not record an internalLink for a bookmark (it is an external web link, not an imported note)", () => {
+ const doc = listDoc(["b1"], [bookmarkBlock("b1", { url: "https://example.com/", targetObjectId: "bookmark-obj-cid", state: "Done" })]);
+ const resolve: LinkResolver = () => ({ noteId: "n", title: "unexpected" });
+
+ const result = parseObject(doc, resolve);
+ expect(result.linkTargetIds).toEqual([]);
+ });
+});
+
describe("extractContent", () => {
it("returns empty output when the block tree has no resolvable root", () => {
expect(extractContent([], "missing", () => undefined)).toEqual({ html: "", linkTargetIds: [], fileTargetIds: [] });
diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.ts
index d7f59a8d89..a57890ac3a 100644
--- a/packages/trilium-core/src/services/import/anytype/content.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.ts
@@ -4,8 +4,9 @@
* An object's `snapshot.data.blocks` is a flat list joined into a tree by each block's `childrenIds`.
* {@link extractContent} walks that tree from the root in document order and converts each block to HTML —
* headings (`<h2>`/`<h3>`/`<h4>`), bullet/numbered/task lists (grouped and nested), toggles, callouts,
- * quotes, dividers, tables ({@link renderTable}), Mermaid diagrams / LaTeX math ({@link renderLatexBlock})
- * and cross-page reference links — applying inline marks ({@link renderInlineText}) and rendering code
+ * quotes, dividers, tables ({@link renderTable}), Mermaid diagrams / LaTeX math ({@link renderLatexBlock}),
+ * bookmark cards ({@link renderBookmark} → link-embed previews) and cross-page reference links — applying
+ * inline marks ({@link renderInlineText}) and rendering code
* blocks ({@link renderCodeBlock}). It returns the HTML plus the Trilium ids of every linked-to page (for
* the `internalLink` relations). The structure importer (importer.ts) owns object selection and the note
* tree; it calls into here. Mirrors the Notion importer's `converter.ts`.
@@ -114,6 +115,21 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLi
return `<p><a class="reference-link" href="#root/${target.noteId}">${escapeHtml(target.title)}</a></p>`;
}
+ // A bookmark block — Anytype's web-link card. It becomes a Trilium link-embed (open-graph preview),
+ // the same markup the Notion importer produces for its bookmark cards. The card's url/title/description
+ // are carried inline; its favicon/preview are content-addressed file CIDs, emitted as placeholders the
+ // importer resolves to inline `data:` URIs (how Trilium natively stores a link-embed favicon/image).
+ // Those file ids are surfaced (like an inline image's) so a collection-scoped export doesn't mistake
+ // them for stray members. A card still missing its url is dropped.
+ if (block.bookmark) {
+ for (const hash of [block.bookmark.faviconHash, block.bookmark.imageHash]) {
+ if (hash) {
+ fileTargetIds.add(hash);
+ }
+ }
+ return renderBookmark(block.bookmark);
+ }
+
// A file/media block — an embedded image or attached file (PDF, audio, …). The placeholder carries
// the linked FileObject's id in the `src`/`href`; the importer resolves it to a saved attachment
// once the note (and thus the attachment) exists — an inline image for an Image, a reference link
@@ -419,6 +435,44 @@ function paletteValue(covering: AppliedMark[], type: string, palette: Record<str
}
// #endregion
+// #region Bookmarks
+/**
+ * Renders an Anytype bookmark block as a Trilium link-embed (`<section class="link-embed" …>`), the same
+ * open-graph-preview markup the Notion importer produces and CKEditor's LinkEmbed plugin round-trips. The
+ * card's `url`, `title` and `description` map to `data-url` / `data-title` / `data-description`. The
+ * favicon/preview are content-addressed file CIDs (`faviconHash`/`imageHash`), emitted as-is in
+ * `data-favicon` / `data-image` as placeholders — the importer resolves each to an inline base64 `data:` URI
+ * (the form Trilium natively stores a link-embed favicon/image in), or drops the attribute when the export
+ * has no bytes for it. Optional fields are only written when present. A card with no url (still fetching, or
+ * a broken export) is dropped.
+ */
+export function renderBookmark(bookmark: NonNullable<AnytypeBlock["bookmark"]>): string {
+ const url = (bookmark.url ?? "").trim();
+ if (!url) {
+ return "";
+ }
+
+ let attrs = `data-url="${escapeHtml(url)}" data-embed-type="opengraph"`;
+ const title = (bookmark.title ?? "").trim();
+ if (title) {
+ attrs += ` data-title="${escapeHtml(title)}"`;
+ }
+ const description = (bookmark.description ?? "").trim();
+ if (description) {
+ attrs += ` data-description="${escapeHtml(description)}"`;
+ }
+ const favicon = (bookmark.faviconHash ?? "").trim();
+ if (favicon) {
+ attrs += ` data-favicon="${escapeHtml(favicon)}"`;
+ }
+ const image = (bookmark.imageHash ?? "").trim();
+ if (image) {
+ attrs += ` data-image="${escapeHtml(image)}"`;
+ }
+ return `<section class="link-embed" ${attrs}></section>`;
+}
+// #endregion
+
// #region Code blocks
// PrismJS language ids Anytype uses that don't line up with a Trilium markdown language code. Most ids
// (javascript, python, go, rust, …) match directly; only the mismatches need listing here. `clike` is
diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts
index e77ca7ac46..4785d3527e 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts
@@ -132,6 +132,74 @@ describe("Anytype importer — integration", () => {
expect(decodeUtf8(first?.getContent() ?? "")).toBe("<p>Hello world</p><p>Second paragraph</p>");
});
+ it("keeps a bookmark block as a link-embed, inlining its favicon as a base64 data URI", async () => {
+ // A page holding a bookmark card. The card's target is a separate `ot-bookmark` object (a non-page
+ // layout, so not imported); the card carries the url/title/description and a favicon file id (resolved
+ // from the export's filesObjects/files to an inline data URI, how Trilium natively stores a favicon).
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "page1", childrenIds: ["header", "bm"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "bm", bookmark: { url: "https://triliumnotes.org/", title: "Trilium Notes", description: "An open-source note-taking app.", faviconHash: "fav-cid", type: "Page", targetObjectId: "bookmark-obj", state: "Done" } }
+ ],
+ details: { id: "page1", name: "Links", resolvedLayout: 0 },
+ objectTypes: ["ot-page"]
+ }
+ }
+ });
+ // The `ot-bookmark` object the card mirrors — layout 11, so it must NOT be imported as a page.
+ const bookmarkObject = JSON.stringify({
+ sbType: "Page",
+ snapshot: { data: { blocks: [{ id: "bookmark-obj", childrenIds: [] }], details: { id: "bookmark-obj", name: "Trilium Notes", resolvedLayout: 11, source: "https://triliumnotes.org/" }, objectTypes: ["ot-bookmark"] } }
+ });
+ const faviconBytes = Buffer.from([0x00, 0x01, 0x02, 0x03]);
+
+ const importRoot = await importAnytype({
+ "objects/page1.pb.json": page,
+ "objects/bookmark.pb.json": bookmarkObject,
+ "filesObjects/fav.pb.json": fileObjectJson("fav-cid", "triliumnotes_org_icon", "ico", "image/x-icon", "files\\triliumnotes_org_icon.ico"),
+ "files/triliumnotes_org_icon.ico": faviconBytes
+ });
+
+ const children = importRoot.getChildNotes();
+ expect(children.map((note) => note.title)).toEqual(["Links"]);
+ // The favicon file id has been resolved to an inline data URI (mime derived from the .ico name).
+ expect(decodeUtf8(children[0]?.getContent() ?? "")).toBe(
+ `<section class="link-embed" data-url="https://triliumnotes.org/" data-embed-type="opengraph" data-title="Trilium Notes" data-description="An open-source note-taking app." data-favicon="data:image/vnd.microsoft.icon;base64,${faviconBytes.toString("base64")}"></section>`
+ );
+ });
+
+ it("drops a bookmark's favicon placeholder when the export has no bytes for it", async () => {
+ // The card references a favicon file id, but no filesObjects/files entry backs it — the importer drops
+ // the data-favicon attribute rather than leaving a bare id that would render as a broken image.
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "page1", childrenIds: ["header", "bm"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "bm", bookmark: { url: "https://example.com/", title: "Example", faviconHash: "missing-cid", state: "Done" } }
+ ],
+ details: { id: "page1", name: "Links", resolvedLayout: 0 },
+ objectTypes: ["ot-page"]
+ }
+ }
+ });
+
+ const importRoot = await importAnytype({ "objects/page1.pb.json": page });
+
+ const children = importRoot.getChildNotes();
+ expect(decodeUtf8(children[0]?.getContent() ?? "")).toBe(
+ '<section class="link-embed" data-url="https://example.com/" data-embed-type="opengraph" data-title="Example"></section>'
+ );
+ });
+
it("imports only pages, skipping sets, system objects and the relations/types folders", async () => {
const importRoot = await importAnytype({
"objects/page1.pb.json": pageObject("page1", "Real Page", ["content"]),
diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.ts
index 0e0154f5b7..b87129da54 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.ts
@@ -7,7 +7,8 @@
* headings, inline marks (bold/italic/strikethrough/underline/inline-code and text/background colours),
* code blocks (with the language preserved as the Trilium MIME), bullet/numbered/task lists (grouped and
* nested), toggles (normal toggles → collapsible blocks; toggle headings → plain headings), callouts
- * (→ admonitions), quotes/highlights (→ `<blockquote>`), dividers (→ `<hr>`), inline file/media blocks
+ * (→ admonitions), quotes/highlights (→ `<blockquote>`), dividers (→ `<hr>`), bookmark cards (Anytype's
+ * web-link card → a Trilium link-embed / open-graph preview), inline file/media blocks
* (an embedded image → an inline `role:"image"` attachment; any other attached file → a `role:"file"`
* attachment reference link, the bytes resolved from the export's `filesObjects/` metadata + `files/`
* bytes) and cross-page links (Anytype's block-level "link to object" → a Trilium reference link plus an
@@ -34,7 +35,7 @@ import imageService from "../../image.js";
import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import type TaskContext from "../../task_context.js";
-import { decodeUtf8 } from "../../utils/binary.js";
+import { decodeUtf8, encodeBase64 } from "../../utils/binary.js";
import date_utils from "../../utils/date.js";
import { newEntityId } from "../../utils/index.js";
import { basename } from "../../utils/path.js";
@@ -452,22 +453,44 @@ function createFileMemberNote(parentNoteId: string, info: FileObjectInfo, bytes:
/**
* Resolves the inline file/media placeholders a page's body carries ({@link ./content.js} emits each
* `file` block as an `<img>` / `<a class="anytype-file">` whose `src`/`href` is the linked `FileObject`'s
- * id). For each one it looks the id up in the export's file metadata and bytes, then saves the bytes as an
- * attachment and rewrites the reference to point at it — an inline `role:"image"` for an image, a
- * `role:"file"` attachment reference-link for any other file type (matching the Notion importer). A
- * placeholder whose file is missing from the export (no metadata or bytes — e.g. a still-uploading file) is
- * dropped (image) or left as plain text (other). Only re-saves the content when something changed.
+ * id, and each bookmark card's favicon/preview as a `data-favicon` / `data-image` file id on its
+ * `section.link-embed`). For a file placeholder it looks the id up in the export's file metadata and bytes,
+ * then saves the bytes as an attachment and rewrites the reference to point at it — an inline `role:"image"`
+ * for an image, a `role:"file"` attachment reference-link for any other file type (matching the Notion
+ * importer). A bookmark's favicon/preview id is instead resolved to an inline base64 `data:` URI (the form
+ * Trilium natively stores a link-embed favicon/image in), never an attachment. A placeholder whose file is
+ * missing from the export (no metadata or bytes — e.g. a still-uploading file) is dropped (image /
+ * favicon / preview) or left as plain text (other file). Only re-saves the content when something changed.
*/
function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, shrinkImages: boolean) {
const content = decodeUtf8(note.getContent());
// Cheap guard: parse only when the body actually holds a placeholder to resolve.
- if (!content.includes("<img") && !content.includes('class="anytype-file"')) {
+ if (!content.includes("<img") && !content.includes('class="anytype-file"') && !content.includes("link-embed")) {
return;
}
const root = parse(content);
let changed = false;
+ // A bookmark card's favicon/preview: resolve each file-id placeholder to an inline base64 data URI, or
+ // drop the attribute when the export has no bytes for it (rather than leaving a bare id that renders as a
+ // broken image; the client already falls back to a placeholder when the attribute is absent).
+ for (const section of root.querySelectorAll("section.link-embed")) {
+ for (const attr of ["data-favicon", "data-image"]) {
+ const targetId = section.getAttribute(attr);
+ if (!targetId) {
+ continue;
+ }
+ const dataUri = inlineFileDataUri(targetId, fileObjects, files);
+ if (dataUri) {
+ section.setAttribute(attr, dataUri);
+ } else {
+ section.removeAttribute(attr);
+ }
+ changed = true;
+ }
+ }
+
for (const img of root.querySelectorAll("img")) {
const targetId = img.getAttribute("src");
const bytes = targetId ? inlineFileBytes(targetId, fileObjects, files) : undefined;
@@ -527,6 +550,17 @@ function inlineFileBytes(targetId: string, fileObjects: Map<string, FileObjectIn
return info ? files.get(normalizePath(info.source)) : undefined;
}
+/** A file id resolved to an inline `data:<mime>;base64,<bytes>` URI (for a bookmark card's favicon/preview,
+ * stored inline rather than as an attachment), or undefined when the export has no bytes for it. */
+function inlineFileDataUri(targetId: string, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>): string | undefined {
+ const bytes = inlineFileBytes(targetId, fileObjects, files);
+ if (!bytes) {
+ return undefined;
+ }
+ const mime = fileObjects.get(targetId)?.mime || "application/octet-stream";
+ return `data:${mime};base64,${encodeBase64(bytes)}`;
+}
+
/**
* Restores a page's original timestamps (note creation stamps "modified" — and the blob — with now). A
* date-less page is left untouched, keeping its import-time dates. When only one date is present we fall back
diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.ts
index d31369efeb..d4baab2326 100644
--- a/packages/trilium-core/src/services/import/anytype/model.ts
+++ b/packages/trilium-core/src/services/import/anytype/model.ts
@@ -36,9 +36,10 @@ export interface AnytypeText {
iconEmoji?: string;
}
-/** A single block in an object's `snapshot.data.blocks`. Non-text blocks (dividers, dataviews, …) carry
- * other keys this importer doesn't read yet; only `id`, `childrenIds`, `text`, `div`, `link` and (for code
- * blocks) `fields.lang` are needed to pull out the page's content in document order. */
+/** A single block in an object's `snapshot.data.blocks`. Non-text blocks (dataviews, …) carry other keys
+ * this importer doesn't read yet; only `id`, `childrenIds`, `text`, `div`, `link`, `file`, `latex`,
+ * `bookmark`, `table`/`tableRow` and (for code blocks) `fields.lang` are needed to pull out the page's
+ * content in document order. */
export interface AnytypeBlock {
id: string;
childrenIds?: string[];
@@ -76,6 +77,22 @@ export interface AnytypeBlock {
text?: string;
processor?: string;
};
+ /** A "bookmark" block — Anytype's web-link card. It carries the target site's `url`, `title` and
+ * `description` inline (fetched by Anytype when the card was created); `faviconHash`/`imageHash` are the
+ * CIDs of the fetched icon/preview `FileObject`s (content-addressed, not URLs — the importer resolves them
+ * to inline base64 `data:` URIs), and `targetObjectId` is the separate `ot-bookmark` object the card
+ * mirrors (a non-page layout, so not imported). Rendered as a Trilium link-embed (open-graph preview),
+ * like the Notion importer's bookmark cards. */
+ bookmark?: {
+ url?: string;
+ title?: string;
+ description?: string;
+ imageHash?: string;
+ faviconHash?: string;
+ type?: string;
+ targetObjectId?: string;
+ state?: string;
+ };
/** A table block (an empty marker object). Its two children are a `TableColumns` and a `TableRows`
* layout block; each row's cells are text blocks whose id is `${rowId}-${columnId}`. */
table?: Record<string, unknown>;