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(markdown): preserve heading hierarchy instead of flattening to H2 (#8383)
Elian Doran86dcf5755ed8
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.tsindex 771a2c22d3..6e4528f32b 100644--- a/packages/commons/src/lib/markdown_renderer.spec.ts+++ b/packages/commons/src/lib/markdown_renderer.spec.ts@@ -128,6 +128,20 @@ describe("renderToHtml", () => {const html = render("## sub heading", "irrelevant");expect(html).toBe("<h2>sub heading</h2>");});++ it("shifts the whole hierarchy down one level when a content <h1> remains (#8383)", () => {+ // A leading <h1> demoted to <h2> while leaving a sibling <h2> as <h2> would+ // collapse two distinct levels; instead the hierarchy shifts down so nesting+ // is preserved (and clamps at <h6>).+ expect(render("# A\n\n## B\n\n### C", "X")).toBe("<h2>A</h2><h3>B</h3><h4>C</h4>");+ expect(render("# A\n\n###### Deep", "X")).toBe("<h2>A</h2><h6>Deep</h6>");+ });++ it("does not shift when the title is stripped and the content already starts at <h2>", () => {+ // The common case: the leading <h1> equals the title and is removed, leaving+ // content that already begins at <h2> — nothing else should move.+ expect(render("# Title\n\n## A\n\n### B", "Title")).toBe("<h2>A</h2><h3>B</h3>");+ });});describe("paragraphs", () => {diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex d6ca557b13..fb55a079c8 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -183,19 +183,43 @@ function getNormalizedMimeFromMarkdownLanguage(language: string | undefined): st}function handleH1(content: string, title: string): string {- let isFirstH1Handled = false;+ // Drop the leading <h1> if it merely repeats the note title — the title is+ // rendered separately above the content, so keeping it would duplicate it.+ content = stripDuplicateTitleHeading(content, title);++ // If a content <h1> still remains, the author's hierarchy starts at level 1.+ // The editor reserves <h1> for the note title and only offers <h2>–<h6>, so+ // shift every heading down one level (clamping at <h6>) to preserve nesting.+ // Demoting <h1>→<h2> alone collapsed distinct <h1>/<h2> levels onto the same+ // <h2>, flattening the hierarchy (see #8383).+ if (/<h1[^>]*>[^<]*<\/h1>/i.test(content)) {+ content = shiftHeadingsDown(content);+ }- return content.replace(/<h1[^>]*>([^<]*)<\/h1>/gi, (match, text: string) => {- text = unescapeHtml(text);- const convertedContent = `<h2>${text}</h2>`;+ return content;+}- if (!isFirstH1Handled) {- isFirstH1Handled = true;- return title.trim() === text.trim() ? "" : convertedContent;- }+/** Removes the first `<h1>` when its (decoded) text equals the note title. */+function stripDuplicateTitleHeading(content: string, title: string): string {+ // No `g` flag: only the very first <h1> is a title candidate.+ return content.replace(/<h1[^>]*>([^<]*)<\/h1>/i, (match, text: string) =>+ unescapeHtml(text).trim() === title.trim() ? "" : match+ );+}- return convertedContent;- });+/**+ * Shifts every heading down one level so the content hierarchy fits the editor's+ * <h2>–<h6> range: <h2>–<h5> become <h3>–<h6>, the remaining <h1> become <h2>+ * (decoding their text to stay consistent with the title comparison), and <h6>+ * stays <h6> since there is no <h7> to shift into.+ */+function shiftHeadingsDown(content: string): string {+ // Shift the sub-headings first so the <h1>→<h2> demotion below isn't re-shifted.+ return content+ .replace(/<(\/?)h([2-5])\b([^>]*)>/gi, (_match, slash, level, rest) =>+ `<${slash}h${Number(level) + 1}${rest}>`)+ .replace(/<h1[^>]*>([^<]*)<\/h1>/gi, (_match, text) =>+ `<h2>${unescapeHtml(text)}</h2>`);}export function extractCodeBlocks(text: string): { processedText: string; placeholderMap: Map<string, string> } {diff --git a/packages/trilium-core/src/services/import/markdown.spec.ts b/packages/trilium-core/src/services/import/markdown.spec.tsindex 6e65bf35f7..96e7127097 100644--- a/packages/trilium-core/src/services/import/markdown.spec.ts+++ b/packages/trilium-core/src/services/import/markdown.spec.ts@@ -43,7 +43,43 @@ describe("markdown", () => {# another oneHello, world`, "title");- expect(result).toBe(`<h2>Hello</h2><h2>world</h2><h2>another one</h2><p>Hello, world</p>`);+ // <h1> is reserved for the note title, so the hierarchy is shifted down one+ // level rather than collapsed: the two top-level `#` become <h2> siblings and+ // the nested `##` becomes <h3>, preserving the author's nesting (#8383).+ expect(result).toBe(`<h2>Hello</h2><h3>world</h3><h2>another one</h2><p>Hello, world</p>`);+ });++ it("preserves heading hierarchy by shifting levels when content starts at H1 (#8383)", () => {+ // Content authored with H1 as the top level: every heading shifts down one+ // level so the parent/child relationship survives instead of flattening onto H2.+ expect(markdownService.renderToHtml(trimIndentation`\+ # Main Section+ ## Subsection A+ ### Detail+ ## Subsection B+ `, "Notes")).toBe(`<h2>Main Section</h2><h3>Subsection A</h3><h4>Detail</h4><h3>Subsection B</h3>`);++ // The first H1 matching the title is stripped; if a content H1 still remains,+ // the rest is shifted, otherwise it is left untouched.+ expect(markdownService.renderToHtml(trimIndentation`\+ # Notes+ # Chapter 1+ ## Section+ `, "Notes")).toBe(`<h2>Chapter 1</h2><h3>Section</h3>`);++ // Common case: title is stripped and the content already starts at H2 — no shift.+ expect(markdownService.renderToHtml(trimIndentation`\+ # Notes+ ## Section+ ### Sub+ `, "Notes")).toBe(`<h2>Section</h2><h3>Sub</h3>`);++ // Deeper levels clamp at H6 (there is no H7 to shift into).+ expect(markdownService.renderToHtml(trimIndentation`\+ # Top+ ##### Five+ ###### Six+ `, "Notes")).toBe(`<h2>Top</h2><h6>Five</h6><h6>Six</h6>`);});it("parses duplicate title with escape correctly", () => {diff --git a/packages/trilium-core/src/services/import/utils.spec.ts b/packages/trilium-core/src/services/import/utils.spec.tsindex abd33e025d..7959456b0c 100644--- a/packages/trilium-core/src/services/import/utils.spec.ts+++ b/packages/trilium-core/src/services/import/utils.spec.ts@@ -90,6 +90,26 @@ describe("#handleH1", () => {"w/ multiple <h1> tags, and the 1st matching NOT the title tag, it should NOT strip any other <h1> tags",["<h1>Introduction</h1><h1>Topic ABC</h1><h1>Summary</h1>", "Topic ABC"],"<h2>Introduction</h2><h2>Topic ABC</h2><h2>Summary</h2>"+ ],+ [+ "w/ a content <h1> followed by an <h2>, it should shift the hierarchy down instead of collapsing both onto <h2> (#8383)",+ ["<h1>Main</h1><h2>Sub</h2>", "Title"],+ "<h2>Main</h2><h3>Sub</h3>"+ ],+ [+ "w/ the 1st <h1> matching the title and a remaining content <h1>, it should strip the title and shift the rest",+ ["<h1>Title</h1><h1>Chapter</h1><h2>Section</h2>", "Title"],+ "<h2>Chapter</h2><h3>Section</h3>"+ ],+ [+ "w/ the 1st <h1> matching the title and only <h2> content remaining, it should strip the title without shifting",+ ["<h1>Title</h1><h2>Section</h2>", "Title"],+ "<h2>Section</h2>"+ ],+ [+ "w/ headings deeper than <h2>, the shift should clamp at <h6>",+ ["<h1>A</h1><h2>B</h2><h6>C</h6>", "Title"],+ "<h2>A</h2><h3>B</h3><h6>C</h6>"]];diff --git a/packages/trilium-core/src/services/import/utils.ts b/packages/trilium-core/src/services/import/utils.tsindex 3c5a73d9a0..a3bcab5b80 100644--- a/packages/trilium-core/src/services/import/utils.ts+++ b/packages/trilium-core/src/services/import/utils.ts@@ -1,20 +1,43 @@import { unescapeHtml } from "../utils";function handleH1(content: string, title: string) {- let isFirstH1Handled = false;+ // Drop the leading <h1> if it merely repeats the note title — the title is+ // rendered separately above the content, so keeping it would duplicate it.+ content = stripDuplicateTitleHeading(content, title);- return content.replace(/<h1[^>]*>([^<]*)<\/h1>/gi, (match, text) => {- text = unescapeHtml(text);- const convertedContent = `<h2>${text}</h2>`;+ // If a content <h1> still remains, the author's hierarchy starts at level 1.+ // The editor reserves <h1> for the note title and only offers <h2>–<h6>, so+ // shift every heading down one level (clamping at <h6>) to preserve nesting.+ // Demoting <h1>→<h2> alone collapsed distinct <h1>/<h2> levels onto the same+ // <h2>, flattening the hierarchy (see #8383).+ if (/<h1[^>]*>[^<]*<\/h1>/i.test(content)) {+ content = shiftHeadingsDown(content);+ }- // strip away very first found h1 tag, if it matches the title- if (!isFirstH1Handled) {- isFirstH1Handled = true;- return title.trim() === text.trim() ? "" : convertedContent;- }+ return content;+}++/** Removes the first `<h1>` when its (decoded) text equals the note title. */+function stripDuplicateTitleHeading(content: string, title: string) {+ // No `g` flag: only the very first <h1> is a title candidate.+ return content.replace(/<h1[^>]*>([^<]*)<\/h1>/i, (match, text) =>+ unescapeHtml(text).trim() === title.trim() ? "" : match+ );+}- return convertedContent;- });+/**+ * Shifts every heading down one level so the content hierarchy fits the editor's+ * <h2>–<h6> range: <h2>–<h5> become <h3>–<h6>, the remaining <h1> become <h2>+ * (decoding their text to stay consistent with the title comparison), and <h6>+ * stays <h6> since there is no <h7> to shift into.+ */+function shiftHeadingsDown(content: string) {+ // Shift the sub-headings first so the <h1>→<h2> demotion below isn't re-shifted.+ return content+ .replace(/<(\/?)h([2-5])\b([^>]*)>/gi, (_match, slash, level, rest) =>+ `<${slash}h${Number(level) + 1}${rest}>`)+ .replace(/<h1[^>]*>([^<]*)<\/h1>/gi, (_match, text) =>+ `<h2>${unescapeHtml(text)}</h2>`);}function extractHtmlTitle(content: string): string | null {