feat: footnotes (#2384)

* feat: footnotes

* feat: proper DOCX support
This commit is contained in:
Philip Okugbe
2026-08-12 12:30:30 +01:00
committed by GitHub
parent 7439da2f6e
commit a0b2ac6ae3
21 changed files with 987 additions and 9 deletions
@@ -34,6 +34,8 @@ export function htmlToMarkdown(html: string): string {
iframeEmbed,
image,
video,
footnoteRef,
footnotesList,
]);
return turndownService.turndown(html).replaceAll('<br>', ' ');
}
@@ -203,6 +205,56 @@ function image(turndownService: _TurndownService) {
});
}
function getFootnoteAnchor(node: HTMLElement): HTMLElement | null {
const child = node.firstElementChild as HTMLElement | null;
return child?.nodeName === 'A' && child.classList.contains('footnote-ref')
? child
: null;
}
function footnoteRef(turndownService: _TurndownService) {
turndownService.addRule('footnoteRef', {
filter: function (node: HTMLInputElement) {
return node.nodeName === 'SUP' && !!getFootnoteAnchor(node);
},
replacement: function (_content: string, node: HTMLInputElement) {
const anchor = getFootnoteAnchor(node);
const number =
anchor.getAttribute('data-reference-number') || anchor.textContent;
return `[^${number}]`;
},
});
}
function footnotesList(turndownService: _TurndownService) {
turndownService.addRule('footnotesList', {
filter: function (node: HTMLInputElement) {
return node.nodeName === 'OL' && node.classList.contains('footnotes');
},
replacement: function (_content: string, node: HTMLInputElement) {
const items = Array.from(node.children).filter(
(child) => child.nodeName === 'LI',
);
const definitions = items.map((li, index) => {
const number =
(li.getAttribute('id') || '').replace('fn:', '') ||
String(index + 1);
const markdown = turndownService
.turndown((li as HTMLElement).innerHTML)
.trim();
// continuation lines need a 4-space indent to stay in the footnote
const [first, ...rest] = markdown.split('\n');
const body = [
first,
...rest.map((line: string) => (line.trim() ? ` ${line}` : line)),
].join('\n');
return `[^${number}]: ${body}`;
});
return `\n\n${definitions.join('\n')}\n\n`;
},
});
}
function video(turndownService: _TurndownService) {
turndownService.addRule('video', {
filter: function (node: HTMLInputElement) {