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): resolve Anytype inline reference links (mentions)
Elian Doran0f1567600e53
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.tsindex 57e09d5673..d11e13aaa2 100644--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts@@ -323,6 +323,44 @@ describe("renderInlineText", () => {});});+describe("inline mentions", () => {+ /** A resolver that maps any non-"missing" id to a note, so a Mention resolves unless it's "missing". */+ const resolve: LinkResolver = (cid) => (cid === "missing" ? undefined : { noteId: `note-${cid}`, title: `Title ${cid}` });++ it("wraps a resolved Mention span in a reference link and reports the target via onLink", () => {+ const linked: string[] = [];+ const html = renderInlineText("see X here", [mark(4, 5, "Mention", "abc")], resolve, (id) => linked.push(id));+ expect(html).toBe('see <a class="reference-link" href="#root/note-abc">X</a> here');+ expect(linked).toEqual(["note-abc"]);+ });++ it("leaves a Mention as plain text when its target wasn't imported, recording no link", () => {+ const linked: string[] = [];+ const html = renderInlineText("see X here", [mark(4, 5, "Mention", "missing")], resolve, (id) => linked.push(id));+ expect(html).toBe("see X here");+ expect(linked).toEqual([]);+ });++ it("leaves a Mention plain when no resolver is supplied (parsing in isolation)", () => {+ expect(renderInlineText("see X", [mark(4, 5, "Mention", "abc")])).toBe("see X");+ });++ it("nests structural marks inside the mention anchor (anchor outermost)", () => {+ const html = renderInlineText("bold link", [mark(5, 9, "Mention", "abc"), mark(5, 9, "Bold")], resolve);+ expect(html).toBe('bold <a class="reference-link" href="#root/note-abc"><strong>link</strong></a>');+ });++ it("renders two mentions in one line, each its own reference link", () => {+ // Mirrors the "Page with block and inline reference links" page: two mentions over one paragraph.+ const linked: string[] = [];+ const html = renderInlineText("Inline link: 2 Untitled ", [mark(13, 14, "Mention", "two"), mark(16, 24, "Mention", "one")], resolve, (id) => linked.push(id));+ expect(html).toBe(+ 'Inline link: <a class="reference-link" href="#root/note-two">2</a> <a class="reference-link" href="#root/note-one">Untitled</a> '+ );+ expect(linked).toEqual(["note-two", "note-one"]);+ });+});+describe("renderCodeBlock", () => {it("wraps code in <pre><code> with the resolved language class", () => {// Anytype tags C-family code as PrismJS "clike"; Trilium has no such code, so it's aliased to C.diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.tsindex a72e6fd57d..20f5204606 100644--- a/packages/trilium-core/src/services/import/anytype/content.ts+++ b/packages/trilium-core/src/services/import/anytype/content.ts@@ -38,6 +38,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLiconst visited = new Set<string>();const linkTargetIds = new Set<string>();+ const addLink = (noteId: string) => linkTargetIds.add(noteId);// Renders a run of sibling ids, grouping consecutive same-kind list items into one list. The header// chrome and already-visited blocks (a node reachable twice) are skipped.@@ -83,7 +84,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLi}function renderItem(kind: ListKind, item: AnytypeBlock): string {- const text = renderInlineText(item.text?.text ?? "", item.text?.marks?.marks ?? []);+ const text = renderInlineText(item.text?.text ?? "", item.text?.marks?.marks ?? [], resolveLink, addLink);const nested = renderSequence(item.childrenIds ?? []);if (kind === "task") {// CKEditor's read-only todo-list markup (matches the markdown importer's checkbox output).@@ -134,7 +135,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLi// A table block: render its columns/rows/cells subtree directly. Returning here skips the generic// child walk below, which would otherwise emit every cell's text as a stray paragraph after the table.if (block.table) {- return renderTable(block, byId);+ return renderTable(block, byId, resolveLink, addLink);}// Use the raw text (not trimmed) so mark offsets stay aligned; only the emptiness test trims.@@ -145,12 +146,12 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLiif (style === "Toggle") {// A normal toggle becomes a Trilium collapsible block: its label is the summary, its children// the collapsed body. (Toggle *headings* fall through to a normal heading below, via tagForStyle.)- return `<details class="trilium-collapsible"><summary>${renderInlineText(rawText, marks)}</summary>${renderSequence(block.childrenIds ?? [])}</details>`;+ return `<details class="trilium-collapsible"><summary>${renderInlineText(rawText, marks, resolveLink, addLink)}</summary>${renderSequence(block.childrenIds ?? [])}</details>`;}if (style === "Quote") {// Anytype's Highlight block (internal style "Quote") → a blockquote; its background tint is dropped.- const firstPara = rawText.trim() ? `<p>${renderInlineText(rawText, marks)}</p>` : "";+ const firstPara = rawText.trim() ? `<p>${renderInlineText(rawText, marks, resolveLink, addLink)}</p>` : "";return `<blockquote>${firstPara}${renderSequence(block.childrenIds ?? [])}</blockquote>`;}@@ -162,7 +163,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLiconst type = emoji ? "note" : "tip";// Escape the emoji like every other piece of user text here — it's interpolated raw into the// markup, so an export carrying markup in this field would otherwise inject it.- const lead = [escapeHtml(emoji), renderInlineText(rawText, marks)].filter(Boolean).join(" ");+ const lead = [escapeHtml(emoji), renderInlineText(rawText, marks, resolveLink, addLink)].filter(Boolean).join(" ");const firstPara = lead ? `<p>${lead}</p>` : "";return `<aside class="admonition ${type}">${firstPara}${renderSequence(block.childrenIds ?? [])}</aside>`;}@@ -174,7 +175,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLihtml = renderCodeBlock(rawText, block.fields?.lang);} else {const tag = tagForStyle(style);- html = `<${tag}>${renderInlineText(rawText, marks)}</${tag}>`;+ html = `<${tag}>${renderInlineText(rawText, marks, resolveLink, addLink)}</${tag}>`;}}// A non-list block's children (e.g. a toggle heading's collapsed content) follow as flattened siblings.@@ -258,6 +259,8 @@ interface AppliedMark {param: string;from: number;to: number;+ /** For a resolved `Mention`, the reference-link href (`#root/<noteId>`) its span wraps. */+ href?: string;}/**@@ -266,24 +269,38 @@ interface AppliedMark {* into valid nested HTML by splitting the text at every mark boundary, so no segment straddles a mark edge,* then wrapping each segment in the tags whose range fully covers it. Adjacent segments always differ in* their active set (a boundary is only created where a mark starts or ends), so output is clean without a- * merge pass. Links, mentions and emoji are ignored, leaving their text as plain (escaped) content.+ * merge pass. An inline `Mention` (a link to another object, its target id in `param`) becomes a Trilium+ * reference link around its span when `resolveLink` maps the target to an imported note — and the note id is+ * surfaced via `onLink` so the caller records the `internalLink` relation; an unresolved mention (or no+ * resolver — parsing in isolation) leaves the text plain. Emoji are ignored, leaving their text as plain+ * (escaped) content.*/-export function renderInlineText(text: string, marks: AnytypeMark[]): string {+export function renderInlineText(text: string, marks: AnytypeMark[], resolveLink?: LinkResolver, onLink?: (noteId: string) => void): string {const length = text.length;- // Keep only marks we render (known structural kind, or a known colour name), with offsets clamped to- // the text and empty/reversed ranges dropped.+ // Keep only marks we render (known structural kind, a known colour name, or a resolvable mention link),+ // with offsets clamped to the text and empty/reversed ranges dropped.const applicable: AppliedMark[] = [];for (const mark of marks) {const param = mark.param ?? "";- if (mark.type === undefined || !isRenderable(mark.type, param)) {- continue;- }const from = Math.max(0, Math.min(length, mark.range?.from ?? 0));const to = Math.max(0, Math.min(length, mark.range?.to ?? 0));- if (from < to) {- applicable.push({ type: mark.type, param, from, to });+ if (from >= to) {+ continue;+ }+ if (mark.type === "Mention") {+ // An inline link to another object → a reference link, when its target was imported.+ const target = param && resolveLink ? resolveLink(param) : undefined;+ if (target) {+ applicable.push({ type: "Mention", param, from, to, href: `#root/${target.noteId}` });+ onLink?.(target.noteId);+ }+ continue;+ }+ if (mark.type === undefined || !isRenderable(mark.type, param)) {+ continue;}+ applicable.push({ type: mark.type, param, from, to });}if (applicable.length === 0) {@@ -326,7 +343,8 @@ function isRenderable(type: string, param: string): boolean {/*** Wraps one segment in the tags of the marks that fully cover it. Text and background colour fold into a* single innermost `<span>` (a highlight without a text colour gets the default dark text); the structural- * marks then nest around it, Bold outermost per {@link MARK_ORDER}.+ * marks then nest around it, Bold outermost per {@link MARK_ORDER}; a covering mention link wraps the whole+ * thing as the outermost reference-link anchor.*/function wrapSegment(segment: string, covering: AppliedMark[]): string {const textColor = paletteValue(covering, "TextColor", TEXT_COLORS);@@ -349,6 +367,11 @@ function wrapSegment(segment: string, covering: AppliedMark[]): string {html = `<${tag}>${html}</${tag}>`;}+ const mention = covering.find((mark) => mark.type === "Mention");+ if (mention?.href) {+ html = `<a class="reference-link" href="${mention.href}">${html}</a>`;+ }+return html;}@@ -417,8 +440,10 @@ export function renderLatexBlock(text: string, processor: string | undefined): s* order and, for each row, place that column's cell (blank when absent) so the grid stays aligned. A row* flagged `isHeader` becomes `<th scope="col">` in a `<thead>`; the rest are `<td>` in the `<tbody>`. The* table is wrapped in `<figure class="table">`, the shape CKEditor stores (mirroring the Notion importer).+ * `resolveLink`/`onLink` are passed through to cell text so an inline mention in a cell becomes a reference+ * link (and records its `internalLink`), like anywhere else.*/-export function renderTable(table: AnytypeBlock, byId: Map<string, AnytypeBlock>): string {+export function renderTable(table: AnytypeBlock, byId: Map<string, AnytypeBlock>, resolveLink?: LinkResolver, onLink?: (noteId: string) => void): string {const [colsLayoutId, rowsLayoutId] = table.childrenIds ?? [];const columnIds = (colsLayoutId ? byId.get(colsLayoutId)?.childrenIds : undefined) ?? [];const rowIds = (rowsLayoutId ? byId.get(rowsLayoutId)?.childrenIds : undefined) ?? [];@@ -447,7 +472,7 @@ export function renderTable(table: AnytypeBlock, byId: Map<string, AnytypeBlock>const cells = columnIds.map((columnId) => {const cell = cellByColumn.get(columnId);- const content = cell ? renderInlineText(cell.text?.text ?? "", cell.text?.marks?.marks ?? []) : "";+ const content = cell ? renderInlineText(cell.text?.text ?? "", cell.text?.marks?.marks ?? [], resolveLink, onLink) : "";return `<${tag}${scope}>${content}</${tag}>`;}).join("");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.tsindex 30ab52c491..44b9d2c890 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@@ -514,6 +514,45 @@ describe("Anytype importer — integration", () => {expect(note?.getRelations().filter((r) => r.name === "internalLink")).toHaveLength(0);});+ it("renders an inline mention as a reference link and records an internalLink relation for backlinks", async () => {+ // "Source" mentions "Target" inline via a Mention mark (the target object's id in `param`), mirroring+ // the "Page with block and inline reference links" page.+ const source = JSON.stringify({+ sbType: "Page",+ snapshot: {+ data: {+ blocks: [+ { id: "src", childrenIds: ["header", "src-p"] },+ { id: "header", childrenIds: ["title"] },+ { id: "title", text: { text: "", style: "Title" } },+ { id: "src-p", text: { text: "Inline link: Target here", style: "Paragraph", marks: { marks: [{ range: { from: 13, to: 19 }, type: "Mention", param: "tgt" }] } } }+ ],+ details: { id: "src", name: "Source", resolvedLayout: 0 }+ }+ }+ });+ const target = pageObject("tgt", "Target", ["I am linked"]);++ const importRoot = await importAnytype({+ "objects/source.pb.json": source,+ "objects/target.pb.json": target+ });++ const sourceNote = importRoot.getChildNotes().find((n) => n.title === "Source");+ const targetNote = importRoot.getChildNotes().find((n) => n.title === "Target");+ expect(sourceNote).toBeDefined();+ expect(targetNote).toBeDefined();++ // The mention span becomes an inline reference link to the target note, the surrounding text intact.+ expect(decodeUtf8(sourceNote?.getContent() ?? "")).toBe(`<p>Inline link: <a class="reference-link" href="#root/${targetNote?.noteId}">Target</a> here</p>`);++ // ...and drives backlink detection just like a block-level link.+ const internalLinks = sourceNote?.getRelations().filter((r) => r.name === "internalLink") ?? [];+ expect(internalLinks.map((r) => r.value)).toEqual([targetNote?.noteId]);+ const backlinks = targetNote?.getTargetRelations().filter((r) => r.name === "internalLink") ?? [];+ expect(backlinks.map((r) => r.noteId)).toEqual([sourceNote?.noteId]);+ });+it("preserves a page's created and modified dates from Anytype's detail timestamps", async () => {const page = JSON.stringify({sbType: "Page",diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.tsindex 9bae775c46..dcbbc13dbd 100644--- a/packages/trilium-core/src/services/import/anytype/model.ts+++ b/packages/trilium-core/src/services/import/anytype/model.ts@@ -14,8 +14,8 @@ export interface AnytypeMarkRange {}/** An inline formatting span over a text block's `text`. `type` is the kind (Bold, Italic, Strikethrough,- * Underscored, Keyboard, TextColor, …); `param` carries extra data for some kinds (a colour name, a link- * URL). Marks may overlap freely and are not pre-sorted. */+ * Underscored, Keyboard, TextColor, Mention, …); `param` carries extra data for some kinds (a colour name, a+ * link URL, or — for a `Mention` — the linked object's id). Marks may overlap freely and are not pre-sorted. */export interface AnytypeMark {range?: AnytypeMarkRange;type?: string;