1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231/**
* Markdown renderer - converts markdown to HTML
*/
function escapeHtml(text: string): string {
if (!text) return '';
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
// Callout types with their styling (background, border, icon)
const CALLOUT_TYPES: Record<string, { bg: string; border: string; color: string; label: string }> = {
tip: { bg: '#eff6ff', border: '#3b82f6', color: '#1e3a8a', label: 'Tip' },
note: { bg: '#f3f4f6', border: '#6b7280', color: '#1f2937', label: 'Note' },
important: { bg: '#fef3c7', border: '#f59e0b', color: '#713f12', label: 'Important' },
warning: { bg: '#fee2e2', border: '#ef4444', color: '#7f1d1d', label: 'Warning' },
success: { bg: '#dcfce7', border: '#22c55e', color: '#14532d', label: 'Success' },
};
// Convert GitHub blob URLs to raw URLs (for embedded images)
// e.g. https://github.com/Org/Repo/blob/SHA/path/file.png → https://raw.githubusercontent.com/Org/Repo/SHA/path/file.png
function rewriteGitHubBlobUrl(url: string): string {
return url.replace(
/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/,
'https://raw.githubusercontent.com/$1/$2/$3/$4'
);
}
export function renderMarkdown(md: string): string {
let html = md;
// First pass: handle callout code blocks (```tip, ```important, ```warning, ```note, ```success)
// Render them as styled callouts before the generic code block handler runs
const callouts: string[] = [];
html = html.replace(/```(tip|note|important|warning|success)\n([\s\S]*?)```/g, (_, type, content) => {
const cfg = CALLOUT_TYPES[type];
// Render markdown inside callout content (recursively, simply)
const inner = renderInlineMarkdown(content.trim());
const calloutHtml = `<div class="md-callout md-callout-${type}" style="background:${cfg.bg};border-left:4px solid ${cfg.border};color:${cfg.color};padding:12px 16px;margin:16px 0;border-radius:6px;">${inner}</div>`;
callouts.push(calloutHtml);
return `%%CALLOUT${callouts.length - 1}%%`;
});
// Preserve code blocks first (replace with placeholders)
const codeBlocks: string[] = [];
html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
codeBlocks.push(`<pre><code class="language-${lang || 'text'}">${escapeHtml(code.trim())}</code></pre>`);
return `%%CODEBLOCK${codeBlocks.length - 1}%%`;
});
// Preserve inline code
const inlineCode: string[] = [];
html = html.replace(/`([^`]+)`/g, (_, code) => {
inlineCode.push(`<code>${escapeHtml(code)}</code>`);
return `%%INLINECODE${inlineCode.length - 1}%%`;
});
// Remove HTML comments (but keep other HTML)
html = html.replace(/<!--[\s\S]*?-->/g, '');
// Collect reference definitions: [ref]: url "title"
const refs: Record<string, { url: string; title?: string }> = {};
html = html.replace(/^\[([^\]]+)\]:\s*(\S+)(?:\s+"([^"]*)")?$/gm, (_, ref, url, title) => {
refs[ref.toLowerCase()] = { url: url.trim(), title };
return '';
});
// Handle images:  - must come before links
html = html.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, alt, url, title) => {
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
return `<img src="${url}" alt="${escapeHtml(alt)}"${titleAttr} style="max-width:100%;">`;
});
// Reference-style images: ![alt][ref] or ![alt][]
html = html.replace(/!\[([^\]]*)\]\[([^\]]*)\]/g, (_, alt, ref) => {
const key = (ref || alt).toLowerCase();
const r = refs[key];
if (r) {
const titleAttr = r.title ? ` title="${escapeHtml(r.title)}"` : '';
return `<img src="${r.url}" alt="${escapeHtml(alt)}"${titleAttr} style="max-width:100%;">`;
}
return `![${alt}]`;
});
// Tables: detect by |---|---| pattern
html = html.replace(/^(\|.+\|)\n(\|[-:\s|]+\|)\n((?:\|.+\|\n?)+)/gm, (_, header, sep, body) => {
const alignments: string[] = [];
sep.split('|').filter(Boolean).forEach((cell: string) => {
const c = cell.trim();
if (c.startsWith(':') && c.endsWith(':')) alignments.push('center');
else if (c.endsWith(':')) alignments.push('right');
else alignments.push('left');
});
const parseRow = (row: string, tag: string) => {
const cells = row.split('|').filter(Boolean);
return `<tr>${cells.map((c: string, i: number) =>
`<${tag} style="text-align:${alignments[i] || 'left'}">${c.trim()}</${tag}>`
).join('')}</tr>`;
};
const headerRow = parseRow(header, 'th');
const bodyRows = body.trim().split('\n').map((r: string) => parseRow(r, 'td')).join('');
return `<table><thead>${headerRow}</thead><tbody>${bodyRows}</tbody></table>`;
});
// Headers (process inline markdown after)
html = html.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>');
html = html.replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>');
html = html.replace(/^####\s+(.+)$/gm, '<h4>$1</h4>');
html = html.replace(/^###\s+(.+)$/gm, '<h3>$1</h3>');
html = html.replace(/^##\s+(.+)$/gm, '<h2>$1</h2>');
html = html.replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
// Horizontal rules
html = html.replace(/^[-*_]{3,}\s*$/gm, '<hr>');
// Blockquotes (handle multiple consecutive lines)
html = html.replace(/^>\s*(.*)$/gm, '<blockquote>$1</blockquote>');
html = html.replace(/<\/blockquote>\n<blockquote>/g, '<br>');
// Bold and italic (must handle ** before *)
html = html.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
html = html.replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, '<em>$1</em>');
html = html.replace(/___(.+?)___/g, '<strong><em>$1</em></strong>');
html = html.replace(/__(.+?)__/g, '<strong>$1</strong>');
html = html.replace(/(?<!_)_([^_\n]+)_(?!_)/g, '<em>$1</em>');
// Strikethrough
html = html.replace(/~~(.+?)~~/g, '<del>$1</del>');
// Links: [text](url "title")
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, text, url, title) => {
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
return `<a href="${url}"${titleAttr} rel="noopener">${text}</a>`;
});
// Reference-style links: [text][ref] or [text][]
html = html.replace(/\[([^\]]+)\]\[([^\]]*)\]/g, (_, text, ref) => {
const key = (ref || text).toLowerCase();
const r = refs[key];
if (r) {
const titleAttr = r.title ? ` title="${escapeHtml(r.title)}"` : '';
return `<a href="${r.url}"${titleAttr} rel="noopener">${text}</a>`;
}
return `[${text}]`;
});
// Task lists: - [ ] or - [x]
html = html.replace(/^(\s*)[-*+]\s+\[( |x)\]\s+(.+)$/gm, (_, indent, checked, text) => {
const isChecked = checked === 'x' ? ' checked disabled' : ' disabled';
return `${indent}<li class="task-list-item"><input type="checkbox"${isChecked}> ${text}</li>`;
});
// Unordered lists
html = html.replace(/^(\s*)[-*+]\s+(.+)$/gm, '$1<li>$2</li>');
// Ordered lists
html = html.replace(/^(\s*)\d+\.\s+(.+)$/gm, '$1<li>$2</li>');
// Wrap consecutive <li> in <ul>
html = html.replace(/(<li[\s>][\s\S]*?<\/li>\n?)+/g, '<ul>$&</ul>');
// Paragraphs
html = html.replace(/\n\n+/g, '</p>\n<p>');
html = '<p>' + html + '</p>';
// Clean up: remove <p> wrapping block elements
const blockTags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'ul', 'ol', 'blockquote', 'hr', 'table', 'div'];
blockTags.forEach(tag => {
html = html.replace(new RegExp(`<p>\\s*(<${tag}[\\s>])`, 'g'), '$1');
html = html.replace(new RegExp(`(</${tag}>)\\s*</p>`, 'g'), '$1');
});
html = html.replace(/<p>\s*(<img\s)/g, '$1');
html = html.replace(/<p>\s*(<a\s[^>]*id=)/g, '$1');
html = html.replace(/<p>\s*<\/p>/g, '');
// Restore code blocks and inline code
codeBlocks.forEach((block, i) => {
html = html.replace(`%%CODEBLOCK${i}%%`, block);
});
inlineCode.forEach((code, i) => {
html = html.replace(`%%INLINECODE${i}%%`, code);
});
// Restore callouts (after paragraph wrapping)
callouts.forEach((callout, i) => {
html = html.replace(`%%CALLOUT${i}%%`, callout);
});
// Strip <p> wrappers around restored block elements
html = html.replace(/<p>\s*(<div\s[^>]*class="md-callout[\s\S]*?<\/div>)\s*<\/p>/g, '$1');
html = html.replace(/<p>\s*(<pre[\s>][\s\S]*?<\/pre>)\s*<\/p>/g, '$1');
// Rewrite GitHub blob URLs in <img> tags to raw URLs (so embedded images actually load)
html = html.replace(/<img\s+([^>]*?)src="([^"]+)"([^>]*?)>/g, (_, before, src, after) => {
return `<img ${before}src="${rewriteGitHubBlobUrl(src)}"${after}>`;
});
return html;
}
// Lightweight inline markdown renderer for callout content
// Supports: bold, italic, links, inline code, line breaks
function renderInlineMarkdown(text: string): string {
let html = text;
// Inline code first
const codes: string[] = [];
html = html.replace(/`([^`]+)`/g, (_, code) => {
codes.push(`<code>${escapeHtml(code)}</code>`);
return ` C${codes.length - 1} `;
});
// Links: [text](url)
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, '<a href="$2" rel="noopener">$1</a>');
// Bold and italic
html = html.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
html = html.replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, '<em>$1</em>');
// Line breaks → <br>
html = html.replace(/\n/g, '<br>');
// Restore inline code
codes.forEach((code, i) => {
html = html.replace(` C${i} `, code);
});
return html;
}