Skip to content

Build your personal knowledge base with Trilium Notes

feat(markdown): use lexer-based ToC

Elian Doranc4657c72e59b
diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsx
index 10fd150689..4cdf618db7 100644
--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx
+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx
@@ -38,13 +38,13 @@ export default function TableOfContents() {
<RightPanelWidget id="toc" title={t("toc.table_of_contents")} grow>
{((noteType === "text" && isReadOnly) || (noteType === "doc")) && <ReadOnlyTextTableOfContents />}
{noteType === "text" && !isReadOnly && <EditableTextTableOfContents />}
- {noteType === "file" && noteMime === "application/pdf" && <PdfTableOfContents />}
- {note?.isMarkdown() && <ReadOnlyTextTableOfContents />}
+ {noteType === "file" && noteMime === "application/pdf" && <ContextDataTableOfContents />}
+ {note?.isMarkdown() && <ContextDataTableOfContents />}
</RightPanelWidget>
);
}
-function PdfTableOfContents() {
+function ContextDataTableOfContents() {
const data = useGetContextData("toc");
return (
diff --git a/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts
index 0addb5037a..a7231a880f 100644
--- a/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts
+++ b/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts
@@ -3,18 +3,23 @@ import { describe, expect, it } from "vitest";
import { renderWithSourceLines } from "./Markdown.js";
describe("renderWithSourceLines", () => {
- function extractLines(html: string): number[] {
+ function extractLines(src: string): number[] {
+ const { html } = renderWithSourceLines(src);
return [ ...html.matchAll(/data-source-line="(\d+)"/g) ].map((m) => parseInt(m[1], 10));
}
- it("returns empty string for empty input", () => {
- expect(renderWithSourceLines("")).toBe("");
+ function html(src: string): string {
+ return renderWithSourceLines(src).html;
+ }
+
+ it("returns empty html for empty input", () => {
+ expect(html("")).toBe("");
});
it("tags a single block as line 1", () => {
- const html = renderWithSourceLines("hello");
- expect(extractLines(html)).toEqual([ 1 ]);
- expect(html).toContain("hello");
+ const result = html("hello");
+ expect(extractLines("hello")).toEqual([ 1 ]);
+ expect(result).toContain("hello");
});
it("assigns correct source lines to consecutive blocks separated by blank lines", () => {
@@ -26,7 +31,7 @@ describe("renderWithSourceLines", () => {
"Another one." // line 5
].join("\n");
- expect(extractLines(renderWithSourceLines(src))).toEqual([ 1, 3, 5 ]);
+ expect(extractLines(src)).toEqual([ 1, 3, 5 ]);
});
it("counts multi-line blocks so subsequent blocks get the right line", () => {
@@ -39,19 +44,18 @@ describe("renderWithSourceLines", () => {
"after" // 6
].join("\n");
- expect(extractLines(renderWithSourceLines(src))).toEqual([ 1, 6 ]);
+ expect(extractLines(src)).toEqual([ 1, 6 ]);
});
it("renders standard markdown constructs inside the wrappers", () => {
- const html = renderWithSourceLines("## Heading\n\n- item\n");
- expect(html).toContain("<h2>Heading</h2>");
- expect(html).toContain("<ul>");
- expect(html).toContain("<li>item</li>");
+ const result = html("## Heading\n\n- item\n");
+ expect(result).toContain("<h2>Heading</h2>");
+ expect(result).toContain("<ul>");
+ expect(result).toContain("<li>item</li>");
});
it("keeps H1 as H1 in the preview (no title-row context to avoid)", () => {
- const html = renderWithSourceLines("# Top level");
- expect(html).toContain("<h1>Top level</h1>");
+ expect(html("# Top level")).toContain("<h1>Top level</h1>");
});
it("preserves reference-style links across per-block parsing", () => {
@@ -61,33 +65,47 @@ describe("renderWithSourceLines", () => {
"[t]: https://example.com"
].join("\n");
- const html = renderWithSourceLines(src);
- expect(html).toContain('href="https://example.com"');
+ expect(html(src)).toContain('href="https://example.com"');
});
it("normalizes fenced code languages to CKEditor MIME identifiers for syntax highlighting", () => {
- const html = renderWithSourceLines("```javascript\nconst x = 1;\n```");
- expect(html).toMatch(/class="language-application-javascript-env-(backend|frontend)"/);
+ expect(html("```javascript\nconst x = 1;\n```")).toMatch(/class="language-application-javascript-env-(backend|frontend)"/);
});
it("produces CKEditor admonition markup for GFM callouts", () => {
- const html = renderWithSourceLines("> [!NOTE]\n> heads up");
- expect(html).toContain('<aside class="admonition note">');
+ expect(html("> [!NOTE]\n> heads up")).toContain('<aside class="admonition note">');
});
it("preserves the `mermaid` fence language so the mermaid rewrite can match it", () => {
- const html = renderWithSourceLines("```mermaid\ngraph TD;\nA-->B;\n```");
- expect(html).toContain('class="language-mermaid"');
+ expect(html("```mermaid\ngraph TD;\nA-->B;\n```")).toContain('class="language-mermaid"');
});
it("produces math-tex spans for inline math", () => {
- const html = renderWithSourceLines("Energy: $e=mc^2$.");
- expect(html).toContain('<span class="math-tex">');
+ expect(html("Energy: $e=mc^2$.")).toContain('<span class="math-tex">');
});
it("renders [[wikilinks]] with hash-router hrefs so the preview navigates correctly", () => {
- const html = renderWithSourceLines("See [[abc123]] for details.");
- expect(html).toContain('class="reference-link"');
- expect(html).toContain('href="#root/abc123"');
+ const result = html("See [[abc123]] for details.");
+ expect(result).toContain('class="reference-link"');
+ expect(result).toContain('href="#root/abc123"');
+ });
+
+ it("extracts headings with correct levels and lines", () => {
+ const src = [
+ "# Title", // line 1
+ "", // line 2
+ "text", // line 3
+ "", // line 4
+ "## Section", // line 5
+ "", // line 6
+ "### Sub" // line 7
+ ].join("\n");
+
+ const { headings } = renderWithSourceLines(src);
+ expect(headings).toEqual([
+ { id: "md-heading-0", level: 1, text: "Title", line: 1 },
+ { id: "md-heading-1", level: 2, text: "Section", line: 5 },
+ { id: "md-heading-2", level: 3, text: "Sub", line: 7 }
+ ]);
});
});
diff --git a/apps/client/src/widgets/type_widgets/code/Markdown.tsx b/apps/client/src/widgets/type_widgets/code/Markdown.tsx
index 05a27ad511..cf4e744c9f 100644
--- a/apps/client/src/widgets/type_widgets/code/Markdown.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Markdown.tsx
@@ -6,15 +6,23 @@ import DOMPurify from "dompurify";
import { Marked } from "marked";
import { createContext } from "preact";
import { useContext, useEffect, useMemo, useState } from "preact/hooks";
-
+import NoteContext from "../../../components/note_context";
import SplitEditor from "../helpers/SplitEditor";
import { ReadOnlyTextContent } from "../text/ReadOnlyText";
import { TypeWidgetProps } from "../type_widget";
const marked = new Marked({ breaks: true, gfm: true });
+export interface MarkdownHeading {
+ id: string;
+ level: number;
+ text: string;
+ line: number;
+}
+
interface MarkdownContextValue {
html: string;
+ headings: MarkdownHeading[];
setEditorView: (view: VanillaCodeMirror | null) => void;
setPreviewEl: (el: HTMLDivElement | null) => void;
}
@@ -31,14 +39,15 @@ export default function Markdown(props: TypeWidgetProps) {
const [ content, setContent ] = useState("");
const [ editorView, setEditorView ] = useState<VanillaCodeMirror | null>(null);
const [ previewEl, setPreviewEl ] = useState<HTMLDivElement | null>(null);
- const html = useMemo(() => renderWithSourceLines(content), [ content ]);
+ const { html, headings } = useMemo(() => renderWithSourceLines(content), [ content ]);
useSyncedScrolling(editorView, previewEl);
useSyncedHighlight(editorView, previewEl, html);
+ usePublishToc(props.noteContext, editorView, headings);
const ctx = useMemo<MarkdownContextValue>(
- () => ({ html, setEditorView, setPreviewEl }),
- [ html ]
+ () => ({ html, headings, setEditorView, setPreviewEl }),
+ [ html, headings ]
);
return (
@@ -67,6 +76,36 @@ function MarkdownPreview({ ntxId }: { ntxId: TypeWidgetProps["ntxId"] }) {
);
}
+//#region Table of contents
+/**
+ * Publishes heading data via `setContextData("toc", ...)` so the sidebar
+ * Table of Contents can display headings extracted from the markdown source,
+ * independent of whether the preview pane is visible.
+ */
+function usePublishToc(
+ noteContext: NoteContext | undefined,
+ editorView: VanillaCodeMirror | null,
+ headings: MarkdownHeading[]
+) {
+ useEffect(() => {
+ if (!noteContext) return;
+ noteContext.setContextData("toc", {
+ headings,
+ scrollToHeading(heading) {
+ if (!editorView) return;
+ const mdHeading = headings.find(h => h.id === heading.id);
+ if (!mdHeading) return;
+ const line = editorView.state.doc.line(Math.min(mdHeading.line, editorView.state.doc.lines));
+ const lineBlock = editorView.lineBlockAt(line.from);
+ const scrollerHeight = editorView.scrollDOM.clientHeight;
+ const targetTop = lineBlock.top - scrollerHeight / 2 + lineBlock.height / 2;
+ editorView.scrollDOM.scrollTo({ top: targetTop, behavior: "smooth" });
+ }
+ });
+ }, [ noteContext, headings, editorView ]);
+}
+//#endregion
+
//#region Synced scrolling
/**
* One-directional (editor → preview) scroll sync. On editor scroll, finds the
@@ -161,15 +200,25 @@ const NON_RENDERED_TOKENS = new Set([ "space", "def" ]);
* with the matching lexer token's start line. Marked does not emit source
* positions (markedjs/marked#1267) so we count newlines in `raw` ourselves.
*/
-export function renderWithSourceLines(src: string): string {
+export function renderWithSourceLines(src: string): { html: string; headings: MarkdownHeading[] } {
// Compute the start line of each renderable top-level token in source order.
const tokens = marked.lexer(src);
const lines: number[] = [];
+ const headings: MarkdownHeading[] = [];
let line = 1;
+ let headingIdx = 0;
for (const token of tokens) {
const startLine = line;
line += (token.raw.match(/\n/g) ?? []).length;
if (!NON_RENDERED_TOKENS.has(token.type)) lines.push(startLine);
+ if (token.type === "heading") {
+ headings.push({
+ id: `md-heading-${headingIdx++}`,
+ level: (token as { depth: number }).depth,
+ text: token.text ?? "",
+ line: startLine
+ });
+ }
}
const html = renderToHtml(src, "", {
@@ -177,7 +226,7 @@ export function renderWithSourceLines(src: string): string {
wikiLink: { formatHref: (id) => `#root/${id}` },
demoteH1: false
});
- if (!html) return "";
+ if (!html) return { html: "", headings };
const container = document.createElement("div");
container.innerHTML = html;
@@ -188,6 +237,6 @@ export function renderWithSourceLines(src: string): string {
const sourceLine = lines[i] ?? lines[lines.length - 1] ?? 1;
parts.push(`<div data-source-line="${sourceLine}">${children[i].outerHTML}</div>`);
}
- return parts.join("");
+ return { html: parts.join(""), headings };
}
//#endregion