Elffuss BraidHub

utopia-ia/elffuss public

cfebc45fb327 · 1.8 KiBRawPermalink
1// Minimal, SAFE markdown for the chat (Claude Code plugin style): escape ALL
2// the HTML first, then apply a bounded set of transformations.
3// Supports: ``` code blocks, `inline`, **bold**, *italics*, #### headings,
4// - or numbered lists, and line breaks.
5const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
6const SENT = '\u0000'; // sentinel: impossible in normal text. Written as an
7// escape, not as a literal NUL: a literal one makes git treat this source
8// file as BINARY, so it never shows in a diff and `grep` skips it without
9// saying so. The value is identical; only the spelling changes.
10
11export function renderMarkdown(text) {
12 // 1) set the code blocks aside (their insides are never touched)
13 const blocks = [];
14 let t = String(text).replace(/```(\w*)[ \t]*\n?([\s\S]*?)(?:```|$)/g, (_, lang, body) => {
15 blocks.push({ lang, body });
16 return SENT + (blocks.length - 1) + SENT;
17 });
18
19 t = esc(t);
20 t = t.replace(/`([^`\n]+)`/g, '<code>$1</code>');
21 t = t.replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>');
22 t = t.replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,;:!?]|$)/g, '$1<i>$2</i>');
23 t = t.replace(/^#{1,6}\s*(.+)$/gm, '<h4>$1</h4>');
24 t = t.replace(/^\s*[-•]\s+(.+)$/gm, '<li>$1</li>');
25 t = t.replace(/^\s*\d+\.\s+(.+)$/gm, '<li class="num">$1</li>');
26 t = t.replace(/(?:<li[^>]*>.*<\/li>\n?)+/g, m => '<ul>' + m.replace(/\n/g, '') + '</ul>');
27
28 // line breaks: no <br> glued to block-level tags
29 t = t.replace(/\n(?=<(?:ul|h4))/g, '').replace(/(<\/(?:ul|h4)>)\n/g, '$1');
30 t = t.replace(/\n/g, '<br>');
31
32 // 2) put the code blocks back
33 t = t.replace(new RegExp(SENT + '(\\d+)' + SENT, 'g'), (_, i) => {
34 const { lang, body } = blocks[+i];
35 return `<pre class="codeblock">${lang ? `<span class="lang">${esc(lang)}</span>` : ''}<code>${esc(body.replace(/\n$/, ''))}</code></pre>`;
36 });
37 return t;
38}