Refactor line break handling in markdown.js

This commit is contained in:
2026-01-31 16:36:31 +01:00
parent c2a6035f3d
commit 4ae7f82288

View File

@@ -189,31 +189,25 @@ export function markdownToHTML(text) {
}); });
// 6) Convert line-breaks to <br /> for NON-code content (preserve blank lines) // 6) Convert line-breaks to <br /> for NON-code content (preserve blank lines)
html = html.replace(/\n/g, '<br />'); const linesWithHtml = html.split("\n");
const htmlLines = [];
for (let i = 0; i < linesWithHtml.length; i += 1) {
const line = linesWithHtml[i] ?? "";
const nextLine = i + 1 < linesWithHtml.length ? linesWithHtml[i + 1] : null;
const isEmpty = line.trim().length === 0;
const nextIsEmpty = nextLine !== null ? nextLine.trim().length === 0 : false;
// 6.1) Trim breaks around block elements (headings/lists/etc.) to avoid double spacing if (isEmpty) {
const brPattern = "<br\\s*\\/?>"; htmlLines.push("<br />");
const blockPattern = "(?:h[1-4]|hr|table|ul|ol|blockquote)"; continue;
html = html }
.replace(
new RegExp(`(${brPattern}\\s*)+(<(?:${blockPattern})\\b[^>]*>)`, "g"),
"$2"
)
.replace(
new RegExp(`(<\\/(?:${blockPattern})>)(?:\\s*${brPattern})+`, "g"),
"$1"
);
// 6.2) Trim breaks around code blocks htmlLines.push(line);
html = html if (nextLine !== null && !nextIsEmpty) {
.replace(new RegExp(`${brPattern}\\s*(?=<div class="md-codeblock"\\b)`, "g"), "") htmlLines.push("<br />");
.replace( }
new RegExp( }
`(<div class="md-codeblock"[^>]*>[\\s\\S]*?<\\/div>)\\s*(?:${brPattern}\\s*)+`, html = htmlLines.join("");
"g"
),
"$1"
);
// 7) Restore code blocks with header + copy button // 7) Restore code blocks with header + copy button
html = html.replace(/@@CODEBLOCK(\d+)@@/g, (_, idx) => { html = html.replace(/@@CODEBLOCK(\d+)@@/g, (_, idx) => {