diff --git a/public/app.js b/public/app.js index 98cd060..1f3323f 100644 --- a/public/app.js +++ b/public/app.js @@ -54,6 +54,39 @@ function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])) } +// Small, dependency-free Markdown -> HTML for a project's README. Everything is escaped first, so no +// raw HTML from the file can run; then a safe subset is formatted. Links only for http(s), open extern. +function renderMarkdown(src) { + const esc = escapeHtml(String(src ?? '').replace(/\r\n?/g, '\n')) + const inline = (s) => s + .replace(/`([^`]+)`/g, (_, c) => `${c}`) + .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, (_, txt, url) => `${txt}`) + .replace(/(^|[^*])\*\*([^*\n]+)\*\*/g, '$1$2') + .replace(/(^|[^*_])[*_]([^*_\n]+)[*_]/g, '$1$2') + const lines = esc.split('\n') + let html = '', i = 0 + const closeList = (stack) => { while (stack.length) html += stack.pop() } + const listStack = [] + while (i < lines.length) { + const line = lines[i] + // fenced code block + if (/^\s*```/.test(line)) { closeList(listStack); i++; const buf = []; while (i < lines.length && !/^\s*```/.test(lines[i])) buf.push(lines[i++]); i++; html += `
${buf.join('\n')}
`; continue } + if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) { closeList(listStack); html += '
'; i++; continue } + const h = line.match(/^(#{1,6})\s+(.*)$/) + if (h) { closeList(listStack); html += `${inline(h[2].trim())}`; i++; continue } + const q = line.match(/^\s*>\s?(.*)$/) // '>' was escaped to > + if (q) { closeList(listStack); const buf = []; let m = q; while (i < lines.length && (m = lines[i].match(/^\s*>\s?(.*)$/))) { buf.push(m[1]); i++ } html += `
${inline(buf.join(' '))}
`; continue } + const li = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/) + if (li) { const ordered = /\d/.test(li[2]); const want = ordered ? '' : ''; if (listStack[listStack.length - 1] !== want) { closeList(listStack); html += ordered ? '
    ' : '