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(markdown): render preview as Markdown
Elian Doran69763c8b1437
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex e037383a73..cfe4383f09 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -1,6 +1,7 @@import "./content_renderer.css";-import { normalizeMimeTypeForCKEditor, type TextRepresentationResponse } from "@triliumnext/commons";+import { normalizeMimeTypeForCKEditor, renderToHtml, type TextRepresentationResponse } from "@triliumnext/commons";+import DOMPurify from "dompurify";import { h, render } from "preact";import WheelZoom from 'vanilla-js-wheel-zoom';@@ -8,7 +9,7 @@ import FAttachment from "../entities/fattachment.js";import FNote from "../entities/fnote.js";import imageContextMenuService from "../menus/image_context_menu.js";import { t } from "../services/i18n.js";-import renderText from "./content_renderer_text.js";+import renderText, { postProcessRichContent, renderChildrenList } from "./content_renderer_text.js";import renderDoc from "./doc_renderer.js";import { loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";import openService from "./open.js";@@ -54,6 +55,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNoif (type === "text" || type === "book") {await renderText(entity, $renderedContent, options);+ } else if (type === "markdown") {+ await renderMarkdown(entity, $renderedContent, options);} else if (type === "code") {await renderCode(entity, $renderedContent);} else if (["image", "canvas", "mindMap", "spreadsheet"].includes(type)) {@@ -119,6 +122,31 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo};}+/**+ * Renders a markdown note by converting its source to CKEditor-compatible HTML,+ * then running the same post-render pipeline as text notes (included notes,+ * math, reference links, Mermaid, code highlight) so the preview matches what+ * the user sees in the Markdown note type's preview pane.+ */+async function renderMarkdown(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions) {+ const blob = await note.getBlob();+ const source = blob?.content ?? "";++ if (!source.trim()) {+ if (note instanceof FNote && !options.noChildrenList) {+ await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);+ }+ return;+ }++ const html = renderToHtml(source, note.title, {+ sanitize: (dirty) => DOMPurify.sanitize(dirty),+ wikiLink: { formatHref: (id) => `#root/${id}` }+ });+ $renderedContent.append($('<div class="ck-content">').html(html));+ await postProcessRichContent(note, $renderedContent, options);+}+/*** Renders a code note, by displaying its content and applying syntax highlighting based on the selected MIME type.*/@@ -330,6 +358,8 @@ function getRenderingType(entity: FNote | FAttachment) {if (type === "file" && mime === "application/pdf") {type = "pdf";+ } else if (type === "code" && entity instanceof FNote && entity.isMarkdown()) {+ type = "markdown";} else if ((type === "file" || type === "viewConfig") && mime && CODE_MIME_TYPES.has(mime) && !isIconPack) {type = "code";} else if (type === "file" && mime && mime.startsWith("audio/")) {diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex dd8178708d..1684ce766c 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -15,35 +15,45 @@ export default async function renderText(note: FNote | FAttachment, $renderedConif (blob && !isHtmlEmpty(blob.content)) {$renderedContent.append($('<div class="ck-content">').html(blob.content));+ await postProcessRichContent(note, $renderedContent, options);+ } else if (note instanceof FNote && !options.noChildrenList) {+ await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);+ }+}- const seenNoteIds = options.seenNoteIds ?? new Set<string>();- seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);- if (!options.noIncludedNotes) {- await renderIncludedNotes($renderedContent[0], seenNoteIds);- } else {- $renderedContent.find("section.include-note").remove();- }-- if ($renderedContent.find("span.math-tex").length > 0) {- renderMathInElement($renderedContent[0], { trust: true });- }+/**+ * Apply the post-render passes that make CKEditor-compatible HTML fully+ * interactive: expand `<section class="include-note">`, render inline math and+ * Mermaid diagrams, rewrite reference-link titles, and highlight code blocks.+ * Assumes the caller has already appended the HTML inside a `.ck-content` child+ * of `$renderedContent`.+ */+export async function postProcessRichContent(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {+ const seenNoteIds = options.seenNoteIds ?? new Set<string>();+ seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);+ if (!options.noIncludedNotes) {+ await renderIncludedNotes($renderedContent[0], seenNoteIds);+ } else {+ $renderedContent.find("section.include-note").remove();+ }- const getNoteIdFromLink = (el: HTMLElement) => tree.getNoteIdFromUrl($(el).attr("href") || "");- const referenceLinks = $renderedContent.find<HTMLAnchorElement>("a.reference-link");- const noteIdsToPrefetch = referenceLinks.map((i, el) => getNoteIdFromLink(el));- await froca.getNotes(noteIdsToPrefetch);+ if ($renderedContent.find("span.math-tex").length > 0) {+ renderMathInElement($renderedContent[0], { trust: true });+ }- for (const el of referenceLinks) {- const innerSpan = document.createElement("span");- await link.loadReferenceLinkTitle($(innerSpan), el.href);- el.replaceChildren(innerSpan);- }+ const getNoteIdFromLink = (el: HTMLElement) => tree.getNoteIdFromUrl($(el).attr("href") || "");+ const referenceLinks = $renderedContent.find<HTMLAnchorElement>("a.reference-link");+ const noteIdsToPrefetch = referenceLinks.map((i, el) => getNoteIdFromLink(el));+ await froca.getNotes(noteIdsToPrefetch);- await rewriteMermaidDiagramsInContainer($renderedContent[0] as HTMLDivElement);- await formatCodeBlocks($renderedContent);- } else if (note instanceof FNote && !options.noChildrenList) {- await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);+ for (const el of referenceLinks) {+ const innerSpan = document.createElement("span");+ await link.loadReferenceLinkTitle($(innerSpan), el.href);+ el.replaceChildren(innerSpan);}++ await rewriteMermaidDiagramsInContainer($renderedContent[0] as HTMLDivElement);+ await formatCodeBlocks($renderedContent);}async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<string>) {@@ -201,7 +211,7 @@ export async function applyInlineMermaid(container: HTMLDivElement) {mermaidLastRenderedByPosition.set(container, nodes.map((n) => n.innerHTML));}-async function renderChildrenList($renderedContent: JQuery<HTMLElement>, note: FNote, includeArchivedNotes: boolean) {+export async function renderChildrenList($renderedContent: JQuery<HTMLElement>, note: FNote, includeArchivedNotes: boolean) {let childNoteIds = note.getChildNoteIds();if (!childNoteIds.length) {