UNPKG

ts-markdown

Version:

An extensible TypeScript markdown generator that takes JSON and creates a markdown document.

79 lines (78 loc) 2.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.footnote = exports.appendFootnotes = exports.footnoteRenderer = void 0; const rendering_1 = require("../rendering"); /** * The renderer for footnote entries. * * @param entry The footnote entry. * @param options Document-level render options. * @returns Footnote ID markdown content. */ const footnoteRenderer = (entry, options) => { if ('footnote' in entry) { return `[^${entry.footnote.id}]`; } throw new Error('Entry is not a footnote entry. Unable to render.'); }; exports.footnoteRenderer = footnoteRenderer; /** * The renderer for footnote content at the bottom of the document. * * @param data Content to include in the footnote. * @param document The document to update. * @param options Document-level options. * @returns The updated document. */ function appendFootnotes(data, document, options) { let footnotes = getFootnoteEntries(data); if (footnotes.length > 0) { document += '\n\n' + getFootnotesString(footnotes, options); } return document; } exports.appendFootnotes = appendFootnotes; function getFootnotesString(footnotes, options) { return footnotes .map((entry) => { let content = Array.isArray(entry.footnote.content) ? entry.footnote.content : [entry.footnote.content]; return (0, rendering_1.renderEntries)(content, options) .split('\n') .map((line, index) => { let prefix = index === 0 ? `[^${entry.footnote.id}]: ` : ' '; return prefix + line; }) .join('\n'); }) .join('\n\n'); } function getFootnoteEntries(data) { return Array.isArray(data) ? data.reduce((prev, curr) => [...prev, ...getFootnoteEntries(curr)], []) : data !== null && typeof data === 'object' && 'footnote' in data ? [data] : data !== null && typeof data === 'object' ? Object.keys(data).reduce((prev, key) => [ ...prev, ...getFootnoteEntries(data[key]), ], []) : []; } /** * Helper which creates a footnote entry. * * @param options Entry-level options for this element. * @returns a footnote entry */ function footnote(id, content, options) { return { footnote: { id, content, }, ...options, }; } exports.footnote = footnote;