Skip to content
Closed
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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,30 @@ Any unrecognized elements (e.g. `<div>`, `<span>`, `<section>`) 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(<section><Article /></section>, {
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.
5 changes: 5 additions & 0 deletions src/react/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export { renderToMarkdownString } from './render';
export type {
ResolvedMarkdownNode,
MarkdownSerializationContext,
RenderToMarkdownOptions,
} from './render';
118 changes: 109 additions & 9 deletions src/react/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
Expand All @@ -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<Record<string, unknown>>;
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, MarkdownNode | TextNode>,
): 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) {
Expand Down Expand Up @@ -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') {
Expand All @@ -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<string> {
const container = new MarkdownNode('root');

Expand Down Expand Up @@ -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<string>((resolve) => {
let rejectCommit: (error: unknown) => void;
const commitPromise = new Promise<string>((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);
}
}
});

Expand Down
142 changes: 142 additions & 0 deletions src/react/serialize-node.test.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<a href="/docs">
{value}
{suffix}
</a>
);
}
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(
<Value.Provider value="provided">
<section>
<Child />
</section>
</Value.Provider>,
options,
),
).toBe('([provided!](/docs))');
expect(calls).toEqual(['provided']);
});

it('delegates unchanged nodes and applies overrides to nested children', async () => {
expect(
await renderToMarkdownString(
<section>
<span>A</span>
<span>B</span>
</section>,
{
serializers: {
section: (node, context) => context.defaultSerialize(node),
span: (node, context) => `[${context.defaultSerialize(node)}]`,
},
},
),
).toBe('[A][B]');
expect(
await renderToMarkdownString(<p>Hello</p>, {
serializers: { p: () => undefined },
}),
).toBe('Hello\n\n');
});

it('retains parent context when delegating an existing node', async () => {
const tree = (
<ol>
<li>first</li>
<li>second</li>
</ol>
);
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(
<>
<Twice>
<span>X</span>
</Twice>
<Ignore>
<span>Y</span>
</Ignore>
</>,
{
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(<span>test</span>, {
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(<span>value</span>, {
serializers: { span: () => label },
}),
),
);
expect(outputs).toEqual(['first', 'second']);
});
});