web/website/node/news-format.mjs

3 lines
1.1 KiB
JavaScript

const esc=v=>String(v).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function inline(text){let result='',from=0;for(const m of text.matchAll(/\[([^\]\n]{1,200})\]\((https:\/\/[^\s)]+)\)/g)){result+=esc(text.slice(from,m.index));let url;try{url=new URL(m[2]);}catch{}result+=url?.protocol==='https:'?'<a class="dispatch-read-more" href="'+esc(url.href)+'" rel="noopener noreferrer">'+esc(m[1])+'</a>':esc(m[0]);from=m.index+m[0].length;}return result+esc(text.slice(from));}
export function renderNewsBody(value){let html='',paragraph=[],list=false;const flush=()=>{if(paragraph.length){html+='<p>'+inline(paragraph.join(' '))+'</p>';paragraph=[];}if(list){html+='</ul>';list=false;}};for(const raw of String(value).replace(/\r/g,'').split('\n')){const line=raw.trim();if(!line){flush();continue;}const heading=line.match(/^#{1,3}\s+(.+)$/),bullet=line.match(/^[-*]\s+(.+)$/);if(heading){flush();html+='<h3>'+inline(heading[1])+'</h3>';}else if(bullet){if(paragraph.length)flush();if(!list){html+='<ul>';list=true;}html+='<li>'+inline(bullet[1])+'</li>';}else{if(list)flush();paragraph.push(line);}}flush();return html;}