diff --git a/README.md b/README.md index 6555c36..d2e1e54 100644 --- a/README.md +++ b/README.md @@ -142,3 +142,30 @@ Any unrecognized elements (e.g. `
`, ``, `
`) render their chi ## License [MIT](./LICENSE) + +### Custom serialization of resolved nodes + +`renderToMarkdownString(element, { serializers })` optionally overrides named +host elements after React resolves their components. Omitting this option keeps +the existing Markdown output. A serializer returns `undefined` to delegate, or a +string to replace that element's output: + +```tsx +await renderToMarkdownString(
, { + serializers: { + section(node, context) { + return context.defaultSerialize(node); + }, + }, +}); +``` + +The callback receives a resolved tree of `element` nodes (`name`, `props`, and +`children`) and `text` nodes (`value`). `props` omits the original React +`children`; use the resolved `children` instead. `context.serialize(node)` applies +custom serializers, while `context.defaultSerialize(node)` uses the built-in +serializer for that node and still applies overrides to its descendants. +Callbacks run after commit and must not call Hooks or mutate nodes. Components +retain normal Context, Hooks, and parent-child execution; serializers do not +execute components a second time. A thrown serializer error rejects the render +promise. Options belong to one render call and are safe to use concurrently. diff --git a/src/react/index.ts b/src/react/index.ts index c09dae2..78d5667 100644 --- a/src/react/index.ts +++ b/src/react/index.ts @@ -1 +1,6 @@ export { renderToMarkdownString } from './render'; +export type { + ResolvedMarkdownNode, + MarkdownSerializationContext, + RenderToMarkdownOptions, +} from './render'; diff --git a/src/react/render.ts b/src/react/render.ts index b129b69..d232978 100644 --- a/src/react/render.ts +++ b/src/react/render.ts @@ -200,14 +200,20 @@ function getBlockSeparator( return '\n\n'; } -function childToMarkdown(child: MarkdownNode | TextNode): string { +function childToMarkdown( + child: MarkdownNode | TextNode, + options: RenderToMarkdownOptions, +): string { if (child instanceof TextNode) { return child.text; } - return toMarkdown(child); + return toMarkdown(child, options); } -function renderChildren(root: MarkdownNode): string { +function renderChildren( + root: MarkdownNode, + options: RenderToMarkdownOptions, +): string { const { children } = root; if (children.length === 0) { @@ -220,7 +226,7 @@ function renderChildren(root: MarkdownNode): string { let previousMarkdown = ''; for (const child of children) { - const markdown = childToMarkdown(child); + const markdown = childToMarkdown(child, options); const separator = shouldSeparateBlocks && previousChild ? getBlockSeparator(previousChild, child, previousMarkdown, markdown) @@ -241,12 +247,99 @@ function renderChildren(root: MarkdownNode): string { return parts.join(''); } +/** A snapshot of a host node after React has resolved components. */ +export type ResolvedMarkdownNode = + | { readonly type: 'text'; readonly value: string } + | { + readonly type: 'element'; + readonly name: string; + readonly props: Readonly>; + readonly children: readonly ResolvedMarkdownNode[]; + }; + +export interface MarkdownSerializationContext { + /** Serialize a resolved subtree, applying the custom serializer. */ + serialize(node: ResolvedMarkdownNode): string; + /** Use the built-in serializer for this node, retaining child overrides. */ + defaultSerialize(node: ResolvedMarkdownNode): string; +} + +export interface RenderToMarkdownOptions { + /** + * Optionally serialize resolved host nodes. Return undefined to retain the + * built-in behavior. Components still execute in their normal React tree. + * This hook runs after commit; it must not call React hooks or mutate nodes. + */ + serializers?: Readonly< + Record< + string, + ( + node: ResolvedMarkdownNode, + context: MarkdownSerializationContext, + ) => string | undefined + > + >; +} + +function snapshot( + node: MarkdownNode | TextNode, + originals: WeakMap, +): ResolvedMarkdownNode { + if (node instanceof TextNode) { + const result = { type: 'text', value: node.text } as const; + originals.set(result, node); + return result; + } + const { children: _children, ...props } = node.props; + const result = { + type: 'element', + name: node.type, + props, + children: node.children.map((child) => snapshot(child, originals)), + } as const; + originals.set(result, node); + return result; +} + +function restore(node: ResolvedMarkdownNode): MarkdownNode | TextNode { + if (node.type === 'text') return new TextNode(node.value); + const result = new MarkdownNode(node.name, { ...node.props }); + for (const child of node.children) result.appendChild(restore(child)); + return result; +} + // Convert node tree to Markdown string -function toMarkdown(root: MarkdownNode): string { +function toMarkdown( + root: MarkdownNode, + options: RenderToMarkdownOptions = {}, + useOverride = true, +): string { + const serializer = options.serializers?.[root.type]; + if (useOverride && serializer) { + const originals = new WeakMap< + ResolvedMarkdownNode, + MarkdownNode | TextNode + >(); + const resolved = snapshot(root, originals); + const serialize = ( + node: ResolvedMarkdownNode, + override: boolean, + ): string => { + const restored = originals.get(node) ?? restore(node); + return restored instanceof TextNode + ? restored.text + : toMarkdown(restored, options, override); + }; + const result = serializer(resolved, { + serialize: (node) => serialize(node, true), + defaultSerialize: (node) => serialize(node, false), + }); + if (result !== undefined) return result; + } const { type, props, children } = root; // Get children's Markdown lazily so ignored nodes do not serialize children. - const getChildrenMarkdown = () => renderChildren(root); + const getChildrenMarkdown = () => renderChildren(root, options); // Generate corresponding Markdown based on element type switch (type) { @@ -326,7 +419,7 @@ function toMarkdown(root: MarkdownNode): string { case 'tr': { const cells = children .filter((child): child is MarkdownNode => child instanceof MarkdownNode) - .map((cell) => toMarkdown(cell).trim()); + .map((cell) => toMarkdown(cell, options).trim()); // If it's a header row, add separator if (root.parent && root.parent.type === 'thead') { @@ -347,6 +440,7 @@ function toMarkdown(root: MarkdownNode): string { // Render function (SSR-like behavior: neither useEffect nor useLayoutEffect run) export async function renderToMarkdownString( element: React.ReactElement, + options: RenderToMarkdownOptions = {}, ): Promise { const container = new MarkdownNode('root'); @@ -380,14 +474,20 @@ export async function renderToMarkdownString( try { // Set up a promise that resolves when commit completes let resolveCommit: ((arg: string) => void) | null = null; - const commitPromise = new Promise((resolve) => { + let rejectCommit: (error: unknown) => void; + const commitPromise = new Promise((resolve, reject) => { resolveCommit = resolve; + rejectCommit = reject; }); reconciler.updateContainer(element, root, null, () => { // This callback is called after commit if (resolveCommit) { - resolveCommit(toMarkdown(container)); + try { + resolveCommit(toMarkdown(container, options)); + } catch (error) { + rejectCommit(error); + } } }); diff --git a/src/react/serialize-node.test.tsx b/src/react/serialize-node.test.tsx new file mode 100644 index 0000000..2f7122b --- /dev/null +++ b/src/react/serialize-node.test.tsx @@ -0,0 +1,142 @@ +import { createContext, useContext, useState } from 'react'; +import { describe, expect, it } from 'vitest'; +import { type RenderToMarkdownOptions, renderToMarkdownString } from './render'; + +describe('resolved host-node serializers', () => { + it('executes components in their normal tree before serialization', async () => { + const Value = createContext('default'); + const calls: string[] = []; + function Child() { + const [suffix] = useState('!'); + const value = useContext(Value); + calls.push(value); + return ( + + {value} + {suffix} + + ); + } + const options: RenderToMarkdownOptions = { + serializers: { + section(node, context) { + if (node.type !== 'element') return undefined; + expect(node.children).toEqual([ + { + type: 'element', + name: 'a', + props: { href: '/docs' }, + children: [ + { type: 'text', value: 'provided' }, + { type: 'text', value: '!' }, + ], + }, + ]); + return `(${context.defaultSerialize(node)})`; + }, + }, + }; + expect( + await renderToMarkdownString( + +
+ +
+
, + options, + ), + ).toBe('([provided!](/docs))'); + expect(calls).toEqual(['provided']); + }); + + it('delegates unchanged nodes and applies overrides to nested children', async () => { + expect( + await renderToMarkdownString( +
+ A + B +
, + { + serializers: { + section: (node, context) => context.defaultSerialize(node), + span: (node, context) => `[${context.defaultSerialize(node)}]`, + }, + }, + ), + ).toBe('[A][B]'); + expect( + await renderToMarkdownString(

Hello

, { + serializers: { p: () => undefined }, + }), + ).toBe('Hello\n\n'); + }); + + it('retains parent context when delegating an existing node', async () => { + const tree = ( +
    +
  1. first
  2. +
  3. second
  4. +
+ ); + const expected = await renderToMarkdownString(tree); + expect( + await renderToMarkdownString(tree, { + serializers: { li: (node, context) => context.defaultSerialize(node) }, + }), + ).toBe(expected); + }); + + it('preserves ownership when a parent duplicates or suppresses children', async () => { + function Twice({ children }: { children: React.ReactNode }) { + return ( + <> + {children} + {children} + + ); + } + function Ignore({ children: _children }: { children: React.ReactNode }) { + return null; + } + expect( + await renderToMarkdownString( + <> + + X + + + Y + + , + { + serializers: { + span: (node, context) => `(${context.defaultSerialize(node)})`, + }, + }, + ), + ).toBe('(X)(X)'); + }); + + it('rejects serializer errors without throwing out of the commit callback', async () => { + await expect( + renderToMarkdownString(test, { + serializers: { + span() { + throw new Error('serialization failed'); + }, + }, + }), + ).rejects.toThrow('serialization failed'); + }); + + it('keeps concurrent serializers isolated', async () => { + const outputs = await Promise.all( + ['first', 'second'].map((label) => + renderToMarkdownString(value, { + serializers: { span: () => label }, + }), + ), + ); + expect(outputs).toEqual(['first', 'second']); + }); +});