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
refactor(markdown): fold demoteHeadings into markdown_renderer
Elian Dorand51efefd4b8b
diff --git a/packages/commons/src/lib/heading_demotion.spec.ts b/packages/commons/src/lib/heading_demotion.spec.tsdeleted file mode 100644index 0ec404ab68..0000000000--- a/packages/commons/src/lib/heading_demotion.spec.ts+++ /dev/null@@ -1,47 +0,0 @@-import { describe, expect, it } from "vitest";--import { demoteHeadings } from "./heading_demotion.js";--/** Identity decoder — keeps the heading text verbatim. */-const verbatim = (s: string) => s;--describe("demoteHeadings", () => {- it("leaves content untouched when there is no <h1>", () => {- expect(demoteHeadings("<h2>A</h2><h3>B</h3>", "Title", verbatim)).toBe("<h2>A</h2><h3>B</h3>");- });-- it("strips the leading <h1> that duplicates the title without shifting the rest", () => {- // The common case: title removed, content already starts at <h2>.- expect(demoteHeadings("<h1>Title</h1><h2>A</h2><h3>B</h3>", "Title", verbatim))- .toBe("<h2>A</h2><h3>B</h3>");- });-- it("shifts the whole hierarchy down one level when a content <h1> remains", () => {- // Top-level <h1> and nested <h2> stay distinct instead of both becoming <h2>.- expect(demoteHeadings("<h1>A</h1><h2>B</h2><h3>C</h3>", "Title", verbatim))- .toBe("<h2>A</h2><h3>B</h3><h4>C</h4>");- // Title stripped, but a remaining content <h1> still triggers the shift.- expect(demoteHeadings("<h1>Title</h1><h1>Chapter</h1><h2>Section</h2>", "Title", verbatim))- .toBe("<h2>Chapter</h2><h3>Section</h3>");- });-- it("clamps at <h6> since there is no <h7>", () => {- expect(demoteHeadings("<h1>A</h1><h5>E</h5><h6>F</h6>", "Title", verbatim))- .toBe("<h2>A</h2><h6>E</h6><h6>F</h6>");- });-- it("matches headings with inline markup and carries attributes onto the demoted <h2>", () => {- expect(demoteHeadings("<h1>Chapter <em>One</em></h1><h2>Intro</h2>", "Title", verbatim))- .toBe("<h2>Chapter <em>One</em></h2><h3>Intro</h3>");- expect(demoteHeadings(`<h1 id="top">Main</h1><h2>Sub</h2>`, "Title", verbatim))- .toBe(`<h2 id="top">Main</h2><h3>Sub</h3>`);- });-- it("applies the injected decoder to the demoted <h1> text and the title comparison only", () => {- const upper = (s: string) => s.toUpperCase();- // The decoder runs on the <h1> text but not on shifted sub-headings.- expect(demoteHeadings("<h1>a</h1><h2>b</h2>", "Title", upper)).toBe("<h2>A</h2><h3>b</h3>");- // The decoder is also used when comparing the first <h1> against the title.- expect(demoteHeadings("<h1>a</h1>", "A", upper)).toBe("");- });-});diff --git a/packages/commons/src/lib/heading_demotion.ts b/packages/commons/src/lib/heading_demotion.tsdeleted file mode 100644index 9031ddb038..0000000000--- a/packages/commons/src/lib/heading_demotion.ts+++ /dev/null@@ -1,61 +0,0 @@-/** Decodes HTML entities in heading text; supplied by each {@link demoteHeadings} caller. */-export type EntityDecoder = (str: string) => string;--/**- * Trilium reserves `<h1>` for the note title and the editor only supports- * `<h2>`–`<h6>`. When rendered/imported content starts its hierarchy at `<h1>`,- * naively demoting every `<h1>` to `<h2>` while leaving `<h2>`–`<h6>` untouched- * collapses distinct levels onto the same `<h2>`, flattening the nesting (#8383).- *- * This strips the leading `<h1>` if it duplicates the title, then — if a content- * `<h1>` still remains — shifts the whole hierarchy down one level so the author's- * structure is preserved.- *- * The entity decoder is injected so each call-site keeps its own `unescapeHtml`- * semantics: the markdown renderer decodes numeric/hex/named entities, while the- * HTML importer decodes only the five basic ones (matching `api.unescapeHtml`).- */-export function demoteHeadings(- content: string,- title: string,- unescapeHtml: EntityDecoder-): string {- content = stripDuplicateTitleHeading(content, title, unescapeHtml);-- // If a content <h1> still remains, the hierarchy starts at level 1: shift every- // heading down one level (clamping at <h6>) so nesting is preserved instead of- // collapsing distinct <h1>/<h2> levels onto the same <h2>.- if (/<h1[^>]*>[\s\S]*?<\/h1>/i.test(content)) {- content = shiftHeadingsDown(content, unescapeHtml);- }-- return content;-}--/** Removes the first `<h1>` when its (decoded) text equals the note title. */-function stripDuplicateTitleHeading(- content: string,- title: string,- unescapeHtml: EntityDecoder-): string {- // No `g` flag: only the very first <h1> is a title candidate. `[\s\S]*?` (not- // `[^<]*`) so headings with inline markup or attributes still match.- return content.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/i, (match, text: string) =>- unescapeHtml(text).trim() === title.trim() ? "" : match- );-}--/**- * Shifts `<h2>`–`<h5>` to `<h3>`–`<h6>` and the remaining `<h1>` to `<h2>`- * (preserving attributes and decoding text). `<h6>` stays put — there is no `<h7>`.- */-function shiftHeadingsDown(content: string, unescapeHtml: EntityDecoder): string {- // Shift the sub-headings first so the <h1>→<h2> demotion below isn't re-shifted.- // `[\s\S]*?` matches headings containing inline markup; the captured attributes- // are carried over to the demoted <h2>.- return content- .replace(/<(\/?)h([2-5])\b([^>]*)>/gi, (_match, slash, level, rest) =>- `<${slash}h${Number(level) + 1}${rest}>`)- .replace(/<h1([^>]*)>([\s\S]*?)<\/h1>/gi, (_match, attrs, text) =>- `<h2${attrs}>${unescapeHtml(text)}</h2>`);-}diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.tsindex 6e4528f32b..4877124107 100644--- a/packages/commons/src/lib/markdown_renderer.spec.ts+++ b/packages/commons/src/lib/markdown_renderer.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { CustomMarkdownRenderer, extractCodeBlocks, renderToHtml } from "./markdown_renderer.js";+import { CustomMarkdownRenderer, demoteHeadings, extractCodeBlocks, renderToHtml } from "./markdown_renderer.js";import { DEFAULT_TASK_STATES, DONE_TASK_STATE, NONE_TASK_STATE } from "./task_states.js";/** Identity sanitizer so we can assert the raw rendered HTML. */@@ -452,3 +452,47 @@ describe("renderToHtml", () => {});});});++describe("demoteHeadings", () => {+ /** Identity decoder — keeps the heading text verbatim. */+ const verbatim = (s: string) => s;++ it("leaves content untouched when there is no <h1>", () => {+ expect(demoteHeadings("<h2>A</h2><h3>B</h3>", "Title", verbatim)).toBe("<h2>A</h2><h3>B</h3>");+ });++ it("strips the leading <h1> that duplicates the title without shifting the rest", () => {+ // The common case: title removed, content already starts at <h2>.+ expect(demoteHeadings("<h1>Title</h1><h2>A</h2><h3>B</h3>", "Title", verbatim))+ .toBe("<h2>A</h2><h3>B</h3>");+ });++ it("shifts the whole hierarchy down one level when a content <h1> remains", () => {+ // Top-level <h1> and nested <h2> stay distinct instead of both becoming <h2>.+ expect(demoteHeadings("<h1>A</h1><h2>B</h2><h3>C</h3>", "Title", verbatim))+ .toBe("<h2>A</h2><h3>B</h3><h4>C</h4>");+ // Title stripped, but a remaining content <h1> still triggers the shift.+ expect(demoteHeadings("<h1>Title</h1><h1>Chapter</h1><h2>Section</h2>", "Title", verbatim))+ .toBe("<h2>Chapter</h2><h3>Section</h3>");+ });++ it("clamps at <h6> since there is no <h7>", () => {+ expect(demoteHeadings("<h1>A</h1><h5>E</h5><h6>F</h6>", "Title", verbatim))+ .toBe("<h2>A</h2><h6>E</h6><h6>F</h6>");+ });++ it("matches headings with inline markup and carries attributes onto the demoted <h2>", () => {+ expect(demoteHeadings("<h1>Chapter <em>One</em></h1><h2>Intro</h2>", "Title", verbatim))+ .toBe("<h2>Chapter <em>One</em></h2><h3>Intro</h3>");+ expect(demoteHeadings(`<h1 id="top">Main</h1><h2>Sub</h2>`, "Title", verbatim))+ .toBe(`<h2 id="top">Main</h2><h3>Sub</h3>`);+ });++ it("applies the injected decoder to the demoted <h1> text and the title comparison only", () => {+ const upper = (s: string) => s.toUpperCase();+ // The decoder runs on the <h1> text but not on shifted sub-headings.+ expect(demoteHeadings("<h1>a</h1><h2>b</h2>", "Title", upper)).toBe("<h2>A</h2><h3>b</h3>");+ // The decoder is also used when comparing the first <h1> against the title.+ expect(demoteHeadings("<h1>a</h1>", "A", upper)).toBe("");+ });+});diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex a73c9a4549..9dcecaaedb 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -1,7 +1,6 @@import { Marked, Renderer, type Token, type Tokens } from "marked";import markedFootnote from "marked-footnote";-import { demoteHeadings } from "./heading_demotion.js";import { DEFAULT_TASK_STATES, type TaskStateDef } from "./task_states.js";type TaskListItem = Tokens.ListItem & { _taskState?: string };@@ -183,6 +182,68 @@ function getNormalizedMimeFromMarkdownLanguage(language: string | undefined): streturn MIME_TYPE_AUTO;}+/** Decodes HTML entities in heading text; supplied by each {@link demoteHeadings} caller. */+export type EntityDecoder = (str: string) => string;++/**+ * Trilium reserves `<h1>` for the note title and the editor only supports+ * `<h2>`–`<h6>`. When rendered/imported content starts its hierarchy at `<h1>`,+ * naively demoting every `<h1>` to `<h2>` while leaving `<h2>`–`<h6>` untouched+ * collapses distinct levels onto the same `<h2>`, flattening the nesting (#8383).+ *+ * This strips the leading `<h1>` if it duplicates the title, then — if a content+ * `<h1>` still remains — shifts the whole hierarchy down one level so the author's+ * structure is preserved.+ *+ * The entity decoder is injected so each call-site keeps its own `unescapeHtml`+ * semantics: the markdown renderer (here) decodes numeric/hex/named entities, while+ * the HTML importer decodes only the five basic ones (matching `api.unescapeHtml`).+ */+export function demoteHeadings(+ content: string,+ title: string,+ unescapeHtml: EntityDecoder+): string {+ content = stripDuplicateTitleHeading(content, title, unescapeHtml);++ // If a content <h1> still remains, the hierarchy starts at level 1: shift every+ // heading down one level (clamping at <h6>) so nesting is preserved instead of+ // collapsing distinct <h1>/<h2> levels onto the same <h2>.+ if (/<h1[^>]*>[\s\S]*?<\/h1>/i.test(content)) {+ content = shiftHeadingsDown(content, unescapeHtml);+ }++ return content;+}++/** Removes the first `<h1>` when its (decoded) text equals the note title. */+function stripDuplicateTitleHeading(+ content: string,+ title: string,+ unescapeHtml: EntityDecoder+): string {+ // No `g` flag: only the very first <h1> is a title candidate. `[\s\S]*?` (not+ // `[^<]*`) so headings with inline markup or attributes still match.+ return content.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/i, (match, text: string) =>+ unescapeHtml(text).trim() === title.trim() ? "" : match+ );+}++/**+ * Shifts `<h2>`–`<h5>` to `<h3>`–`<h6>` and the remaining `<h1>` to `<h2>`+ * (preserving attributes and decoding text). `<h6>` stays put — there is no `<h7>`.+ */+function shiftHeadingsDown(content: string, unescapeHtml: EntityDecoder): string {+ // Shift the sub-headings first so the <h1>→<h2> demotion below isn't re-shifted.+ // `[\s\S]*?` matches headings containing inline markup; the captured attributes+ // are carried over to the demoted <h2>.+ return content+ .replace(/<(\/?)h([2-5])\b([^>]*)>/gi, (_match, slash, level, rest) =>+ `<${slash}h${Number(level) + 1}${rest}>`)+ .replace(/<h1([^>]*)>([\s\S]*?)<\/h1>/gi, (_match, attrs, text) =>+ `<h2${attrs}>${unescapeHtml(text)}</h2>`);+}+export function extractCodeBlocks(text: string): { processedText: string; placeholderMap: Map<string, string> } {const codeMap = new Map<string, string>();let id = 0;diff --git a/packages/trilium-core/src/services/import/utils.ts b/packages/trilium-core/src/services/import/utils.tsindex 2f4d069ff4..b3c8521805 100644--- a/packages/trilium-core/src/services/import/utils.ts+++ b/packages/trilium-core/src/services/import/utils.ts@@ -1,4 +1,4 @@-import { demoteHeadings } from "@triliumnext/commons/src/lib/heading_demotion.js";+import { demoteHeadings } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { unescapeHtml } from "../utils";