rob-revisited/ide/ui/js/board-md.js

218 lines
11 KiB
JavaScript

// The Markdown of the Board's cards (GFM, what the issue trackers speak), rendered safely: headings, paragraphs whose line breaks
// are kept, bold / italic / strikethrough, <u>, <mark>, <span style="color:#rrggbb">, `code`, code blocks, quotes (nested), lists
// (nested, numbered, [ ] / [x] tasks), tables (aligned), rules, links (http(s), mailto) and pictures (http(s), data:image, and
// attachment:<name>: a picture of the card). parse() makes a tree of plain objects (tested with node), toDom() builds it with
// DOM nodes only from an allow-list: no HTML of the text is ever interpreted, no script, style, event handler or javascript: URL.
const TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'b', 'i', 's', 'u', 'mark', 'span', 'code', 'pre', 'blockquote', 'ul', 'ol', 'li',
'table', 'thead', 'tbody', 'tr', 'th', 'td', 'hr', 'a', 'img', 'input']);
const node = (tag, attrs = {}, kids = []) => ({ tag, attrs, kids });
/** a link's address when it may be one (http, https, mailto), else null */
export function safeHref(url) {
const u = String(url || '').trim();
return /^(https?:\/\/|mailto:)/i.test(u) && !/[\s<>"]/.test(u) ? u : null;
}
/** a picture's address when it may be one (http, https, data:image of a picture type, attachment:<name>), else null */
export function safeSrc(url) {
const u = String(url || '').trim();
if (/^attachment:[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(u)) return u;
if (/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/i.test(u)) return u;
return /^https?:\/\//i.test(u) && !/[\s<>"]/.test(u) ? u : null;
}
// ---- inline ----
const PAIRS = [['**', 'b'], ['__', 'b'], ['~~', 's'], ['*', 'i'], ['_', 'i']];
/** the inline Markdown of a paragraph, a heading or a cell as a list of nodes and strings */
export function parseInline(text) {
const out = [];
let buf = '';
const push = (n) => { if (buf) { out.push(buf); buf = ''; } out.push(n); };
let i = 0;
while (i < text.length) {
const rest = text.slice(i);
const c = text[i];
let m;
if (c === '\\' && i + 1 < text.length && /[!-/:-@[-`{-~]/.test(text[i + 1])) { buf += text[i + 1]; i += 2; continue; }
if (c === '\n') { push(node('br')); i++; continue; }
if (c === '`' && (m = /^(`+)([\s\S]*?[^`])\1(?!`)/.exec(rest))) { push(node('code', {}, [m[2].replace(/^ (.*) $/, '$1')])); i += m[0].length; continue; }
if (c === '!' && (m = /^!\[([^\]\n]*)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/.exec(rest))) {
const src = safeSrc(m[2]);
push(src ? node('img', { src, alt: m[1] }) : m[1]);
i += m[0].length; continue;
}
if (c === '[' && (m = /^\[((?:\\.|[^\]\\])*)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/.exec(rest))) {
const href = safeHref(m[2]);
const kids = parseInline(m[1]);
if (href) push(node('a', { href }, kids)); else { if (buf) { out.push(buf); buf = ''; } out.push(...kids); }
i += m[0].length; continue;
}
if (c === '<') {
if ((m = /^<(https?:\/\/[^\s<>]+)>/.exec(rest))) { push(node('a', { href: m[1] }, [m[1]])); i += m[0].length; continue; }
if ((m = /^<br\s*\/?>/i.exec(rest))) { push(node('br')); i += m[0].length; continue; }
if ((m = /^<(u|mark)>([\s\S]*?)<\/\1>/i.exec(rest))) { push(node(m[1].toLowerCase(), {}, parseInline(m[2]))); i += m[0].length; continue; }
if ((m = /^<span style="color:\s*(#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3})\s*;?">([\s\S]*?)<\/span>/i.exec(rest))) { push(node('span', { color: m[1] }, parseInline(m[2]))); i += m[0].length; continue; }
}
if ((c === 'h' || c === 'H') && (m = /^https?:\/\/[^\s<>()]*[^\s<>().,;:!?'"]/.exec(rest)) && !/[A-Za-z0-9]$/.test(buf)) { push(node('a', { href: m[0] }, [m[0]])); i += m[0].length; continue; }
let done = false;
for (const [mark, tag] of PAIRS) {
if (!rest.startsWith(mark) || /\s/.test(text[i + mark.length] || ' ')) continue;
if (mark[0] === '_' && /[A-Za-z0-9]/.test(text[i - 1] || '')) continue; // snake_case stays text
let end = i + mark.length;
while ((end = text.indexOf(mark, end + 1)) !== -1) {
if (!/\s/.test(text[end - 1]) && !(mark.length === 1 && text[end + 1] === mark) && !(mark[0] === '_' && /[A-Za-z0-9]/.test(text[end + mark.length] || ''))) break;
}
if (end === -1) continue;
push(node(tag, {}, parseInline(text.slice(i + mark.length, end))));
i = end + mark.length;
done = true;
break;
}
if (done) continue;
buf += c;
i++;
}
if (buf) out.push(buf);
return out;
}
// ---- blocks ----
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([\w+-]*)/;
const HEADING = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
const RULE = /^ {0,3}([-*_])(\s*\1){2,}\s*$/;
const QUOTE = /^ {0,3}> ?/;
const ITEM = /^( *)([-*+]|\d{1,9}[.)])(\s+|$)/;
const TABLE_SEP = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
const cells = (line) => {
const s = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '');
const out = [];
let cur = '';
for (let i = 0; i < s.length; i++) {
if (s[i] === '\\' && s[i + 1] === '|') { cur += '\\|'; i++; } else if (s[i] === '|') { out.push(cur.trim()); cur = ''; } else cur += s[i];
}
out.push(cur.trim());
return out;
};
const startsBlock = (line, next) => FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || ITEM.test(line)
|| (line.includes('|') && next !== undefined && TABLE_SEP.test(next) && next.includes('-'));
/** the block Markdown as a list of nodes */
export function parse(text) {
const lines = String(text || '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').split('\n');
return blocks(lines);
}
function blocks(lines) {
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
let m;
if (!line.trim()) { i++; continue; }
if ((m = FENCE.exec(line))) {
const code = [];
for (i++; i < lines.length && !lines[i].trim().startsWith(m[1]); i++) code.push(lines[i]);
i++;
out.push(node('pre', {}, [node('code', m[2] ? { lang: m[2] } : {}, [code.join('\n')])]));
} else if ((m = HEADING.exec(line))) {
out.push(node('h' + m[1].length, {}, parseInline(m[2])));
i++;
} else if (RULE.test(line)) {
out.push(node('hr'));
i++;
} else if (QUOTE.test(line)) {
const inner = [];
for (; i < lines.length && (QUOTE.test(lines[i]) || (lines[i].trim() && !startsBlock(lines[i], lines[i + 1]) && inner.length && inner[inner.length - 1].trim())); i++) inner.push(lines[i].replace(QUOTE, ''));
out.push(node('blockquote', {}, blocks(inner)));
} else if ((m = ITEM.exec(line))) {
const ordered = /\d/.test(m[2]);
const list = node(ordered ? 'ol' : 'ul', ordered && parseInt(m[2], 10) !== 1 ? { start: parseInt(m[2], 10) } : {});
const base = m[1].length;
while (i < lines.length) {
const im = ITEM.exec(lines[i]);
if (!im || im[1].length !== base || /\d/.test(im[2]) !== ordered) break;
const width = im[1].length + im[2].length + Math.max(1, Math.min(4, im[3].length || 1));
const content = [lines[i].slice(im[0].length)];
for (i++; i < lines.length; i++) {
const l = lines[i];
if (!l.trim()) { // a blank line: the item goes on only if what follows is indented under it
if (i + 1 < lines.length && lines[i + 1].trim() && /^ */.exec(lines[i + 1])[0].length >= width) { content.push(''); continue; }
break;
}
const indent = /^ */.exec(l)[0].length;
if (indent >= width || (indent > base && ITEM.test(l))) content.push(l.slice(Math.min(indent, width)));
else if (!startsBlock(l, lines[i + 1]) && content[content.length - 1].trim()) content.push(l.trim()); // a lazy continuation
else break;
}
let kids = blocks(content);
if (kids.length && kids[0].tag === 'p' && !content.includes('')) kids = [...kids[0].kids, ...kids.slice(1)]; // tight items
const task = typeof kids[0] === 'string' ? /^\[( |x|X)\]\s+/.exec(kids[0]) : null;
if (task) kids = [node('input', { type: 'checkbox', checked: task[1] !== ' ' }), kids[0].slice(task[0].length), ...kids.slice(1)];
list.kids.push(node('li', {}, kids));
}
out.push(list);
} else if (line.includes('|') && i + 1 < lines.length && TABLE_SEP.test(lines[i + 1]) && lines[i + 1].includes('-')) {
const head = cells(line);
const align = cells(lines[i + 1]).map((c) => (c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : c.startsWith(':') ? 'left' : ''));
const row = (cs, tag) => node('tr', {}, head.map((_, k) => node(tag, align[k] ? { align: align[k] } : {}, parseInline((cs[k] || '').replace(/\\\|/g, '|')))));
const body = [];
for (i += 2; i < lines.length && lines[i].trim() && lines[i].includes('|'); i++) body.push(row(cells(lines[i]), 'td'));
out.push(node('table', {}, [node('thead', {}, [row(head, 'th')]), node('tbody', {}, body)]));
} else {
const para = [];
for (; i < lines.length && lines[i].trim() && !(para.length && startsBlock(lines[i], lines[i + 1])); i++) para.push(lines[i].trim());
out.push(node('p', {}, parseInline(para.join('\n'))));
}
}
return out;
}
// ---- DOM ----
/**
* The tree as DOM nodes. hooks.onLink(url) opens a link; hooks.picture(name) is a Promise of a data: address of the card's picture
* (attachment:<name>); hooks.onImage(img, src) for a click on a picture.
*/
export function toDom(tree, hooks = {}) {
const make = (n) => {
if (typeof n === 'string') return document.createTextNode(n);
if (!TAGS.has(n.tag)) return document.createTextNode('');
const e = document.createElement(n.tag);
const a = n.attrs || {};
if (n.tag === 'a') {
e.href = '#';
e.title = a.href;
e.addEventListener('click', (ev) => { ev.preventDefault(); hooks.onLink?.(a.href); });
} else if (n.tag === 'img') {
e.alt = a.alt || '';
e.loading = 'lazy';
if (a.src.startsWith('attachment:')) {
e.dataset.attachment = a.src.slice(11);
hooks.picture?.(a.src.slice(11)).then((url) => { e.src = url; }, () => { e.classList.add('missing'); e.alt = `${a.alt || ''} (${a.src.slice(11)})`; });
} else e.src = a.src;
e.addEventListener('click', () => hooks.onImage?.(e, a.src));
} else if (n.tag === 'input') {
e.type = 'checkbox';
e.checked = !!a.checked;
e.disabled = true;
} else if (n.tag === 'span' && a.color) e.style.color = a.color;
else if ((n.tag === 'td' || n.tag === 'th') && a.align) e.style.textAlign = a.align;
else if (n.tag === 'ol' && a.start) e.start = a.start;
for (const k of n.kids || []) e.append(make(k));
return e;
};
return tree.map(make);
}
/** the start of a description as plain text (for a card's tile) */
export function plainText(md) {
const text = (n) => (typeof n === 'string' ? n : n.tag === 'br' ? '\n' : n.tag === 'img' ? '' : (n.kids || []).map(text).join(''));
return parse(md).map((b) => (b.tag === 'ul' || b.tag === 'ol' ? b.kids.map((li) => '• ' + text(li)).join('\n') : text(b))).join('\n');
}