image grouping

This commit is contained in:
2026-05-14 22:17:12 +02:00
parent 9b53f15d14
commit f94c70a45c
2 changed files with 80 additions and 0 deletions
+36
View File
@@ -92,9 +92,45 @@ function injectDimensions(html: string, dims?: ImageDims): string {
});
}
// Marked emits `<p><figure>…</figure></p>` because the image renderer returns
// a block element from an inline slot. Strip the `<p>` wrapper when the
// paragraph contains nothing but figures (and whitespace / <br>), so the
// figure-grouping step below can see contiguous runs.
function unwrapFiguresFromParagraphs(html: string): string {
return html.replace(/<p>([\s\S]*?)<\/p>/g, (match, inner: string) => {
const stripped = inner.replace(/<br\s*\/?>/g, '').trim();
if (!stripped) return match;
if (/^(?:\s*<figure>[\s\S]*?<\/figure>\s*)+$/.test(stripped)) {
return stripped;
}
return match;
});
}
// Wrap runs of 2+ consecutive <figure> elements in a `.figure-row` flex
// container. Each figure gets `flex: <aspect-ratio>` so widths divide the
// row proportionally and the final heights match.
function groupFigures(html: string): string {
return html.replace(
/(?:<figure>[\s\S]*?<\/figure>\s*){2,}/g,
(run) => {
const figures = run.match(/<figure>[\s\S]*?<\/figure>/g) ?? [];
const items = figures.map((fig) => {
const m = fig.match(/<img[^>]*\swidth="(\d+)"[^>]*\sheight="(\d+)"/);
const ratio = m ? Number(m[1]) / Number(m[2]) : 1;
const safe = Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
return fig.replace('<figure>', `<figure style="flex:${safe.toFixed(3)} ${safe.toFixed(3)} 0">`);
});
return `<div class="figure-row">${items.join('')}</div>`;
},
);
}
export function renderMarkdown(src: string, dims?: ImageDims): string {
let html = renderer.parse(src, { async: false }) as string;
html = injectDimensions(html, dims);
html = unwrapFiguresFromParagraphs(html);
html = groupFigures(html);
return DOMPurify.sanitize(html, {
ADD_TAGS: [...KATEX_TAGS, 'figure', 'figcaption'],
ADD_ATTR: ['aria-hidden', 'style', 'id', 'class', 'encoding', 'mathvariant', 'displaystyle', 'scriptlevel', 'loading'],