Skip to content

Build your personal knowledge base with Trilium Notes

refactor(markdown): extract shared heading-demotion into commons

Elian Doran2d7e101ffc16
diff --git a/packages/commons/src/lib/heading_demotion.spec.ts b/packages/commons/src/lib/heading_demotion.spec.ts
new file mode 100644
index 0000000000..0ec404ab68
--- /dev/null
+++ b/packages/commons/src/lib/heading_demotion.spec.ts
@@ -0,0 +1,47 @@
+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.ts
new file mode 100644
index 0000000000..9031ddb038
--- /dev/null
+++ b/packages/commons/src/lib/heading_demotion.ts
@@ -0,0 +1,61 @@
+/** 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.ts b/packages/commons/src/lib/markdown_renderer.ts
index 9e6e0d594e..a73c9a4549 100644
--- a/packages/commons/src/lib/markdown_renderer.ts
+++ b/packages/commons/src/lib/markdown_renderer.ts
@@ -1,6 +1,7 @@
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 };
@@ -182,49 +183,6 @@ function getNormalizedMimeFromMarkdownLanguage(language: string | undefined): st
return MIME_TYPE_AUTO;
}
-function handleH1(content: string, title: string): string {
- // 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[^>]*>[\s\S]*?<\/h1>/i.test(content)) {
- content = shiftHeadingsDown(content);
- }
-
- return content;
-}
-
-/** 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. `[\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 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>
- * (preserving attributes and 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.
- // `[\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;
@@ -423,7 +381,7 @@ export function renderToHtml(content: string, title: string, options: RenderToHt
// h1 handling needs to come before sanitization.
if (options.demoteH1 !== false) {
- html = handleH1(html, title);
+ html = demoteHeadings(html, title, unescapeHtml);
}
html = options.sanitize(html);
diff --git a/packages/trilium-core/src/services/import/utils.ts b/packages/trilium-core/src/services/import/utils.ts
index 01f77b04d4..2f4d069ff4 100644
--- a/packages/trilium-core/src/services/import/utils.ts
+++ b/packages/trilium-core/src/services/import/utils.ts
@@ -1,46 +1,12 @@
+import { demoteHeadings } from "@triliumnext/commons/src/lib/heading_demotion.js";
+
import { unescapeHtml } from "../utils";
function handleH1(content: string, title: string) {
- // 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[^>]*>[\s\S]*?<\/h1>/i.test(content)) {
- content = shiftHeadingsDown(content);
- }
-
- 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. `[\s\S]*?` (not
- // `[^<]*`) so headings with inline markup or attributes still match.
- return content.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/i, (match, text) =>
- unescapeHtml(text).trim() === title.trim() ? "" : match
- );
-}
-
-/**
- * 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>
- * (preserving attributes and 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.
- // `[\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>`);
+ // Reserve <h1> for the note title and shift the content hierarchy to fit the
+ // editor's <h2>–<h6> range (see #8383). Pass our own `unescapeHtml`, which —
+ // unlike the markdown renderer's — only decodes the five basic HTML entities.
+ return demoteHeadings(content, title, unescapeHtml);
}
function extractHtmlTitle(content: string): string | null {