image grouping
This commit is contained in:
@@ -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'],
|
||||
|
||||
Reference in New Issue
Block a user