import DOMPurify from 'dompurify'; import { Marked } from 'marked'; function escapeHtml(text: string): string { return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); } const markdown = new Marked({ gfm: true, renderer: { html: ({ text }) => escapeHtml(text), // Marked otherwise passes text inside raw inline HTML through unescaped. text: (token) => ('escaped' in token && token.escaped ? escapeHtml(token.text) : false), // Never generate an image element, even in the sanitizer's detached document. image: ({ text }) => escapeHtml(text ? `[Image: ${text}]` : '[Image]'), checkbox: ({ checked }) => (checked ? '☑ ' : '☐ '), }, }); function copyControls( doc: Document, className: 'answer-copy' | 'code-copy', label: string, text: string, ): [HTMLButtonElement, HTMLSpanElement] { const button = doc.createElement('button'); button.type = 'button'; button.className = className; button.textContent = label; const feedback = doc.createElement('span'); feedback.className = 'copy-feedback'; feedback.setAttribute('role', 'status'); button.addEventListener('click', async () => { feedback.textContent = ''; try { const clipboard = doc.defaultView?.navigator.clipboard; if (!clipboard) { feedback.textContent = 'Clipboard unavailable. Select and copy the text manually.'; return; } await clipboard.writeText(text); feedback.textContent = 'Copied.'; } catch { feedback.textContent = 'Could not copy. Select and copy the text manually.'; } }); return [button, feedback]; } export function renderAnswer(target: HTMLElement, text: string): void { if (!text.trim()) { target.replaceChildren(); return; } const content = DOMPurify.sanitize(markdown.parse(text, { async: false }), { ALLOWED_TAGS: [ 'a', 'blockquote', 'br', 'code', 'del', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'li', 'ol', 'p', 'pre', 'strong', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'ul', ], ALLOWED_ATTR: ['align', 'class', 'href', 'start', 'title'], ALLOW_ARIA_ATTR: false, ALLOW_DATA_ATTR: false, RETURN_DOM_FRAGMENT: true, }); for (const link of content.querySelectorAll('a')) { const url = URL.parse(link.getAttribute('href') ?? ''); if (!url || (url.protocol !== 'https:' && url.protocol !== 'http:') || url.username || url.password) { link.replaceWith(...link.childNodes); continue; } link.href = url.href; link.target = '_blank'; link.rel = 'noopener noreferrer'; } const doc = target.ownerDocument; for (const code of content.querySelectorAll('pre > code')) { code.parentElement?.after(...copyControls(doc, 'code-copy', 'Copy code', code.textContent ?? '')); } target.replaceChildren(content, ...copyControls(doc, 'answer-copy', 'Copy answer', text)); }