Files
ad/molodetz/static/js/utils/ContentRenderer.js
T

24 lines
882 B
JavaScript

// retoor <retoor@molodetz.nl>
import { marked } from "../../vendor/marked.esm.js";
import DOMPurify from "../../vendor/purify.es.mjs";
import { EMOJI_MAP } from "../generated/EmojiMap.js";
export class ContentRenderer {
static ALLOWED_URI = /^(?:(?:https?|mailto|tel):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
static normalize(text) {
return (text || "").replace(/[\u2013\u2014]/g, "-").replace(/:([a-z0-9_+-]+):/g, (match, name) => EMOJI_MAP[name] || match);
}
static render(text, { inline = false } = {}) {
try {
const source = ContentRenderer.normalize(text);
const html = inline ? marked.parseInline(source) : marked.parse(source, { gfm: true, breaks: true });
return DOMPurify.sanitize(html, { ALLOWED_URI_REGEXP: ContentRenderer.ALLOWED_URI });
} catch (error) {
console.error("render failed", error);
return "";
}
}
}