caption element before table is placed as first element of the table (allows markdown tables to have caption)

This commit is contained in:
Adam Teichert
2025-12-15 23:01:35 -07:00
parent a203dc6e46
commit e07d0a6e47
2 changed files with 53 additions and 3 deletions

View File

@@ -0,0 +1,37 @@
import { describe, it, expect } from 'vitest';
import { markdownToHtmlNoImages } from './htmlMarkdownUtils';
describe('markdownToHtmlNoImages', () => {
it('moves caption into table when caption immediately precedes table', () => {
const markdown = `<caption>My Table</caption>
| Header |
| --- |
| Cell |`;
const html = markdownToHtmlNoImages(markdown);
// We expect the caption to be inside the table
expect(html).toMatch(/<table>\s*<caption>My Table<\/caption>/);
});
it('renders table correctly without caption', () => {
const markdown = `
| Header |
| --- |
| Cell |`;
const html = markdownToHtmlNoImages(markdown);
expect(html).toMatch(/<table>/);
expect(html).not.toMatch(/<caption>/);
expect(html).toContain('Header');
expect(html).toContain('Cell');
});
it('moves caption with attributes into table', () => {
const markdown = `<caption style="color:red">My Table</caption>
| Header |
| --- |
| Cell |`;
const html = markdownToHtmlNoImages(markdown);
expect(html).toMatch(/<table>\s*<caption style="color:red">My Table<\/caption>/);
});
});

View File

@@ -125,8 +125,21 @@ export function markdownToHTMLSafe({
} }
export function markdownToHtmlNoImages(markdownString: string) { export function markdownToHtmlNoImages(markdownString: string) {
const clean = DOMPurify.sanitize( const parsedHtml = marked.parse(markdownString, {
marked.parse(markdownString, { async: false, pedantic: false, gfm: true }) async: false,
).replaceAll(/>[^<>]*<\/math>/g, "></math>"); pedantic: false,
gfm: true,
}) as string;
// Move caption inside table
const htmlWithCaptionInTable = parsedHtml.replace(
/(<caption[^>]*>[\s\S]*?<\/caption>)\s*(<table[^>]*>)/g,
"$2$1"
);
const clean = DOMPurify.sanitize(htmlWithCaptionInTable).replaceAll(
/>[^<>]*<\/math>/g,
"></math>"
);
return clean; return clean;
} }