Only preserve <figure> when contains <figcaption>

This commit is contained in:
Will Boyd
2024-02-21 17:38:28 -05:00
parent b1625f7700
commit 53523321ed
+20 -7
View File
@@ -55,14 +55,27 @@ function initTurndownService() {
} }
}); });
// preserve <figure> and <figcaption> -- the extra newlines between tags are // preserve <figure> when it contains a <figcaption>
// necessary because of how markdown is being used inside HTML tags turndownService.addRule('figure', {
turndownService.addRule('fig', { filter: 'figure',
filter: ['figure', 'figcaption'],
replacement: (content, node) => { replacement: (content, node) => {
const tagName = node.nodeName.toLowerCase(); if (node.querySelector('figcaption')) {
const result = '\n\n<' + tagName + '>\n\n' + content + '\n\n</' + tagName + '>\n\n'; // extra newlines are necessary for markdown and HTML to render correctly together
return result.replace('\n\n\n\n', '\n\n'); // reduce quadruple newlines const result = '\n\n<figure>\n\n' + content + '\n\n</figure>\n\n';
return result.replace('\n\n\n\n', '\n\n'); // collapse quadruple newlines
} else {
// does not contain <figcaption>, do not preserve
return content;
}
}
});
// preserve <figcaption>
turndownService.addRule('figcaption', {
filter: 'figcaption',
replacement: (content, node) => {
// extra newlines are necessary for markdown and HTML to render correctly together
return '\n\n<figcaption>\n\n' + content + '\n\n</figcaption>\n\n';
} }
}); });