Download js/render.js from wuosyn/frejya: direct link, hf CLI and curl.
- Browser
- Download file 5.09 kB
-
https://huggingface.co/spaces/wuosyn/frejya/resolve/main/js/render.js
- Command line
-
hf download hf://spaces/wuosyn/frejya/js/render.js
-
curl -L -o render.js https://huggingface.co/spaces/wuosyn/frejya/resolve/main/js/render.js
5.09 kB
| // Markdown + math + code -> safe DOM. | |
| // | |
| // Model output is untrusted text. Pipeline: | |
| // 1. pull the TeX out (protocol.extractMath) so Markdown cannot mangle it | |
| // 2. Markdown -> HTML (marked), code highlighted with highlight.js | |
| // 3. sanitise with DOMPurify against a small allow-list | |
| // 4. put KaTeX-rendered math back, into text positions only | |
| import { Marked, DOMPurify, katex, hljs } from '../vendor/vendor.js'; | |
| import { extractMath, MATH_OPEN, MATH_CLOSE } from './protocol.js'; | |
| const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); | |
| const marked = new Marked({ | |
| gfm: true, | |
| breaks: true, | |
| renderer: { | |
| code({ text, lang }) { | |
| const language = (lang || '').trim().split(/\s+/)[0].toLowerCase(); | |
| let body; | |
| if (language && hljs.getLanguage(language)) { | |
| try { | |
| body = hljs.highlight(text, { language, ignoreIllegals: true }).value; | |
| } catch { | |
| body = escapeHtml(text); | |
| } | |
| } else { | |
| body = escapeHtml(text); | |
| } | |
| const label = language ? ` data-lang="${escapeHtml(language)}"` : ''; | |
| return `<pre${label}><code class="hljs">${body}</code></pre>\n`; | |
| }, | |
| }, | |
| }); | |
| const PURIFY = { | |
| ALLOWED_TAGS: [ | |
| 'p', 'br', 'strong', 'b', 'em', 'i', 'del', 's', 'code', 'pre', 'blockquote', 'ul', 'ol', 'li', 'a', | |
| 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'span', 'sup', 'sub', 'kbd', | |
| ], | |
| ALLOWED_ATTR: ['href', 'title', 'class', 'start', 'align', 'data-lang'], | |
| ALLOWED_URI_REGEXP: /^(?:https?:|mailto:)/i, | |
| RETURN_DOM_FRAGMENT: true, | |
| }; | |
| // Only syntax-highlighting classes survive, so model output cannot borrow the app's own styles. | |
| DOMPurify.addHook('uponSanitizeAttribute', (node, data) => { | |
| if (data.attrName === 'class') { | |
| const kept = data.attrValue.split(/\s+/).filter((c) => /^hljs(?:-[\w-]+)?$/.test(c) || /^language-[\w-]+$/.test(c)); | |
| if (kept.length) data.attrValue = kept.join(' '); | |
| else data.keepAttr = false; | |
| } | |
| }); | |
| const mathCache = new Map(); | |
| function renderTex(tex, display) { | |
| const key = `${display ? 'D' : 'I'}${tex}`; | |
| let html = mathCache.get(key); | |
| if (html === undefined) { | |
| try { | |
| html = katex.renderToString(tex, { displayMode: display, throwOnError: false, strict: 'ignore', trust: false, output: 'htmlAndMathml' }); | |
| } catch { | |
| html = `<code>${escapeHtml(tex)}</code>`; | |
| } | |
| if (mathCache.size > 600) mathCache.clear(); | |
| mathCache.set(key, html); | |
| } | |
| return html; | |
| } | |
| const PLACEHOLDER = new RegExp(`${MATH_OPEN}(\\d+)${MATH_CLOSE}`, 'g'); | |
| function restoreMath(root, items) { | |
| const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); | |
| const targets = []; | |
| while (walker.nextNode()) { | |
| if (walker.currentNode.nodeValue.includes(MATH_OPEN)) targets.push(walker.currentNode); | |
| } | |
| for (const node of targets) { | |
| const parent = node.parentNode; | |
| const inCode = parent.closest?.('code, pre'); | |
| const frag = document.createDocumentFragment(); | |
| let last = 0; | |
| const value = node.nodeValue; | |
| for (const m of value.matchAll(PLACEHOLDER)) { | |
| const item = items[Number(m[1])]; | |
| if (m.index > last) frag.append(value.slice(last, m.index)); | |
| if (!item) { | |
| // not one of ours: leave nothing behind | |
| } else if (inCode) { | |
| frag.append(item.display ? `$$${item.tex}$$` : `$${item.tex}$`); | |
| } else { | |
| const holder = document.createElement('span'); | |
| holder.className = item.display ? 'math math--display' : 'math'; | |
| holder.innerHTML = renderTex(item.tex, item.display); // KaTeX output, generated with trust:false | |
| frag.append(holder); | |
| } | |
| last = m.index + m[0].length; | |
| } | |
| if (last < value.length) frag.append(value.slice(last)); | |
| parent.replaceChild(frag, node); | |
| } | |
| } | |
| /** Renders one chat bubble's Markdown source to a DocumentFragment that is safe to insert. */ | |
| export function renderMarkdown(src) { | |
| const { text, items } = extractMath(src); | |
| const html = marked.parse(text, { async: false }); | |
| const frag = DOMPurify.sanitize(html, PURIFY); | |
| for (const a of frag.querySelectorAll('a')) { | |
| a.setAttribute('target', '_blank'); | |
| a.setAttribute('rel', 'noopener noreferrer'); | |
| } | |
| if (items.length) restoreMath(frag, items); | |
| // The private-use markers must never reach the page, whatever happened above. | |
| const stray = document.createTreeWalker(frag, NodeFilter.SHOW_TEXT); | |
| while (stray.nextNode()) { | |
| const n = stray.currentNode; | |
| if (n.nodeValue.includes(MATH_OPEN) || n.nodeValue.includes(MATH_CLOSE)) { | |
| n.nodeValue = n.nodeValue.replace(/[]/g, ''); | |
| } | |
| } | |
| return frag; | |
| } | |
| /** | |
| * Renders what the user typed: kept as plain text (so asterisks and underscores | |
| * stay literal) but with any TeX math they wrote rendered. | |
| */ | |
| export function renderUserText(src) { | |
| const { text, items } = extractMath(src); | |
| const frag = document.createDocumentFragment(); | |
| frag.append(text); | |
| if (items.length) restoreMath(frag, items); | |
| return frag; | |
| } | |