Open History to see the last commit
1import { parseMarkdown } from './parser.js'
2import type { BlockNode, ComponentNode, FootnoteItemNode, HeadingAnchorOptions, InlineComponentNode, InlineNode, MarkdownDocument, MarkdownInput, RenderOptions, TableCellNode } from './types.js'
3import { escapeAttr, escapeHtml, footnoteReferenceId } from './utils.js'
4
5export function renderHtml(input: MarkdownInput, options: RenderOptions = {}): string {
6 const document = typeof input === 'string' ? parseMarkdown(input, options) : input
7 return document.children.map(node => renderBlock(node, options)).join('\n')
8}
9
10export function renderBlock(node: BlockNode, options: RenderOptions = {}): string {
11 const extension = renderExtension(node, options)
12 if (extension !== undefined) return extension
13
14 switch (node.type) {
15 case 'heading': {
16 const id = node.id ? ` id="${escapeAttr(node.id)}"` : ''
17 const framework = node.framework ? ` data-framework="${escapeAttr(node.framework)}"` : ''
18 return `<h${node.depth}${id}${framework}>${renderInlines(node.children, options)}${renderHeadingAnchor(node.id, options)}</h${node.depth}>`
19 }
20 case 'paragraph':
21 return `<p>${renderInlines(node.children, options)}</p>`
22 case 'code':
23 return renderCodeBlock(node, options)
24 case 'list': {
25 const tag = node.ordered ? 'ol' : 'ul'
26 const start = node.ordered && node.start !== undefined && node.start !== 1 ? ` start="${node.start}"` : ''
27 const items = node.items.map(item => `<li>${renderListItemChildren(item.children, item.checked, node.loose, options)}</li>`).join('\n')
28 return `<${tag}${start}>\n${items}\n</${tag}>`
29 }
30 case 'blockquote':
31 return `<blockquote>\n${node.children.map(child => renderBlock(child, options)).join('\n')}\n</blockquote>`
32 case 'table': {
33 const header = `<thead><tr>${node.header.map((cell, index) => renderTableCell('th', cell, node.align[index], options)).join('')}</tr></thead>`
34 const body = node.rows.length
35 ? `<tbody>${node.rows
36 .map(row => `<tr>${row.map((cell, index) => renderTableCell('td', cell, node.align[index], options)).join('')}</tr>`)
37 .join('')}</tbody>`
38 : ''
39 return `<table>${header}${body}</table>`
40 }
41 case 'footnotes':
42 return renderFootnotes(node.items, options)
43 case 'thematicBreak':
44 return '<hr>'
45 case 'html':
46 return options.allowHtml ? node.value : escapeHtml(node.value)
47 case 'callout':
48 return renderCallout(node, options)
49 case 'component':
50 return renderComponent(node, options)
51 }
52}
53
54export function renderInline(node: InlineNode, options: RenderOptions = {}): string {
55 const extension = renderExtension(node, options)
56 if (extension !== undefined) return extension
57
58 switch (node.type) {
59 case 'text':
60 return escapeHtml(node.value)
61 case 'inlineCode':
62 return `<code>${escapeHtml(node.value)}</code>`
63 case 'strong':
64 return `<strong>${renderInlines(node.children, options)}</strong>`
65 case 'emphasis':
66 return `<em>${renderInlines(node.children, options)}</em>`
67 case 'strike':
68 return `<del>${renderInlines(node.children, options)}</del>`
69 case 'footnoteReference':
70 return `<sup><a id="user-content-fnref-${escapeAttr(footnoteReferenceId(node.id, node.referenceIndex))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${escapeAttr(node.id)}">${node.number}</a></sup>`
71 case 'link':
72 return `<a href="${escapeAttr(node.href)}"${node.title ? ` title="${escapeAttr(node.title)}"` : ''}>${renderInlines(node.children, options)}</a>`
73 case 'image':
74 return `<img src="${escapeAttr(node.src)}" alt="${escapeAttr(node.alt)}"${node.title ? ` title="${escapeAttr(node.title)}"` : ''}>`
75 case 'break':
76 return '<br>'
77 case 'inlineHtml':
78 return options.allowHtml ? node.value : escapeHtml(node.value)
79 case 'inlineComponent':
80 return renderComponent(node, options)
81 }
82}
83
84export function renderDocument(document: MarkdownDocument, options: RenderOptions = {}): string {
85 return renderHtml(document, options)
86}
87
88function renderInlines(nodes: InlineNode[], options: RenderOptions): string {
89 return nodes.map(node => renderInline(node, options)).join('')
90}
91
92function renderCodeBlock(node: Extract<BlockNode, { type: 'code' }>, options: RenderOptions): string {
93 const lang = node.lang ?? 'plaintext'
94 const preAttrs = `class="tm-code${options.codeLineNumbers ? ' tm-code--line-numbers' : ''}" data-lang="${escapeAttr(lang)}"`
95 + (node.meta ? ` data-meta="${escapeAttr(node.meta)}"` : '')
96 + (node.title ? ` data-code-title="${escapeAttr(node.title)}"` : '')
97 + (node.file ? ` data-filename="${escapeAttr(node.file)}"` : '')
98 + (node.framework ? ` data-framework="${escapeAttr(node.framework)}"` : '')
99 const html = options.highlighter?.(node.value, lang, {
100 ...(node.meta && { meta: node.meta }),
101 ...(node.highlightLines && { highlightLines: node.highlightLines }),
102 ...(options.codeLineNumbers !== undefined && { lineNumbers: options.codeLineNumbers }),
103 }) ?? escapeHtml(node.value)
104
105 const pre = `<pre ${preAttrs}><code class="language-${escapeAttr(lang)}">${html}</code></pre>`
106 if (!node.title) return pre
107
108 return `<figure class="tm-code-frame" data-lang="${escapeAttr(lang)}"><figcaption>${escapeHtml(node.title)}</figcaption>${pre}</figure>`
109}
110
111function renderListItemChildren(children: BlockNode[], checked: boolean | undefined, loose: boolean | undefined, options: RenderOptions): string {
112 let result = checked === undefined ? '' : `<input type="checkbox" disabled${checked ? ' checked' : ''}> `
113 for (let index = 0; index < children.length; index++) {
114 const child = children[index]!
115 if (child.type === 'paragraph' && (!loose || index === 0)) {
116 result += renderInlines(child.children, options)
117 if (loose) result = `<p>${result}</p>`
118 } else result += (index ? '\n' : '') + renderBlock(child, options)
119 }
120 return result
121}
122
123function renderCallout(node: Extract<BlockNode, { type: 'callout' }>, options: RenderOptions): string {
124 const kind = node.kind.toLowerCase()
125 const children = node.children.map(child => renderBlock(child, options)).join('\n')
126 return `<div class="markdown-alert markdown-alert-${escapeAttr(kind)}"><p class="markdown-alert-title">${escapeHtml(node.title)}</p><div class="markdown-alert-content">${children}</div></div>`
127}
128
129function renderFootnotes(items: FootnoteItemNode[], options: RenderOptions): string {
130 const renderedItems = items.map(item => `<li id="user-content-fn-${escapeAttr(item.id)}">\n${renderFootnoteItem(item, options)}\n</li>`).join('\n')
131 return `<section data-footnotes="" class="footnotes"><h2 id="footnote-label" class="sr-only">Footnotes${renderHeadingAnchor('footnote-label', options)}</h2>\n<ol>\n${renderedItems}\n</ol>\n</section>`
132}
133
134function renderFootnoteItem(item: FootnoteItemNode, options: RenderOptions): string {
135 const backref = renderFootnoteBackrefs(item)
136 const lastIndex = item.children.length - 1
137
138 const result = item.children
139 .map((child, index) => {
140 if (index === lastIndex && child.type === 'paragraph') {
141 return `<p>${renderInlines(child.children, options)}${backref}</p>`
142 }
143 return renderBlock(child, options)
144 })
145 if (item.children[lastIndex]?.type !== 'paragraph') result.push(`<p>${backref.trimStart()}</p>`)
146 return result.join('\n')
147}
148
149function renderFootnoteBackrefs(item: FootnoteItemNode): string {
150 let result = ''
151 for (let index = 1; index <= (item.referenceCount ?? 1); index++) {
152 const referenceId = footnoteReferenceId(item.id, index)
153 const label = index === 1 ? `${item.number}` : `${item.number}-${index}`
154 result += ` <a data-footnote-backref="" aria-label="Back to reference ${label}" class="data-footnote-backref" href="#user-content-fnref-${escapeAttr(referenceId)}">↩</a>`
155 }
156 return result
157}
158
159function renderComponent(node: ComponentNode | InlineComponentNode, options: RenderOptions): string {
160 const tag = node.tagName ?? (node.type === 'inlineComponent' ? 'span' : 'md-comment-component')
161 const attrs = renderComponentAttrs(node)
162 const children = node.type === 'inlineComponent'
163 ? renderInlines(node.children, options)
164 : node.children.map(child => renderBlock(child, options)).join('\n')
165 return `<${tag}${attrs}>${children}</${tag}>`
166}
167
168function renderTableCell(
169 tag: 'td' | 'th',
170 cell: TableCellNode,
171 align: 'left' | 'center' | 'right' | undefined,
172 options: RenderOptions,
173): string {
174 const style = align ? ` style="text-align:${align}"` : ''
175 return `<${tag}${style}>${renderInlines(cell.children, options)}</${tag}>`
176}
177
178function renderExtension(node: BlockNode | InlineNode, options: RenderOptions): string | undefined {
179 for (const extension of options.extensions ?? []) {
180 const rendered = extension.renderHtml?.(node, {
181 options,
182 renderBlock: block => renderBlock(block, options),
183 renderInline: inline => renderInline(inline, options),
184 })
185 if (rendered !== undefined) return rendered
186 }
187 return undefined
188}
189
190function renderHeadingAnchor(id: string | undefined, options: RenderOptions): string {
191 const headingAnchors = options.headingAnchors
192 if (!id || !headingAnchors) return ''
193 const anchorOptions = typeof headingAnchors === 'object' ? headingAnchors : {}
194 return `<a href="#${escapeAttr(id)}" aria-hidden="${anchorOptions.ariaHidden ?? true}" class="${escapeAttr(anchorOptions.className ?? 'anchor-heading anchor-heading-link')}" tabindex="${anchorOptions.tabIndex ?? -1}">${escapeHtml(anchorOptions.content ?? '#')}</a>`
195}
196
197function renderComponentAttrs(node: ComponentNode | InlineComponentNode): string {
198 const props: Record<string, string> = {
199 ...node.properties,
200 }
201
202 if (!node.tagName) {
203 props['data-component'] = node.name
204 if (!props['data-attributes']) props['data-attributes'] = JSON.stringify(node.attributes)
205 }
206
207 return Object.entries(props).map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join('')
208}