30 lines
1.5 KiB
JavaScript
30 lines
1.5 KiB
JavaScript
(() => {
|
|
'use strict';
|
|
// Small inline-only dialect: no HTML, images, macros or remote rendering.
|
|
function render(node, source, links = true, depth = 0) {
|
|
node.replaceChildren();
|
|
if (depth > 8) { node.textContent=source; return; }
|
|
const pattern=/\\([\\`*_\[\]~])|(`+)([^`]+)\2|\*\*(.+?)\*\*|__(.+?)__|~~(.+?)~~|\*([^*]+)\*|_([^_]+)_|\[([^\]]+)\]\(([^\s)]+)\)/g;
|
|
let offset=0;
|
|
for(const m of source.matchAll(pattern)) {
|
|
node.append(document.createTextNode(source.slice(offset,m.index)));
|
|
if(m[1]){node.append(document.createTextNode(m[1]));offset=m.index+m[0].length;continue;}
|
|
let tag,text;
|
|
if(m[2]) {tag='code';text=m[3];} else if(m[4]||m[5]) {tag='strong';text=m[4]||m[5];}
|
|
else if(m[6]) {tag='del';text=m[6];} else if(m[7]||m[8]) {tag='em';text=m[7]||m[8];}
|
|
else {tag='span';text=m[9];if(links&&safeReference(m[10]))tag='a';}
|
|
const child=document.createElement(tag);
|
|
if(tag==='a') {child.href=m[10];child.rel='noopener noreferrer';}
|
|
if(tag==='code')child.textContent=text;else render(child,text,false,depth+1);
|
|
node.append(child);offset=m.index+m[0].length;
|
|
}
|
|
node.append(document.createTextNode(source.slice(offset)));
|
|
}
|
|
function safeReference(ref) {
|
|
if(!ref||/[\\\s\x00-\x1f]/.test(ref))return false;
|
|
if(ref.startsWith('/')&&!ref.startsWith('//'))return true;
|
|
try {const u=new URL(ref);return ['http:','https:'].includes(u.protocol)&&!u.username&&!u.password;}catch{return false;}
|
|
}
|
|
window.PagesTaskPresentation={render,safeReference};
|
|
})();
|