// Draws what renderMarkdown left as placeholders: maths with KaTeX and // Mermaid diagrams with Pele, each loaded the first time a message needs it. // A placeholder keeps its source as text, so a failure leaves it readable. import DOMPurify from 'dompurify'; let katex: Promise<(typeof import('katex'))['default']> | null = null; let pele: Promise | null = null; function loadKatex() { return (katex ??= Promise.all([ import('katex'), import('katex/dist/katex.min.css'), ]).then(([module]) => module.default)); } function loadPele() { return (pele ??= import('pele/lazy')); } // Pele draws from text the model wrote; keep only drawing in what it returns. // Links, animation (which can set an href) and style elements (which would // style the whole page) are dropped too, though Pele draws none of them. function clean(svg: string): SVGElement | null { const fragment = DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true }, FORBID_TAGS: [ 'a', 'style', 'animate', 'animateMotion', 'animateTransform', 'set', 'image', 'use', 'foreignObject', ], RETURN_DOM_FRAGMENT: true, }); const drawn = fragment.firstElementChild; return drawn?.nodeName.toLowerCase() === 'svg' ? (drawn as SVGElement) : null; } // Pele reads anything shaped like a tag in a label as markup, and keeps only // , , , and
: `Vec` would draw as "Vec". Any // other tag-shaped text is written with Mermaid's own escapes, which every // diagram kind reads as the characters; `<>` annotations are left. const KEPT_TAGS = new Set(['b', 'i', 'strong', 'em', 'br']); function escapeTags(source: string): string { return source.replace( /(?\n]*)>(?!>)/g, (tag, close, name, rest) => KEPT_TAGS.has(name.toLowerCase()) ? tag : `#lt;${close}${name}${rest}#gt;`, ); } // The placeholders under root not drawn yet, each with its source, marked as // taken now: a later call could otherwise give a diagram's code block its // copy button, and that button's label, while this one waits for Pele. function claim(root: HTMLElement, selector: string): [HTMLElement, string][] { return [ ...root.querySelectorAll(`${selector}:not([data-drawn])`), ].map((element) => { element.dataset.drawn = '1'; return [element, element.textContent ?? '']; }); } export async function enhance(root: HTMLElement) { const maths = claim(root, '.math'); const diagrams = claim(root, '.diagram'); if (maths.length) { const render = await loadKatex(); for (const [element, tex] of maths) { try { render.render(tex, element, { displayMode: element.dataset.display === '1', throwOnError: false, trust: false, output: 'htmlAndMathml', }); } catch {} } } if (diagrams.length) { const { renderAsync } = await loadPele(); for (const [element, source] of diagrams) { try { const { svg } = await renderAsync(escapeTags(source)); const drawn = clean(svg); if (drawn) element.replaceChildren(drawn); } catch {} } } // A copy button on every code block. The listener is real rather than // inline HTML from the renderer, and the block stays a plain `pre`, so // selecting it still works; the button reports and then falls asleep. for (const pre of [ ...root.querySelectorAll('pre:not([data-copy])'), ]) { pre.dataset.copy = '1'; const wrap = document.createElement('div'); wrap.className = 'codeblock'; const button = document.createElement('button'); button.type = 'button'; button.className = 'code-copy'; button.textContent = 'copy'; button.addEventListener('click', async () => { try { await navigator.clipboard.writeText(pre.textContent ?? ''); } catch { return; } button.textContent = 'copied'; button.classList.add('done'); setTimeout(() => { button.textContent = 'copy'; button.classList.remove('done'); }, 1200); }); pre.replaceWith(wrap); wrap.append(pre, button); } }