From 867d5da99decf8af6864c96617c31db054d8a6d3 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Wed, 18 Nov 2026 20:53:11 -0700 Subject: [PATCH] fix: restore native foldable callouts --- .changeset/foldable-callouts.md | 5 ++ src/extensions/callouts.ts | 35 ++++------ src/extensions/docs.ts | 16 ++--- src/extensions/tabs.ts | 44 ++++++------ src/html.ts | 58 ++++++++-------- src/octane.ts | 23 +++--- src/parser.ts | 119 ++++++++++++++------------------ src/react.ts | 23 +++--- src/types.ts | 2 + tests/docs-extensions.test.ts | 35 +++++++++- 10 files changed, 189 insertions(+), 171 deletions(-) create mode 100644 .changeset/foldable-callouts.md diff --git a/.changeset/foldable-callouts.md b/.changeset/foldable-callouts.md new file mode 100644 index 0000000..8f00794 --- /dev/null +++ b/.changeset/foldable-callouts.md @@ -0,0 +1,5 @@ +--- +"@tanstack/markdown": patch +--- + +Support foldable callouts in HTML, React, and Octane. Use `> [!TIP]- Title` for a callout that starts closed or `> [!TIP]+ Title` for one that starts open. Both use native HTML disclosure controls. diff --git a/src/extensions/callouts.ts b/src/extensions/callouts.ts index 4a18a2f..ffac2d4 100644 --- a/src/extensions/callouts.ts +++ b/src/extensions/callouts.ts @@ -7,33 +7,28 @@ export function calloutsExtension(): MarkdownExtension { } } -export function parseCalloutBlock(context: Parameters>[0]): CalloutNode | undefined { - const first = context.lines[context.index] ?? '' - const match = first.match(/^ {0,3}>\s*\[!([A-Za-z]+)\](?:\s+(.*))?$/) - if (!match) return undefined +export function parseCalloutBlock({ + lines, + index, + consume, + parseBlocks, +}: Parameters>[0]): CalloutNode | undefined { + const match = lines[index]?.match(/^ {0,3}>\s*\[!([A-Za-z]+)\]([+-])?(?:\s+(.*))?$/) + if (!match) return const kind = match[1]!.toLowerCase() - const title = match[2]?.trim() || titleCase(kind) const body: string[] = [] - let cursor = context.index + 1 - - while (cursor < context.lines.length) { - const line = context.lines[cursor] ?? '' - const quoted = line.match(/^ {0,3}>\s?(.*)$/) - if (!quoted) break - body.push(quoted[1]!) - cursor++ + let cursor = index + 1 + for (let quote; (quote = lines[cursor]?.match(/^ {0,3}>\s?(.*)$/)); cursor++) { + body.push(quote[1]!) } - context.consume(cursor - context.index) + consume(cursor - index) return { type: 'callout', kind, - title, - children: context.parseBlocks(body.join('\n')), + title: match[3]?.trim() || kind[0]!.toUpperCase() + kind.slice(1), + ...(match[2] && { open: match[2] === '+' }), + children: parseBlocks(body.join('\n')), } } - -function titleCase(value: string) { - return value.slice(0, 1).toUpperCase() + value.slice(1).toLowerCase() -} diff --git a/src/extensions/docs.ts b/src/extensions/docs.ts index 6ba2d77..b0746ac 100644 --- a/src/extensions/docs.ts +++ b/src/extensions/docs.ts @@ -10,21 +10,13 @@ export interface DocsMarkdownOptions { } export function docsMarkdownExtensions(options: DocsMarkdownOptions = {}): MarkdownExtension[] { + const { collectHeadings } = options const extensions = [ calloutsExtension(), - commentComponentsExtension({ - transformComponent: transformDocsComponent, - }), + commentComponentsExtension({ transformComponent: transformDocsComponent }), ] - - if (options.collectHeadings !== false) { - extensions.push( - headingCollectionExtension( - typeof options.collectHeadings === 'object' ? options.collectHeadings : {}, - ), - ) - } - + if (collectHeadings === false) return extensions + extensions.push(headingCollectionExtension(typeof collectHeadings === 'object' ? collectHeadings : undefined)) return extensions } diff --git a/src/extensions/tabs.ts b/src/extensions/tabs.ts index ecbd69d..fabc8a9 100644 --- a/src/extensions/tabs.ts +++ b/src/extensions/tabs.ts @@ -79,35 +79,35 @@ export function transformPackageManagerTabs(node: ComponentNode): ComponentNode export function transformBundlerTabs(node: ComponentNode): ComponentNode { const sections = splitByHeading(node.children) - const selected = (['vite', 'rsbuild'] as const).flatMap(bundler => { - const section = sections.find(section => section.name.toLowerCase() === bundler) - return section ? [{ ...section, name: bundler }] : [] - }) - if (!selected.length) return node - - const tabs = selected.map(section => ({ slug: section.name, name: section.name })) + const tabs: Array<{ slug: string; name: string }> = [] + const children: ComponentNode[] = [] + for (const name of ['vite', 'rsbuild']) { + const section = sections.find(section => section.name.toLowerCase() === name) + if (!section) continue + tabs.push({ slug: name, name }) + children.push({ + type: 'component', + name: 'tab-panel', + tagName: 'md-tab-panel', + attributes: {}, + properties: { + 'data-tab-slug': name, + 'data-tab-index': `${children.length}`, + 'data-content': section.children.length === 1 && section.children[0]?.type === 'code' ? 'code-only' : 'mixed', + }, + children: section.children, + }) + } + if (!tabs.length) return node return { ...node, properties: { ...node.properties, 'data-attributes': JSON.stringify({ tabs }), - 'data-bundler-meta': JSON.stringify({ bundlers: selected.map(section => section.name) }), + 'data-bundler-meta': JSON.stringify({ bundlers: tabs.map(tab => tab.name) }), }, - children: selected.map((section, index): ComponentNode => { - return { - type: 'component', - name: 'tab-panel', - tagName: 'md-tab-panel', - attributes: {}, - properties: { - 'data-tab-slug': section.name, - 'data-tab-index': `${index}`, - 'data-content': section.children.length === 1 && section.children[0]?.type === 'code' ? 'code-only' : 'mixed', - }, - children: section.children, - } - }), + children, } } diff --git a/src/html.ts b/src/html.ts index 3ea2d9e..ff6adb3 100644 --- a/src/html.ts +++ b/src/html.ts @@ -3,8 +3,7 @@ import type { BlockNode, ComponentNode, FootnoteItemNode, HeadingAnchorOptions, import { escapeAttr, escapeHtml, footnoteReferenceId } from './utils.js' export function renderHtml(input: MarkdownInput, options: RenderOptions = {}): string { - const document = typeof input === 'string' ? parseMarkdown(input, options) : input - return document.children.map(node => renderBlock(node, options)).join('\n') + return renderDocument(typeof input === 'string' ? parseMarkdown(input, options) : input, options) } export function renderBlock(node: BlockNode, options: RenderOptions = {}): string { @@ -28,7 +27,7 @@ export function renderBlock(node: BlockNode, options: RenderOptions = {}): strin return `<${tag}${start}>\n${items}\n` } case 'blockquote': - return `
\n${node.children.map(child => renderBlock(child, options)).join('\n')}\n
` + return `
\n${renderBlocks(node.children, options)}\n
` case 'table': { const header = `${node.header.map((cell, index) => renderTableCell('th', cell, node.align[index], options)).join('')}` const body = node.rows.length @@ -44,8 +43,12 @@ export function renderBlock(node: BlockNode, options: RenderOptions = {}): strin return '
' case 'html': return options.allowHtml ? node.value : escapeHtml(node.value) - case 'callout': - return renderCallout(node, options) + case 'callout': { + const { open } = node + const tag = open === undefined ? 'div' : 'details' + const titleTag = open === undefined ? 'p' : 'summary' + return `<${tag}${open ? ' open' : ''} class="markdown-alert markdown-alert-${escapeAttr(node.kind.toLowerCase())}"><${titleTag} class="markdown-alert-title">${escapeHtml(node.title)}
${renderBlocks(node.children, options)}
` + } case 'component': return renderComponent(node, options) } @@ -82,7 +85,11 @@ export function renderInline(node: InlineNode, options: RenderOptions = {}): str } export function renderDocument(document: MarkdownDocument, options: RenderOptions = {}): string { - return renderHtml(document, options) + return renderBlocks(document.children, options) +} + +function renderBlocks(nodes: BlockNode[], options: RenderOptions): string { + return nodes.map(node => renderBlock(node, options)).join('\n') } function renderInlines(nodes: InlineNode[], options: RenderOptions): string { @@ -91,7 +98,8 @@ function renderInlines(nodes: InlineNode[], options: RenderOptions): string { function renderCodeBlock(node: Extract, options: RenderOptions): string { const lang = node.lang ?? 'plaintext' - const preAttrs = `class="tm-code${options.codeLineNumbers ? ' tm-code--line-numbers' : ''}" data-lang="${escapeAttr(lang)}"` + const escapedLang = escapeAttr(lang) + const preAttrs = `class="tm-code${options.codeLineNumbers ? ' tm-code--line-numbers' : ''}" data-lang="${escapedLang}"` + (node.meta ? ` data-meta="${escapeAttr(node.meta)}"` : '') + (node.title ? ` data-code-title="${escapeAttr(node.title)}"` : '') + (node.file ? ` data-filename="${escapeAttr(node.file)}"` : '') @@ -102,10 +110,10 @@ function renderCodeBlock(node: Extract, options: Re ...(options.codeLineNumbers !== undefined && { lineNumbers: options.codeLineNumbers }), }) ?? escapeHtml(node.value) - const pre = `
${html}
` + const pre = `
${html}
` if (!node.title) return pre - return `
${escapeHtml(node.title)}
${pre}
` + return `
${escapeHtml(node.title)}
${pre}
` } function renderListItemChildren(children: BlockNode[], checked: boolean | undefined, loose: boolean | undefined, options: RenderOptions): string { @@ -120,12 +128,6 @@ function renderListItemChildren(children: BlockNode[], checked: boolean | undefi return result } -function renderCallout(node: Extract, options: RenderOptions): string { - const kind = node.kind.toLowerCase() - const children = node.children.map(child => renderBlock(child, options)).join('\n') - return `

${escapeHtml(node.title)}

${children}
` -} - function renderFootnotes(items: FootnoteItemNode[], options: RenderOptions): string { const renderedItems = items.map(item => `
  • \n${renderFootnoteItem(item, options)}\n
  • `).join('\n') return `

    Footnotes${renderHeadingAnchor('footnote-label', options)}

    \n
      \n${renderedItems}\n
    \n
    ` @@ -158,10 +160,19 @@ function renderFootnoteBackrefs(item: FootnoteItemNode): string { function renderComponent(node: ComponentNode | InlineComponentNode, options: RenderOptions): string { const tag = node.tagName ?? (node.type === 'inlineComponent' ? 'span' : 'md-comment-component') - const attrs = renderComponentAttrs(node) + const props: Record = { + ...node.properties, + } + + if (!node.tagName) { + props['data-component'] = node.name + if (!props['data-attributes']) props['data-attributes'] = JSON.stringify(node.attributes) + } + + const attrs = Object.entries(props).map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join('') const children = node.type === 'inlineComponent' ? renderInlines(node.children, options) - : node.children.map(child => renderBlock(child, options)).join('\n') + : renderBlocks(node.children, options) return `<${tag}${attrs}>${children}` } @@ -193,16 +204,3 @@ function renderHeadingAnchor(id: string | undefined, options: RenderOptions): st const anchorOptions = typeof headingAnchors === 'object' ? headingAnchors : {} return `${escapeHtml(anchorOptions.content ?? '#')}` } - -function renderComponentAttrs(node: ComponentNode | InlineComponentNode): string { - const props: Record = { - ...node.properties, - } - - if (!node.tagName) { - props['data-component'] = node.name - if (!props['data-attributes']) props['data-attributes'] = JSON.stringify(node.attributes) - } - - return Object.entries(props).map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join('') -} diff --git a/src/octane.ts b/src/octane.ts index 5c352de..53179b7 100644 --- a/src/octane.ts +++ b/src/octane.ts @@ -20,7 +20,7 @@ export function Markdown({ children, ...options }: MarkdownProps): ElementDescri export function renderMarkdownOctane(input: MarkdownInput, options: MarkdownOctaneOptions = {}): OctaneNode[] { const document = typeof input === 'string' ? parseMarkdown(input, options) : input - return document.children.map((node, index) => renderBlockOctane(node, options, `b:${index}`)) + return renderBlocks(document.children, options, 'b') } export function renderBlockOctane(node: BlockNode, options: MarkdownOctaneOptions = {}, key?: string): ElementDescriptor { @@ -49,7 +49,7 @@ export function renderBlockOctane(node: BlockNode, options: MarkdownOctaneOption ) } case 'blockquote': - return h(options, 'blockquote', { key }, node.children.map((child, index) => renderBlockOctane(child, options, `${key}:${index}`))) + return h(options, 'blockquote', { key }, renderBlocks(node.children, options, key)) case 'table': return h( options, @@ -75,14 +75,17 @@ export function renderBlockOctane(node: BlockNode, options: MarkdownOctaneOption return options.allowHtml ? h(options, 'div', { key, dangerouslySetInnerHTML: { __html: node.value } }) : h(options, 'p', { key }, node.value) - case 'callout': + case 'callout': { + const { open } = node + const foldable = open !== undefined return h( options, - 'div', - { key, className: `markdown-alert markdown-alert-${node.kind.toLowerCase()}` }, - h(options, 'p', { className: 'markdown-alert-title' }, node.title), - h(options, 'div', { className: 'markdown-alert-content' }, node.children.map((child, index) => renderBlockOctane(child, options, `${key}:${index}`))), + foldable ? 'details' : 'div', + { key, ...(foldable && { open }), className: `markdown-alert markdown-alert-${node.kind.toLowerCase()}` }, + h(options, foldable ? 'summary' : 'p', { className: 'markdown-alert-title' }, node.title), + h(options, 'div', { className: 'markdown-alert-content' }, renderBlocks(node.children, options, key)), ) + } case 'component': return renderComponentOctane(node, options, key) } @@ -132,6 +135,10 @@ export function renderInlineOctane(node: InlineNode, options: MarkdownOctaneOpti } } +function renderBlocks(nodes: BlockNode[], options: MarkdownOctaneOptions, key?: string) { + return nodes.map((child, index) => renderBlockOctane(child, options, `${key}:${index}`)) +} + function renderInlines(nodes: InlineNode[], options: MarkdownOctaneOptions): OctaneNode[] { return nodes.map((node, index) => renderInlineOctane(node, options, `i:${index}`)) } @@ -295,7 +302,7 @@ function renderComponentOctane(node: ComponentNode | InlineComponentNode, option return h(options, tag, { key, ...props }, node.type === 'inlineComponent' ? renderInlines(node.children, options) - : node.children.map((child, index) => renderBlockOctane(child, options, `${key}:${index}`))) + : renderBlocks(node.children, options, key)) } function renderHeadingAnchorOctane(id: string | undefined, options: MarkdownOctaneOptions): OctaneNode { diff --git a/src/parser.ts b/src/parser.ts index f0b31ea..dfd0a42 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -21,14 +21,13 @@ interface BlockParseBudget { } const maxBlockDepth = 64 +const fenceStart = /^( {0,3})(`{3,}|~{3,})(.*)$/ export function parseMarkdown(markdown: string, options: ParseOptions = {}): MarkdownDocument { - const normalized = normalizeInput(markdown) - const frontmatterEnabled = options.frontmatter !== false - let lines = normalized.split('\n') + let lines = normalizeInput(markdown).split('\n') let frontmatter: string | undefined - if (frontmatterEnabled && lines[0] === '---') { + if (options.frontmatter !== false && lines[0] === '---') { const end = lines.findIndex((line, index) => index > 0 && line === '---') if (end > 0) { frontmatter = lines.slice(1, end).join('\n') @@ -36,28 +35,26 @@ export function parseMarkdown(markdown: string, options: ParseOptions = {}): Mar } } - const definitions = extractDefinitions(lines) - lines = definitions.lines + const { lines: content, references, footnotes } = extractDefinitions(lines) const footnoteOrder: string[] = [] const footnoteCounts: Record = Object.create(null) - const hasReferences = Object.keys(definitions.references).length > 0 - const hasFootnotes = Object.keys(definitions.footnotes).length > 0 + const hasReferences = Object.keys(references).length + const hasFootnotes = Object.keys(footnotes).length const parseOptions = hasReferences || hasFootnotes ? { ...options, - ...(hasReferences && { references: definitions.references }), - ...(hasFootnotes && { footnotes: definitions.footnotes, footnoteOrder, footnoteCounts }), + ...(hasReferences && { references }), + ...(hasFootnotes && { footnotes, footnoteOrder, footnoteCounts }), } : options const slugger = createSlugger() - const parser = createBlockParser(lines, parseOptions, slugger) - const children = parser.parse() - if (hasFootnotes && footnoteOrder.length > 0) { - children.push(createFootnotesBlock(definitions.footnotes, footnoteOrder, parseOptions, slugger)) + const children = createBlockParser(content, parseOptions, slugger).parse() + if (footnoteOrder.length) { + children.push(createFootnotesBlock(footnotes, footnoteOrder, parseOptions, slugger)) } - let document: MarkdownDocument = frontmatter === undefined ? { type: 'root', children } : { type: 'root', frontmatter, children } + let document: MarkdownDocument = { type: 'root', ...(frontmatter !== undefined && { frontmatter }), children } for (const extension of parseOptions.extensions ?? []) { document = extension.transformDocument?.(document, { options: parseOptions }) ?? document @@ -98,15 +95,9 @@ function createBlockParser( continue } - const extensionNode = parseExtensionBlock() - if (extensionNode) { - nodes.push(extensionNode) - continue - } - // Letter-led text cannot open a fence, heading, rule, quote, or list. // It can still be a table header, so table detection remains below. - const node = + const node = parseExtensionBlock() ?? (/^[a-z]/i.test(current()) ? undefined : ( parseFence() ?? parseHeading() ?? @@ -125,6 +116,10 @@ function createBlockParser( return nodes } + function createNestedParser(lines: string[]) { + return createBlockParser(lines, options, slugger, budget) + } + function parseExtensionBlock(): BlockNode | undefined { for (const extension of options.extensions ?? []) { let consumed = 0 @@ -133,7 +128,7 @@ function createBlockParser( index: cursor, options: options, parseInline: value => parseInline(value, options), - parseBlocks: value => createBlockParser(normalizeInput(value).split('\n'), options, slugger, budget).parse(), + parseBlocks: value => createNestedParser(normalizeInput(value).split('\n')).parse(), consume: lines => { consumed = lines }, @@ -149,7 +144,7 @@ function createBlockParser( } function parseFence(): CodeBlockNode | undefined { - const match = current().match(/^( {0,3})(`{3,}|~{3,})(.*)$/) + const match = fenceStart.exec(current()) if (!match) return undefined const fence = match[2]! @@ -180,12 +175,12 @@ function createBlockParser( const depth = match[1]!.length as HeadingNode['depth'] const rawValue = match[2] ?? '' - const value = (/^#+[ \t]*$/.test(rawValue) ? '' : rawValue.replace(/[ \t]+#+[ \t]*$/, '')).trim() + const value = rawValue.replace(/(?:^|[ \t]+)#+[ \t]*$/, '').trim() const children = parseInline(value, options) const id = createHeadingId(children) cursor++ - return id ? { type: 'heading', depth, id, children } : { type: 'heading', depth, children } + return { type: 'heading', depth, ...(id && { id }), children } } function parseThematicBreak(): BlockNode | undefined { @@ -211,7 +206,7 @@ function createBlockParser( return { type: 'blockquote', - children: createBlockParser(quoted, options, slugger, budget).parse(), + children: createNestedParser(quoted).parse(), } } @@ -257,24 +252,19 @@ function createBlockParser( if (leadingSpaces(following) < marker.contentIndent) break while (cursor < nextIndex) itemLines.push(stripIndent(inputLines[cursor++]!, marker.contentIndent)) - continue - } - if (leadingSpaces(line) >= marker.contentIndent) { + } else if (leadingSpaces(line) >= marker.contentIndent) { itemLines.push(stripIndent(line, marker.contentIndent)) cursor++ - continue + } else { + if (isBlockStart(line, next())) break + itemLines.push(line.trimStart()) + cursor++ } - if (isBlockStart(line, next())) break - itemLines.push(line.trimStart()) - cursor++ } - const parser = createBlockParser(itemLines, options, slugger, budget) - const children = parser.parse() + const parser = createNestedParser(itemLines) + items.push({ type: 'listItem', children: parser.parse(), ...(checked !== undefined && { checked }) }) loose ||= parser.loose - const item: ListItemNode = { type: 'listItem', children } - if (checked !== undefined) item.checked = checked - items.push(item) } return { @@ -314,25 +304,18 @@ function createBlockParser( } function parseHtmlBlock(): BlockNode | undefined { - if (!options.allowHtml || !/^ {0,3}<([A-Za-z][\w:-]*|!--|\/[A-Za-z])/.test(current())) return undefined - - const html: string[] = [] - if (/^ {0,3}')) break - } - return { type: 'html', value: html.join('\n') } - } - - while (cursor < inputLines.length && !isBlank(current())) { - html.push(current()) - cursor++ + if (!options.allowHtml) return + const startTag = /^ {0,3}<(?:[A-Za-z]|(!--)|\/[A-Za-z])/.exec(current()) + if (!startTag) return + + const start = cursor + if (startTag[1]) { + while (cursor < inputLines.length && !inputLines[cursor++]!.includes('-->')) {} + } else { + while (cursor < inputLines.length && !isBlank(current())) cursor++ } - return { type: 'html', value: html.join('\n') } + return { type: 'html', value: inputLines.slice(start, cursor).join('\n') } } function parseParagraph(): BlockNode { @@ -396,10 +379,10 @@ function extractDefinitions(lines: string[]) { while (index < lines.length) { const line = lines[index]! - const fence = (!activeFence || line.includes(activeFence)) && line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/) + const fence = (!activeFence || line.includes(activeFence)) && fenceStart.exec(line) if (fence) { - if (!activeFence) activeFence = fence[1]! - else if (fence[1]!.startsWith(activeFence) && isBlank(fence[2]!)) activeFence = '' + if (!activeFence) activeFence = fence[2]! + else if (fence[2]!.startsWith(activeFence) && isBlank(fence[3]!)) activeFence = '' } else if (!activeFence) { const footnote = line.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/) if (footnote) { @@ -489,19 +472,20 @@ function listMarker(line: string): if (!match) return undefined const marker = match[2]! - const ordered = /\d/.test(marker[0]!) + const ordered = marker.length > 1 + const indent = match[1]!.length return { ordered, ...(ordered && { number: Number.parseInt(marker, 10) }), - indent: match[1]!.length, + indent, marker: ordered ? marker.at(-1)! : marker, - contentIndent: match[1]!.length + marker.length + (match[3]?.length ?? 1), + contentIndent: indent + marker.length + (match[3]?.length ?? 1), content: match[4] ?? '', } } function leadingSpaces(line: string): number { - return line.match(/^ */)?.[0].length ?? 0 + return /^ */.exec(line)![0].length } function isBlockStart(line: string, next?: string): boolean { @@ -516,7 +500,7 @@ function isBlockStart(line: string, next?: string): boolean { function looksLikeTableHeader(header: string, delimiter: string): boolean { if (!header.includes('|')) return false const cells = splitTableRow(delimiter) - return cells.length === splitTableRow(header).length && cells.every(cell => /^:?-+:?$/.test(cell.trim())) + return cells.length === splitTableRow(header).length && cells.every(cell => /^:?-+:?$/.test(cell)) } function splitTableRow(value: string): string[] { @@ -543,11 +527,8 @@ function splitTableRow(value: string): string[] { } function parseAlign(value: string): 'left' | 'center' | 'right' | undefined { - const trimmed = value.trim() - if (trimmed.startsWith(':') && trimmed.endsWith(':')) return 'center' - if (trimmed.endsWith(':')) return 'right' - if (trimmed.startsWith(':')) return 'left' - return undefined + if (value.startsWith(':')) return value.endsWith(':') ? 'center' : 'left' + if (value.endsWith(':')) return 'right' } function cell(value: string, options: ParseOptions): TableCellNode { diff --git a/src/react.ts b/src/react.ts index e67931d..5432dd8 100644 --- a/src/react.ts +++ b/src/react.ts @@ -28,7 +28,7 @@ export function Markdown({ children, ...options }: MarkdownProps): ReactElement export function renderMarkdownReact(input: MarkdownInput, options: MarkdownReactOptions = {}): ReactNode { const document = typeof input === 'string' ? parseMarkdown(input, options) : input - return document.children.map((node, index) => renderBlockReact(node, options, `b:${index}`)) + return renderBlocks(document.children, options, 'b') } export function renderBlockReact(node: BlockNode, options: MarkdownReactOptions = {}, key?: string): ReactElement { @@ -57,7 +57,7 @@ export function renderBlockReact(node: BlockNode, options: MarkdownReactOptions ) } case 'blockquote': - return h(options, 'blockquote', { key }, node.children.map((child, index) => renderBlockReact(child, options, `${key}:${index}`))) + return h(options, 'blockquote', { key }, renderBlocks(node.children, options, key)) case 'table': return h( options, @@ -83,14 +83,17 @@ export function renderBlockReact(node: BlockNode, options: MarkdownReactOptions return options.allowHtml ? h(options, 'div', { key, dangerouslySetInnerHTML: { __html: node.value } }) : h(options, 'p', { key }, node.value) - case 'callout': + case 'callout': { + const { open } = node + const foldable = open !== undefined return h( options, - 'div', - { key, className: `markdown-alert markdown-alert-${node.kind.toLowerCase()}` }, - h(options, 'p', { className: 'markdown-alert-title' }, node.title), - h(options, 'div', { className: 'markdown-alert-content' }, node.children.map((child, index) => renderBlockReact(child, options, `${key}:${index}`))), + foldable ? 'details' : 'div', + { key, ...(foldable && { open }), className: `markdown-alert markdown-alert-${node.kind.toLowerCase()}` }, + h(options, foldable ? 'summary' : 'p', { className: 'markdown-alert-title' }, node.title), + h(options, 'div', { className: 'markdown-alert-content' }, renderBlocks(node.children, options, key)), ) + } case 'component': return renderComponentReact(node, options, key) } @@ -140,6 +143,10 @@ export function renderInlineReact(node: InlineNode, options: MarkdownReactOption } } +function renderBlocks(nodes: BlockNode[], options: MarkdownReactOptions, key?: string) { + return nodes.map((child, index) => renderBlockReact(child, options, `${key}:${index}`)) +} + function renderInlines(nodes: InlineNode[], options: MarkdownReactOptions): ReactNode[] { return nodes.map((node, index) => renderInlineReact(node, options, `i:${index}`)) } @@ -306,7 +313,7 @@ function renderComponentReact(node: ComponentNode | InlineComponentNode, options return h(options, tag, { key, ...props }, node.type === 'inlineComponent' ? renderInlines(node.children, options) - : node.children.map((child, index) => renderBlockReact(child, options, `${key}:${index}`))) + : renderBlocks(node.children, options, key)) } function renderHeadingAnchorReact(id: string | undefined, options: MarkdownReactOptions): ReactNode { diff --git a/src/types.ts b/src/types.ts index 442b4de..dd0db27 100644 --- a/src/types.ts +++ b/src/types.ts @@ -100,6 +100,8 @@ export interface CalloutNode { type: 'callout' kind: string title: string + /** Initial disclosure state. Omit for a static callout. */ + open?: boolean children: BlockNode[] } diff --git a/tests/docs-extensions.test.ts b/tests/docs-extensions.test.ts index 405c397..ff7b660 100644 --- a/tests/docs-extensions.test.ts +++ b/tests/docs-extensions.test.ts @@ -1,16 +1,47 @@ +import { renderToStaticMarkup as renderOctane } from 'octane/server' +import { createElement } from 'react' +import { renderToStaticMarkup as renderReact } from 'react-dom/server' import { describe, expect, it } from 'vitest' import { parseMarkdown, renderHtml } from '../src/index.js' import { docsMarkdownExtensions } from '../src/extensions/docs.js' +import { Markdown as OctaneMarkdown } from '../src/octane.js' +import { Markdown as ReactMarkdown } from '../src/react.js' const docs = docsMarkdownExtensions() describe('docs markdown extensions', () => { it('renders GitHub-style callouts', () => { - const html = renderHtml('> [!TIP] Custom title\n> Use `redirect_from`.', { + const document = parseMarkdown('> [!TIP] Custom title\n> Use `redirect_from`.', { extensions: docs, }) + expect(document.children[0]).not.toHaveProperty('open') - expect(html).toBe('

    Custom title

    Use redirect_from.

    ') + const html = '

    Custom title

    Use redirect_from.

    ' + expect(renderHtml(document)).toBe(html) + expect(renderReact(createElement(ReactMarkdown, { children: document }))).toBe(html) + expect(renderOctane(OctaneMarkdown, { children: document }).html).toBe(html) + }) + + it.each([ + ['-', 'Polyfill ', 'Polyfill <requirements>', false], + ['+', '', 'Tip', true], + ] as const)('renders %s callouts with native disclosure in every renderer', (marker, title, escapedTitle, open) => { + const source = `> [!TIP]${marker}${title && ` ${title}`}\n> Use **this** polyfill.` + const options = { extensions: docs } + const document = parseMarkdown(source, options) + expect(document.children[0]).toMatchObject({ + type: 'callout', + kind: 'tip', + title: title || 'Tip', + open, + }) + + const classes = 'class="markdown-alert markdown-alert-tip"' + const content = `${escapedTitle}

    Use this polyfill.

    ` + expect(renderHtml(document)).toBe(`${content}`) + const expectedFrameworkMarkup = `${content}` + expect(renderReact(createElement(ReactMarkdown, { children: document }))).toBe(expectedFrameworkMarkup) + expect(renderOctane(OctaneMarkdown, { children: document }).html).toBe(expectedFrameworkMarkup) }) it('renders heading anchors and collects headings', () => {