Handle multi-paragraph code blocks

This ain't going to be fun if the HTML gets messier in the future
pull/54/head
Lim Chee Aun 2023-02-16 21:51:22 +08:00
rodzic 9011b9da35
commit 7aba448f42
2 zmienionych plików z 38 dodań i 0 usunięć

Wyświetl plik

@ -286,6 +286,8 @@
.status .content p {
/* 12px = 75% of 16px */
margin-block: min(0.75em, 12px);
white-space: pre-wrap;
tab-size: 2;
}
.status .content p:first-child {
margin-block-start: 0;
@ -894,6 +896,7 @@ a.card:is(:hover, :focus) {
transparent 160px
);
white-space: pre-wrap;
line-height: 1.2;
}
.status .content p code {

Wyświetl plik

@ -43,6 +43,41 @@ function enhanceContent(content, opts = {}) {
block.replaceWith(pre);
});
// Convert multi-paragraph code blocks to <pre><code>code</code></pre>
const paragraphs = Array.from(dom.querySelectorAll('p'));
// Filter out paragraphs with ``` in beginning only
const codeBlocks = paragraphs.filter((p) => /^```/g.test(p.innerText));
// For each codeBlocks, get all paragraphs until the last paragraph with ``` at the end only
codeBlocks.forEach((block) => {
const nextParagraphs = [block];
let hasCodeBlock = false;
do {
const next = block.nextElementSibling;
if (next && next.tagName === 'P') {
if (/```$/g.test(next.innerText)) {
nextParagraphs.push(next);
hasCodeBlock = true;
break;
} else {
nextParagraphs.push(next);
}
} else {
break;
}
} while (true);
if (hasCodeBlock) {
const pre = document.createElement('pre');
nextParagraphs.forEach((p) => {
// Replace <br /> with newlines
p.querySelectorAll('br').forEach((br) => br.replaceWith('\n'));
});
const codeText = nextParagraphs.map((p) => p.innerHTML).join('\n\n');
pre.innerHTML = `<code>${codeText}</code>`;
block.replaceWith(pre);
nextParagraphs.forEach((p) => p.remove());
}
});
// INLINE CODE
// ===========
// Convert `code` to <code>code</code>