Open History to see the last commit
1import { Fragment, createElement } from 'react'
2import type { ComponentPropsWithoutRef, ComponentType, JSX, ReactElement, ReactNode } from 'react'
3import { parseMarkdown } from './parser.js'
4import { footnoteReferenceId } from './utils.js'
5import type { BlockNode, ComponentNode, FootnoteItemNode, InlineComponentNode, InlineNode, MarkdownInput, RenderOptions, TableCellNode } from './types.js'
6
7type IntrinsicElementName = keyof JSX.IntrinsicElements
8type ComponentMap = Partial<Record<string, string | ComponentType<any>>>
9
10export type MarkdownComponentProps<TagName extends IntrinsicElementName> = ComponentPropsWithoutRef<TagName>
11
12export type MarkdownComponents = Partial<{
13 [TagName in IntrinsicElementName]: IntrinsicElementName | ComponentType<MarkdownComponentProps<TagName>>
14}> &
15 Record<string, string | ComponentType<any> | undefined>
16
17export interface MarkdownReactOptions extends RenderOptions {
18 components?: ComponentMap
19}
20
21export interface MarkdownProps extends MarkdownReactOptions {
22 children: MarkdownInput
23}
24
25export function Markdown({ children, ...options }: MarkdownProps): ReactElement {
26 return createElement(Fragment, null, renderMarkdownReact(children, options))
27}
28
29export function renderMarkdownReact(input: MarkdownInput, options: MarkdownReactOptions = {}): ReactNode {
30 const document = typeof input === 'string' ? parseMarkdown(input, options) : input
31 return document.children.map((node, index) => renderBlockReact(node, options, `b:${index}`))
32}
33
34export function renderBlockReact(node: BlockNode, options: MarkdownReactOptions = {}, key?: string): ReactElement {
35 switch (node.type) {
36 case 'heading':
37 return h(
38 options,
39 `h${node.depth}`,
40 { key, ...(node.id && { id: node.id }), ...(node.framework && { 'data-framework': node.framework }) },
41 renderInlines(node.children, options),
42 renderHeadingAnchorReact(node.id, options),
43 )
44 case 'paragraph':
45 return h(options, 'p', { key }, renderInlines(node.children, options))
46 case 'code':
47 return renderCodeBlockReact(node, options, key)
48 case 'list': {
49 const tag = node.ordered ? 'ol' : 'ul'
50 return h(
51 options,
52 tag,
53 { key, ...(node.ordered && node.start !== undefined && node.start !== 1 && { start: node.start }) },
54 node.items.map((item, index) =>
55 h(options, 'li', { key: index }, renderListItemChildrenReact(item.children, item.checked, node.loose, options, `${index}`)),
56 ),
57 )
58 }
59 case 'blockquote':
60 return h(options, 'blockquote', { key }, node.children.map((child, index) => renderBlockReact(child, options, `${key}:${index}`)))
61 case 'table':
62 return h(
63 options,
64 'table',
65 { key },
66 h(options, 'thead', null, h(options, 'tr', null, node.header.map((cell, index) => renderTableCellReact('th', cell, node.align[index], options, index)))),
67 node.rows.length
68 ? h(
69 options,
70 'tbody',
71 null,
72 node.rows.map((row, rowIndex) =>
73 h(options, 'tr', { key: rowIndex }, row.map((cell, index) => renderTableCellReact('td', cell, node.align[index], options, index))),
74 ),
75 )
76 : null,
77 )
78 case 'footnotes':
79 return renderFootnotesReact(node.items, options, key)
80 case 'thematicBreak':
81 return h(options, 'hr', { key })
82 case 'html':
83 return options.allowHtml
84 ? h(options, 'div', { key, dangerouslySetInnerHTML: { __html: node.value } })
85 : h(options, 'p', { key }, node.value)
86 case 'callout':
87 return h(
88 options,
89 'div',
90 { key, className: `markdown-alert markdown-alert-${node.kind.toLowerCase()}` },
91 h(options, 'p', { className: 'markdown-alert-title' }, node.title),
92 h(options, 'div', { className: 'markdown-alert-content' }, node.children.map((child, index) => renderBlockReact(child, options, `${key}:${index}`))),
93 )
94 case 'component':
95 return renderComponentReact(node, options, key)
96 }
97}
98
99export function renderInlineReact(node: InlineNode, options: MarkdownReactOptions = {}, key?: string): ReactNode {
100 switch (node.type) {
101 case 'text':
102 return node.value
103 case 'inlineCode':
104 return h(options, 'code', { key }, node.value)
105 case 'strong':
106 return h(options, 'strong', { key }, renderInlines(node.children, options))
107 case 'emphasis':
108 return h(options, 'em', { key }, renderInlines(node.children, options))
109 case 'strike':
110 return h(options, 'del', { key }, renderInlines(node.children, options))
111 case 'footnoteReference':
112 return h(
113 options,
114 'sup',
115 { key },
116 h(
117 options,
118 'a',
119 {
120 id: `user-content-fnref-${footnoteReferenceId(node.id, node.referenceIndex)}`,
121 'data-footnote-ref': '',
122 'aria-describedby': 'footnote-label',
123 href: `#user-content-fn-${node.id}`,
124 },
125 node.number,
126 ),
127 )
128 case 'link':
129 return h(options, 'a', { key, href: node.href, ...(node.title && { title: node.title }) }, renderInlines(node.children, options))
130 case 'image':
131 return h(options, 'img', { key, src: node.src, alt: node.alt, ...(node.title && { title: node.title }) })
132 case 'break':
133 return h(options, 'br', { key })
134 case 'inlineHtml':
135 return options.allowHtml
136 ? h(options, 'span', { key, dangerouslySetInnerHTML: { __html: node.value } })
137 : node.value
138 case 'inlineComponent':
139 return renderComponentReact(node, options, key)
140 }
141}
142
143function renderInlines(nodes: InlineNode[], options: MarkdownReactOptions): ReactNode[] {
144 return nodes.map((node, index) => renderInlineReact(node, options, `i:${index}`))
145}
146
147function renderCodeBlockReact(node: Extract<BlockNode, { type: 'code' }>, options: MarkdownReactOptions, key?: string): ReactElement {
148 const lang = node.lang ?? 'plaintext'
149 const highlighter = options.highlighter
150
151 // Keep completed groups of lines in stable text nodes as code grows. Grouping
152 // bounds React's sibling work without relaying out the entire code block.
153 // Static rendering and custom code components retain string children.
154 const content = highlighter ? undefined : !options.components?.code && options.extensions?.some(extension => extension.name === 'streaming')
155 ? node.value.match(/(?:[^\n]*\n){1,4}|[^\n]+$/g)
156 : node.value
157
158 const highlighted =
159 highlighter
160 ? {
161 dangerouslySetInnerHTML: {
162 __html: highlighter(node.value, lang, {
163 ...(node.meta && { meta: node.meta }),
164 ...(node.highlightLines && { highlightLines: node.highlightLines }),
165 ...(options.codeLineNumbers !== undefined && { lineNumbers: options.codeLineNumbers }),
166 }),
167 },
168 }
169 : undefined
170
171 const pre = h(
172 options,
173 'pre',
174 {
175 key,
176 className: `tm-code${options.codeLineNumbers ? ' tm-code--line-numbers' : ''}`,
177 'data-lang': lang,
178 ...(node.meta && { 'data-meta': node.meta }),
179 ...(node.title && { 'data-code-title': node.title }),
180 ...(node.file && { 'data-filename': node.file }),
181 ...(node.framework && { 'data-framework': node.framework }),
182 },
183 h(options, 'code', { className: `language-${lang}`, ...highlighted }, content),
184 )
185
186 if (!node.title) return pre
187
188 return h(
189 options,
190 'figure',
191 { key, className: 'tm-code-frame', 'data-lang': lang },
192 h(options, 'figcaption', null, node.title),
193 pre,
194 )
195}
196
197function renderListItemChildrenReact(
198 children: BlockNode[],
199 checked: boolean | undefined,
200 loose: boolean | undefined,
201 options: MarkdownReactOptions,
202 key: string,
203): ReactNode[] {
204 let result: ReactNode[] =
205 checked === undefined
206 ? []
207 : [
208 h(options, 'input', {
209 key: `${key}:checkbox`,
210 type: 'checkbox',
211 disabled: true,
212 checked,
213 readOnly: true,
214 }),
215 ' ',
216 ]
217
218 for (let index = 0; index < children.length; index++) {
219 const child = children[index]!
220 if (child.type === 'paragraph' && (!loose || index === 0)) {
221 for (const inline of renderInlines(child.children, options)) result.push(inline)
222 if (loose) result = [h(options, 'p', { key: `${key}:paragraph` }, result)]
223 } else result.push(renderBlockReact(child, options, `${key}:${index}`))
224 }
225 return result
226}
227
228function renderTableCellReact(
229 tag: 'td' | 'th',
230 cell: TableCellNode,
231 align: 'left' | 'center' | 'right' | undefined,
232 options: MarkdownReactOptions,
233 key: number,
234): ReactElement {
235 return h(options, tag, { key, ...(align && { style: { textAlign: align } }) }, renderInlines(cell.children, options))
236}
237
238function renderFootnotesReact(items: FootnoteItemNode[], options: MarkdownReactOptions, key?: string): ReactElement {
239 return h(
240 options,
241 'section',
242 { key, 'data-footnotes': '', className: 'footnotes' },
243 h(options, 'h2', { id: 'footnote-label', className: 'sr-only' }, 'Footnotes', renderHeadingAnchorReact('footnote-label', options)),
244 h(
245 options,
246 'ol',
247 null,
248 items.map(item => h(options, 'li', { key: item.id, id: `user-content-fn-${item.id}` }, renderFootnoteItemReact(item, options))),
249 ),
250 )
251}
252
253function renderFootnoteItemReact(item: FootnoteItemNode, options: MarkdownReactOptions): ReactNode[] {
254 const lastIndex = item.children.length - 1
255 const backrefs = renderFootnoteBackrefsReact(item, options)
256
257 const result = item.children.map((child, index) => {
258 if (index === lastIndex && child.type === 'paragraph') {
259 return h(options, 'p', { key: index }, renderInlines(child.children, options), backrefs)
260 }
261 return renderBlockReact(child, options, `${index}`)
262 })
263 if (item.children[lastIndex]?.type !== 'paragraph') result.push(h(options, 'p', { key: 'backref-wrapper' }, backrefs.slice(1)))
264 return result
265}
266
267function renderFootnoteBackrefsReact(item: FootnoteItemNode, options: MarkdownReactOptions): ReactNode[] {
268 const result: ReactNode[] = []
269 for (let index = 1; index <= (item.referenceCount ?? 1); index++) {
270 const referenceId = footnoteReferenceId(item.id, index)
271 const label = index === 1 ? `${item.number}` : `${item.number}-${index}`
272 result.push(
273 ' ',
274 h(
275 options,
276 'a',
277 {
278 key: index,
279 'data-footnote-backref': '',
280 'aria-label': `Back to reference ${label}`,
281 className: 'data-footnote-backref',
282 href: `#user-content-fnref-${referenceId}`,
283 },
284 '\u21a9',
285 ),
286 )
287 }
288 return result
289}
290
291function h(options: MarkdownReactOptions, tag: string | typeof Fragment, props: Record<string, any> | null, ...children: ReactNode[]): ReactElement {
292 const component = typeof tag === 'string' ? options.components?.[tag] ?? tag : tag
293 return createElement(component, props, ...children)
294}
295
296function renderComponentReact(node: ComponentNode | InlineComponentNode, options: MarkdownReactOptions, key?: string): ReactElement {
297 const tag = node.tagName ?? (node.type === 'inlineComponent' ? 'span' : 'md-comment-component')
298 const props: Record<string, string> = {
299 ...node.properties,
300 }
301
302 if (!node.tagName) {
303 props['data-component'] = node.name
304 if (!props['data-attributes']) props['data-attributes'] = JSON.stringify(node.attributes)
305 }
306
307 return h(options, tag, { key, ...props }, node.type === 'inlineComponent'
308 ? renderInlines(node.children, options)
309 : node.children.map((child, index) => renderBlockReact(child, options, `${key}:${index}`)))
310}
311
312function renderHeadingAnchorReact(id: string | undefined, options: MarkdownReactOptions): ReactNode {
313 if (!id || !options.headingAnchors) return null
314
315 const anchorOptions = typeof options.headingAnchors === 'object' ? options.headingAnchors : {}
316 return h(
317 options,
318 'a',
319 {
320 href: `#${id}`,
321 'aria-hidden': anchorOptions.ariaHidden ?? true,
322 className: anchorOptions.className ?? 'anchor-heading anchor-heading-link',
323 tabIndex: anchorOptions.tabIndex ?? -1,
324 },
325 anchorOptions.content ?? '#',
326 )
327}