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
fix/link previews: don't drop them on Markdown export
Elian Dorana10899319fe4
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.tsindex 3ae493a773..160123f4f6 100644--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts@@ -279,6 +279,38 @@ describe("LinkEmbed", () => {expect(data).not.toContain("data-site-name");});+ it("upcasts link previews carrying the Markdown-export fallback anchor, dropping the anchor", () => {+ // The Markdown exporter injects an <a> child into the otherwise empty elements so the+ // export stays readable outside Trilium; on reimport the anchor must vanish into the+ // widget instead of leaking as stray text.+ editor.setData(+ '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="T">' ++ '<a href="https://e.com/">T</a></section>' ++ '<p>See <span class="link-mention" data-url="https://e.com/" data-title="T">' ++ '<a href="https://e.com/">T</a></span> for details.</p>'+ );++ const root = editor.model.document.getRoot();+ expect(root?.childCount).toBe(2);++ const embed = root?.getChild(0);+ expect(embed?.is("element", "linkEmbed")).toBe(true);+ if (embed?.is("element")) {+ expect(embed.getAttribute("url")).toBe("https://e.com/");+ expect(embed.childCount).toBe(0);+ }++ const paragraph = root?.getChild(1);+ const mention = paragraph?.is("element") ? paragraph.getChild(1) : undefined;+ expect(mention?.is("element", "linkMention")).toBe(true);++ // Saving again produces the canonical childless elements — the anchor does not survive,+ // let alone accumulate.+ const data = editor.getData();+ expect(data).not.toContain("<a");+ expect(data).toContain('data-url="https://e.com/"');+ });+it("editing-downcasts a linkMention to an inline widget and renders it via the component", () => {setModelData(editor.model,diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex 36e4eb400f..8b57629d12 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -65,6 +65,61 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("exports link previews as raw HTML with a fallback anchor", () => {+ // Block card/embed: kept as a section (the importer + editor upcast round-trip it), with a+ // fallback link inside so external Markdown renderers show something instead of nothing.+ expect(markdownExportService.toMarkdown(+ '<p>before</p>' ++ '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="Example"></section>' ++ '<p>after</p>'+ )).toBe(+ 'before\n\n' ++ '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="Example"><a href="https://e.com/">Example</a></section>' ++ '\n\nafter'+ );++ // Video embeds share the same element; without a title the URL doubles as the link text.+ expect(markdownExportService.toMarkdown(+ '<section class="link-embed" data-url="https://www.youtube.com/watch?v=abc" data-embed-type="youtube"></section>'+ )).toBe(+ '<section class="link-embed" data-url="https://www.youtube.com/watch?v=abc" data-embed-type="youtube">' ++ '<a href="https://www.youtube.com/watch?v=abc">https://www.youtube.com/watch?v=abc</a></section>'+ );++ // Inline mention: stays inline within the sentence.+ expect(markdownExportService.toMarkdown(+ '<p>See <span class="link-mention" data-url="https://e.com/" data-title="Example"></span> for details.</p>'+ )).toBe(+ 'See <span class="link-mention" data-url="https://e.com/" data-title="Example"><a href="https://e.com/">Example</a></span> for details.'+ );+ });++ it("replaces an existing link preview fallback anchor instead of accumulating it", () => {+ // Content imported from Markdown (and never re-saved by the editor) already carries the+ // fallback anchor, so the element is non-blank and goes through the rule instead of+ // blankReplacement. The anchor is regenerated from the (possibly edited) data attributes.+ const exported = markdownExportService.toMarkdown(+ '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="New title">' ++ '<a href="https://e.com/">Stale title</a></section>'+ );++ expect(exported).toBe(+ '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="New title">' ++ '<a href="https://e.com/">New title</a></section>'+ );+ });++ it("escapes HTML in link preview fallback anchors", () => {+ const exported = markdownExportService.toMarkdown(+ '<section class="link-embed" data-url="https://e.com/?a=1&b=2" data-embed-type="opengraph" data-title="A & B <x>"></section>'+ );++ expect(exported).toBe(+ '<section class="link-embed" data-url="https://e.com/?a=1&b=2" data-embed-type="opengraph" data-title="A & B <x>">' ++ '<a href="https://e.com/?a=1&b=2">A & B <x></a></section>'+ );+ });+it("exports strikethrough text correctly", () => {const html = "<s>hello</s>Hello <s>world</s>";const expected = "~~hello~~Hello ~~world~~";diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex c9abb5198b..aa8c06eaa0 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -1,6 +1,8 @@import { type TaskStateDef } from "@triliumnext/commons";import { ADMONITION_TYPE_MAPPINGS } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { gfm, serializeStructuralHtml } from "@triliumnext/turndown-plugin-gfm";+import escapeHtml from "escape-html";+import { parse as parseHtml } from "node-html-parser";import Turnish, { type Rule } from "turnish";import { getTaskStates } from "../task_states.js";@@ -45,6 +47,12 @@ function toMarkdown(content: string) {return node.outerHTML;}+ // Only reached by a link preview without a data-url (the fallback anchor injected+ // by `injectLinkPreviewFallbacks` makes every other one non-blank).+ if (isLinkPreview(node)) {+ return linkPreviewReplacement(node as HTMLElement);+ }+// Original implementation as per https://github.com/mixmark-io/turndown/blob/master/src/turndown.js.return ("isBlock" in node && node.isBlock) ? '\n\n' : '';},@@ -56,13 +64,14 @@ function toMarkdown(content: string) {instance.addRule("details", buildDetailsFilter());instance.addRule("inlineLink", buildInlineLinkFilter());instance.addRule("figure", buildFigureFilter());+ instance.addRule("linkPreview", buildLinkPreviewFilter());instance.addRule("math", buildMathFilter());instance.addRule("li", buildListItemFilter());instance.use(gfm);instance.keep([ "kbd", "sup", "sub" ]);}- return instance.render(content);+ return instance.render(injectLinkPreviewFallbacks(content));}function rewriteLanguageTag(source: string) {@@ -220,6 +229,59 @@ function buildFigureFilter(): Rule {};}+/**+ * Link previews (block `<section class="link-embed">`, inline `<span class="link-mention">`) keep+ * all their metadata in data attributes on an empty element, so without special handling turndown+ * treats them as blank nodes and drops them from the export entirely — URL included.+ *+ * A fallback `<a>` child is injected before turndown parses the content, which solves three+ * problems at once: the export stays meaningful in renderers that don't know the widget (GitHub,+ * Obsidian show a plain link), the inline mention is no longer blank so turndown's whitespace+ * collapsing doesn't eat the space that follows it (an empty inline element is assumed to render+ * as nothing), and the `linkPreview` rule below fires (rules never run on blank nodes).+ *+ * An anchor already present — e.g. in content imported from Markdown that was never re-saved by+ * the editor — is regenerated rather than kept, so a stale title is refreshed instead of+ * accumulated. On reimport the round-trip is lossless: the sanitizer allows `section`/`span` and+ * `data-*`, and the editor upcasts both purely by tag + class, ignoring children.+ */+function injectLinkPreviewFallbacks(content: string): string {+ if (!content.includes("link-embed") && !content.includes("link-mention")) {+ return content;+ }++ const root = parseHtml(content);+ for (const element of root.querySelectorAll("section.link-embed, span.link-mention")) {+ const url = element.getAttribute("data-url");+ if (url) {+ const title = element.getAttribute("data-title") || url;+ element.innerHTML = `<a href="${escapeHtml(url)}">${escapeHtml(title)}</a>`;+ }+ }++ return root.toString();+}++function isLinkPreview(node: HTMLElement): boolean {+ return (node.nodeName === "SECTION" && node.classList.contains("link-embed"))+ || (node.nodeName === "SPAN" && node.classList.contains("link-mention"));+}++function linkPreviewReplacement(node: HTMLElement): string {+ return node.nodeName === "SECTION" ? `\n\n${node.outerHTML}\n\n` : node.outerHTML;+}++function buildLinkPreviewFilter(): Rule {+ return {+ filter(node) {+ return isLinkPreview(node);+ },+ replacement(_content, node) {+ return linkPreviewReplacement(node as HTMLElement);+ }+ };+}+/*** Markdown has no native syntax for disclosure widgets, but GitHub, Obsidian* and most CommonMark+HTML renderers accept raw <details>/<summary> verbatimdiff --git a/packages/trilium-core/src/services/import/markdown.spec.ts b/packages/trilium-core/src/services/import/markdown.spec.tsindex 36c156bdd4..2af8f09c32 100644--- a/packages/trilium-core/src/services/import/markdown.spec.ts+++ b/packages/trilium-core/src/services/import/markdown.spec.ts@@ -209,6 +209,16 @@ second line 2</code></pre><ul><li>Hello</li><li>world</li></ul><ol><li>Hello</liexpect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);});+ it("imports back link previews exported as raw HTML", () => {+ // The Markdown exporter emits link previews as their canonical HTML plus a fallback+ // anchor; both forms must survive sanitization so the editor can upcast them again.+ const block = '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="Example"><a href="https://e.com/">Example</a></section>';+ expect(markdownService.renderToHtml(block, "Title")).toStrictEqual(block);++ const inline = 'See <span class="link-mention" data-url="https://e.com/" data-title="Example"><a href="https://e.com/">Example</a></span> for details.';+ expect(markdownService.renderToHtml(inline, "Title")).toStrictEqual(`<p>${inline}</p>`);+ });+it("preserves figures and images with sizes", () => {const scenarios = [/*html*/`<figure class="image image-style-align-center image_resized" style="width:53.44%;"><img style="aspect-ratio:991/403;" src="Jump to Note_image.png" width="991" height="403"></figure>`,