Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/foldable-callouts.md
Original file line number Diff line number Diff line change
@@ -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.
35 changes: 15 additions & 20 deletions src/extensions/callouts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,28 @@ export function calloutsExtension(): MarkdownExtension {
}
}

export function parseCalloutBlock(context: Parameters<NonNullable<MarkdownExtension['parseBlock']>>[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<NonNullable<MarkdownExtension['parseBlock']>>[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()
}
16 changes: 4 additions & 12 deletions src/extensions/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
44 changes: 22 additions & 22 deletions src/extensions/tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand Down
58 changes: 28 additions & 30 deletions src/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -28,7 +27,7 @@ export function renderBlock(node: BlockNode, options: RenderOptions = {}): strin
return `<${tag}${start}>\n${items}\n</${tag}>`
}
case 'blockquote':
return `<blockquote>\n${node.children.map(child => renderBlock(child, options)).join('\n')}\n</blockquote>`
return `<blockquote>\n${renderBlocks(node.children, options)}\n</blockquote>`
case 'table': {
const header = `<thead><tr>${node.header.map((cell, index) => renderTableCell('th', cell, node.align[index], options)).join('')}</tr></thead>`
const body = node.rows.length
Expand All @@ -44,8 +43,12 @@ export function renderBlock(node: BlockNode, options: RenderOptions = {}): strin
return '<hr>'
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)}</${titleTag}><div class="markdown-alert-content">${renderBlocks(node.children, options)}</div></${tag}>`
}
case 'component':
return renderComponent(node, options)
}
Expand Down Expand Up @@ -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 {
Expand All @@ -91,7 +98,8 @@ function renderInlines(nodes: InlineNode[], options: RenderOptions): string {

function renderCodeBlock(node: Extract<BlockNode, { type: 'code' }>, 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)}"` : '')
Expand All @@ -102,10 +110,10 @@ function renderCodeBlock(node: Extract<BlockNode, { type: 'code' }>, options: Re
...(options.codeLineNumbers !== undefined && { lineNumbers: options.codeLineNumbers }),
}) ?? escapeHtml(node.value)

const pre = `<pre ${preAttrs}><code class="language-${escapeAttr(lang)}">${html}</code></pre>`
const pre = `<pre ${preAttrs}><code class="language-${escapedLang}">${html}</code></pre>`
if (!node.title) return pre

return `<figure class="tm-code-frame" data-lang="${escapeAttr(lang)}"><figcaption>${escapeHtml(node.title)}</figcaption>${pre}</figure>`
return `<figure class="tm-code-frame" data-lang="${escapedLang}"><figcaption>${escapeHtml(node.title)}</figcaption>${pre}</figure>`
}

function renderListItemChildren(children: BlockNode[], checked: boolean | undefined, loose: boolean | undefined, options: RenderOptions): string {
Expand All @@ -120,12 +128,6 @@ function renderListItemChildren(children: BlockNode[], checked: boolean | undefi
return result
}

function renderCallout(node: Extract<BlockNode, { type: 'callout' }>, options: RenderOptions): string {
const kind = node.kind.toLowerCase()
const children = node.children.map(child => renderBlock(child, options)).join('\n')
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>`
}

function renderFootnotes(items: FootnoteItemNode[], options: RenderOptions): string {
const renderedItems = items.map(item => `<li id="user-content-fn-${escapeAttr(item.id)}">\n${renderFootnoteItem(item, options)}\n</li>`).join('\n')
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>`
Expand Down Expand Up @@ -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<string, string> = {
...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}</${tag}>`
}

Expand Down Expand Up @@ -193,16 +204,3 @@ function renderHeadingAnchor(id: string | undefined, options: RenderOptions): st
const anchorOptions = typeof headingAnchors === 'object' ? headingAnchors : {}
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>`
}

function renderComponentAttrs(node: ComponentNode | InlineComponentNode): string {
const props: Record<string, string> = {
...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('')
}
23 changes: 15 additions & 8 deletions src/octane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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)
}
Expand Down Expand Up @@ -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}`))
}
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading