Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions markdown-svg-renderer.html
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@
// ---- Markdown rendering ----
const markdownSanitizeConfig = {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-svg"],
ADD_ATTR: ["data-svg-id"],
FORBID_ATTR: ["style"],
FORBID_TAGS: ["style"]
};
Expand Down Expand Up @@ -469,13 +469,11 @@
typographer: false
});

function escapeAttr(s) {
return s
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
// Sanitized SVG sources are stashed here and referenced by id, rather than
// embedded in a data- attribute: DOMPurify's SAFE_FOR_XML protection strips
// any attribute whose value contains strings like "</title>" or "</style>",
// which silently dropped legitimate SVGs during the second sanitize pass.
const svgStore = new Map();

const defaultFenceRenderer = md.renderer.rules.fence;
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
Expand All @@ -485,22 +483,30 @@
if (lang === "svg") {
const svg = window.DOMPurify.sanitize(token.content, svgSanitizeConfig).trim();
if (svg) {
return `<div class="svg-block-placeholder" data-svg="${escapeAttr(svg)}"></div>\n`;
const id = String(svgStore.size);
svgStore.set(id, svg);
return `<div class="svg-block-placeholder" data-svg-id="${id}"></div>\n`;
}
}

return defaultFenceRenderer(tokens, idx, options, env, self);
};

function hydrateSvgBlocks(root) {
root.querySelectorAll(".svg-block-placeholder[data-svg]").forEach((placeholder) => {
root.querySelectorAll(".svg-block-placeholder[data-svg-id]").forEach((placeholder) => {
const svg = svgStore.get(placeholder.getAttribute("data-svg-id"));
if (!svg) {
placeholder.remove();
return;
}
const block = document.createElement("svg-block");
block.setAttribute("data-svg", placeholder.getAttribute("data-svg") || "");
block.setAttribute("data-svg", svg);
placeholder.replaceWith(block);
});
}

function renderMarkdown(src) {
svgStore.clear();
const html = md.render(src);
return window.DOMPurify.sanitize(html, markdownSanitizeConfig);
}
Expand Down
Loading