Improve line break handling in markdownToHTML function

This commit is contained in:
2026-01-31 16:40:01 +01:00
parent 4ae7f82288
commit 15993ed33c

View File

@@ -191,22 +191,45 @@ 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)
const linesWithHtml = html.split("\n"); const linesWithHtml = html.split("\n");
const htmlLines = []; const htmlLines = [];
let emptyCount = 0;
let seenNonEmpty = false;
for (let i = 0; i < linesWithHtml.length; i += 1) { for (let i = 0; i < linesWithHtml.length; i += 1) {
const line = linesWithHtml[i] ?? ""; const line = linesWithHtml[i] ?? "";
const nextLine = i + 1 < linesWithHtml.length ? linesWithHtml[i + 1] : null;
const isEmpty = line.trim().length === 0; const isEmpty = line.trim().length === 0;
const nextIsEmpty = nextLine !== null ? nextLine.trim().length === 0 : false;
if (isEmpty) { if (isEmpty) {
htmlLines.push("<br />"); emptyCount += 1;
continue; continue;
} }
htmlLines.push(line); if (seenNonEmpty) {
if (nextLine !== null && !nextIsEmpty) { if (emptyCount === 0) {
htmlLines.push("<br />");
} else {
const extraBreaks = Math.max(0, emptyCount - 1);
for (let j = 0; j < extraBreaks; j += 1) {
htmlLines.push("<br />"); htmlLines.push("<br />");
} }
} }
} else if (emptyCount > 0) {
const extraBreaks = Math.max(0, emptyCount - 1);
for (let j = 0; j < extraBreaks; j += 1) {
htmlLines.push("<br />");
}
}
emptyCount = 0;
htmlLines.push(line);
seenNonEmpty = true;
}
if (emptyCount > 0) {
const extraBreaks = Math.max(0, emptyCount - 1);
for (let j = 0; j < extraBreaks; j += 1) {
htmlLines.push("<br />");
}
}
html = htmlLines.join(""); html = htmlLines.join("");
// 7) Restore code blocks with header + copy button // 7) Restore code blocks with header + copy button