Files
WhatIDo/public/js/md.js
T

193 lines
6.3 KiB
JavaScript

(function () {
function esc(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function safeUrl(value) {
const url = String(value || '').trim();
if (/^\/uploads\/[A-Za-z0-9._-]+$/.test(url)) return url;
if (/^https?:\/\/[^\s]+$/i.test(url)) return url;
return '';
}
function thumbUrl(path) {
if (typeof window.thumbSrc === 'function') return window.thumbSrc(path);
if (path.startsWith('/uploads/')) return '/uploads/thumb/' + path.slice('/uploads/'.length);
return path;
}
function inline(raw) {
const codes = [];
let text = String(raw == null ? '' : raw).replace(/`([^`]+)`/g, (m, code) => {
codes.push(code);
return `\u0000${codes.length - 1}\u0000`;
});
text = esc(text);
text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (m, alt, src) => {
const url = safeUrl(src.replace(/&amp;/g, '&'));
if (!url) return alt;
return `<img src="${esc(thumbUrl(url))}" data-img="${esc(url)}" alt="${esc(alt)}" loading="lazy" onerror="this.onerror=null;this.src='${esc(url)}'">`;
});
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => {
const url = safeUrl(href.replace(/&amp;/g, '&'));
if (!url) return label;
const external = /^https?:\/\//i.test(url);
return `<a href="${esc(url)}"${external ? ' target="_blank" rel="noopener noreferrer"' : ''}>${label}</a>`;
});
text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
text = text.replace(/__([^_]+)__/g, '<strong>$1</strong>');
text = text.replace(/~~([^~]+)~~/g, '<del>$1</del>');
text = text.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
text = text.replace(/\u0000(\d+)\u0000/g, (m, index) => `<code>${esc(codes[Number(index)])}</code>`);
return text;
}
function isBlockStart(line) {
return /^\s*$/.test(line)
|| /^```/.test(line)
|| /^#{1,4}\s+/.test(line)
|| /^\s*>\s?/.test(line)
|| /^\s*([-*+]|\d+\.)\s+/.test(line)
|| /^\s*([-*_])\1{2,}\s*$/.test(line);
}
function parseList(lines, start) {
const baseIndent = lines[start].match(/^(\s*)/)[1].length;
const ordered = /^\s*\d+\.\s+/.test(lines[start]);
let html = ordered ? '<ol>' : '<ul>';
let i = start;
while (i < lines.length) {
const line = lines[i];
const match = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/);
if (!match) break;
const indent = match[1].length;
if (indent < baseIndent) break;
if (indent > baseIndent) {
const nested = parseList(lines, i);
html = html.replace(/<\/li>$/, nested.html + '</li>');
i = nested.next;
continue;
}
if (/^\s*\d+\.\s+/.test(line) !== ordered) break;
let content = match[3];
const task = content.match(/^\[( |x|X)\]\s+(.*)$/);
if (task) {
content = `<input type="checkbox" disabled${task[1].toLowerCase() === 'x' ? ' checked' : ''}> ${inline(task[2])}`;
} else {
content = inline(content);
}
html += `<li>${content}</li>`;
i++;
while (i < lines.length) {
const next = lines[i];
if (/^\s*$/.test(next)) break;
if (/^(\s*)([-*+]|\d+\.)\s+/.test(next)) break;
if (next.match(/^\s*/)[0].length <= baseIndent) break;
html = html.replace(/<\/li>$/, ' ' + inline(next.trim()) + '</li>');
i++;
}
}
html += ordered ? '</ol>' : '</ul>';
return { html, next: i };
}
function splitRow(line) {
let row = line.trim();
if (row.startsWith('|')) row = row.slice(1);
if (row.endsWith('|')) row = row.slice(0, -1);
return row.split('|').map(cell => cell.trim());
}
function renderTable(lines, start) {
const head = splitRow(lines[start]);
let i = start + 2;
const rows = [];
while (i < lines.length && lines[i].includes('|') && lines[i].trim()) {
rows.push(splitRow(lines[i]));
i++;
}
const thead = head.map(cell => `<th>${inline(cell)}</th>`).join('');
const tbody = rows.map(row => `<tr>${row.map(cell => `<td>${inline(cell)}</td>`).join('')}</tr>`).join('');
return {
html: `<div class="md-table-wrap"><table><thead><tr>${thead}</tr></thead><tbody>${tbody}</tbody></table></div>`,
next: i,
};
}
function render(markdown) {
const lines = String(markdown == null ? '' : markdown).replace(/\r\n?/g, '\n').split('\n');
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (/^\s*$/.test(line)) { i++; continue; }
const fence = line.match(/^```\s*([\w-]*)\s*$/);
if (fence) {
const code = [];
i++;
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
code.push(lines[i]);
i++;
}
if (i < lines.length) i++;
out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`);
continue;
}
const heading = line.match(/^(#{1,4})\s+(.*)$/);
if (heading) {
const level = heading[1].length;
out.push(`<h${level}>${inline(heading[2])}</h${level}>`);
i++;
continue;
}
if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
out.push('<hr>');
i++;
continue;
}
if (/^\s*>\s?/.test(line)) {
const quote = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^\s*>\s?/, ''));
i++;
}
out.push(`<blockquote>${render(quote.join('\n'))}</blockquote>`);
continue;
}
if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(lines[i + 1]) && lines[i + 1].includes('-')) {
const table = renderTable(lines, i);
out.push(table.html);
i = table.next;
continue;
}
if (/^\s*([-*+]|\d+\.)\s+/.test(line)) {
const list = parseList(lines, i);
out.push(list.html);
i = list.next;
continue;
}
const paragraph = [];
while (i < lines.length && !isBlockStart(lines[i])) {
paragraph.push(lines[i]);
i++;
}
if (!paragraph.length) { i++; continue; }
out.push(`<p>${paragraph.map(inline).join('<br>')}</p>`);
}
return out.join('\n');
}
window.WhatIDoMD = { render, inline, esc, thumbUrl, safeUrl };
})();