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
20 changes: 19 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ packages/comark/
│ │ ├── indent.ts # Dedent of outdented component children
│ │ ├── unwrap.ts # `unwrap` option
│ │ └── auto-unwrap.ts # `autoUnwrap` option
│ └── stringify/ # AST → markdown string rendering (handlers/ per tag)
│ └── stringify/ # AST → markdown string rendering (handlers/ per tag; transform-node.ts runs `transformNode`)
├── SPEC/ # Behavioral spec fixtures (CommonMark, GFM, HTML, COMARK, auto-close.md)
├── test/ # Vitest test files
├── package.json
Expand Down Expand Up @@ -507,7 +507,10 @@ import {
HTML_VOID_ELEMENTS,
isMarkdownDocument,
sanitizeData,
applyNodeTransforms, // runs a renderer's `transformNode` for one node (used by every renderer)
mergeNodeTransforms, // merges two `transformNode` values into one stable list
} from 'comark/utils'
import type { NodeTransform, NodeTransformContext, NodeTransformResult } from 'comark'
import { noopTracer, withSpan } from 'comark/utils/trace'

// Core plugins — use when calling parseMarkdown() directly (framework-agnostic)
Expand Down Expand Up @@ -785,6 +788,21 @@ the open tag. `<style>`, `<pre>`, `<script>`, `<textarea>`, and block-level `<!-
opener, trailing text after that closer, indented child tag inside a multiline
`<a>`) are skipped tests in `test/html-block.test.ts` — do not weaken them.

## Render-time node transforms

Every renderer accepts `transformNode`, a function or array of functions that may
return a new `tag` and/or `props` for an element node. Each renderer calls
`applyNodeTransforms()` (`src/internal/stringify/transform-node.ts`, exported from
`comark/utils`) right after `resolveAttributes()` and before component lookup, so a
new tag goes through `components` and `componentsManifest`. Hooks always get props
resolved with `parseJson: true`, in every renderer, so one hook works everywhere. The string engine does it
in `one()` (`src/internal/stringify/state.ts`) and renders a copy of the node only when
the hook changes something; untouched nodes keep rendering from their raw attributes. The
returned tag and props are used as-is, not sanitized: transforms are trusted developer
code, and their security is the developer's responsibility. Children
see the returned props as `renderData.props`. Docs:
`docs/content/5.reference/3.reference.md` ("Transforming nodes before render").

## Vue/React/Svelte/Angular Components

### Markdown Component (High-level)
Expand Down
34 changes: 34 additions & 0 deletions docs/content/3.rendering/2.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ This is a **bold** statement with a [link](https://example.com).
| [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins |
| [`components`](#components) | `Record<string, fn>` | `{}` | Custom component renderers |
| [`data`](#data) | `Record<string, any>` | `undefined` | Data passed to component renderers |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |
| `autoClose` | `boolean` | `true` | Close incomplete Markdown and components before parsing |
| `autoUnwrap` | `boolean` | `true` | Remove a single paragraph wrapper inside components |
| `linkify` | `boolean` | `true` | Convert URL-like text into links |
Expand Down Expand Up @@ -177,6 +178,38 @@ Welcome!

::

#### `transformNode`

Change an element's tag or props right before it renders, using values that are only known at render time. The function receives the node's `tag`, its resolved `props`, and the render context. It returns a new `tag`, new `props`, or nothing to keep the node as it is. See [Transforming nodes before render](/reference/reference#transforming-nodes-before-render) for the full rules.

::code-group

```typescript
import { renderHtml } from '@comark/html'

const user = { id: 42 }

const html = await renderHtml(`
::cta
Open your dashboard
::
`, {
// Render every `::cta` as a link to the user's dashboard
transformNode: ({ tag, props }) =>
tag === 'cta' ? { tag: 'a', props: { ...props, href: `/users/${user.id}/dashboard` } } : undefined,
})
```

```html [Output]
<a href="/users/42/dashboard">Open your dashboard</a>
```

::

Comark renders what the function returns as-is, without sanitizing it, and the [security plugin](/plugins/built-in/security) doesn't apply to it. Validate anything you build from untrusted data, such as URLs from `data`.

A returned tag goes through `components` like any other tag.

### `createHtmlRenderer()`

Creates a reusable parse+render function. The underlying parser is initialized once and reused on every call, which is more efficient when rendering many documents.
Expand Down Expand Up @@ -239,6 +272,7 @@ const html = await renderHtmlFromDocument(document)
| --- | --- | --- |
| [`components`](#components) | `Record<string, fn>` | Custom component renderers |
| [`data`](#data) | `Record<string, any>` | Data passed to component renderers |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | Change the tag or props of element nodes right before they render |

---

Expand Down
34 changes: 34 additions & 0 deletions docs/content/3.rendering/3.vue.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ Passing a document to `<Markdown>` skips parsing at runtime, but the **parser is
| `summary` | `boolean` | `false` | Only render content before `<!-- more -->` |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append caret to last text node |
| [`data`](#data) | `Record<string, unknown>` | `{}` | Runtime values referenced from markdown via `:prop="data.path"` |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |

#### `options`

Expand Down Expand Up @@ -281,6 +282,36 @@ const content = `Hello, :badge{:label="data.user.name"}!`
</template>
```

#### `transformNode`

Change an element's tag or props right before it renders, using values that are only known at render time. The function receives the node's `tag`, its resolved `props`, and the render context. It returns a new `tag`, new `props`, or nothing to keep the node as it is. See [Transforming nodes before render](/reference/reference#transforming-nodes-before-render) for the full rules.

```vue [App.vue]
<script setup lang="ts">
import { Markdown } from '@comark/vue'
import type { NodeTransform } from '@comark/vue'

const user = { id: 42 }
const content = `::cta\nOpen your dashboard\n::`

// Render every `::cta` as a link to the user's dashboard
const transformNode: NodeTransform = ({ tag, props }) => {
if (tag !== 'cta') return
return { tag: 'a', props: { ...props, href: `/users/${user.id}/dashboard` } }
}
</script>

<template>
<Suspense>
<Markdown :value="content" :transform-node="transformNode" />
</Suspense>
</template>
```

Comark renders what the function returns as-is, without sanitizing it, and the [security plugin](/plugins/built-in/security) doesn't apply to it. Validate anything you build from untrusted data, such as URLs from `data`.

Define the function once in `<script setup>`. A new array on every render makes the document render again.

### `defineMarkdownComponent`

Creates a pre-configured `<Markdown>` component with default options, plugins, and components baked in.
Expand Down Expand Up @@ -352,6 +383,7 @@ import { AppMarkdown } from './markdown'
| `registerDefaultPlugins` | `boolean` | `true` | Register default plugins (`frontmatter`, `html`, `alert`, `task-list`, `components`, `attributes`) |
| [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins |
| [`components`](#components) | `Record<string, Component>` | `{}` | Custom Vue component mappings |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Node transforms that run before the instance's own `transformNode` |
| `class` | `string` | `undefined` | Additional CSS classes for the wrapper div |

#### `extends`
Expand Down Expand Up @@ -452,6 +484,7 @@ const document = await res.json()
| [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append a blinking caret to the last text node |
| [`data`](#data) | `Record<string, unknown>` | `{}` | Runtime values referenced from markdown via `:prop="data.path"` |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |

### `defineMarkdownDocumentComponent`

Expand Down Expand Up @@ -503,6 +536,7 @@ const document = await res.json()
| [`extends`](#inheritance) | `ReturnType<typeof defineMarkdownDocumentComponent>` | `undefined` | Inherit component mappings from another renderer |
| `name` | `string` | `undefined` | Component name for debugging |
| [`components`](#components) | `Record<string, Component>` | `{}` | Custom Vue component mappings |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Node transforms that run before the instance's own `transformNode` |
| `class` | `string` | `undefined` | Additional CSS classes for the wrapper div |

#### Inheritance
Expand Down
1 change: 1 addition & 0 deletions docs/content/3.rendering/4.nuxt.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ Pass markdown via the default slot or the `value` prop:
| [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode |
| `summary` | `boolean` | `false` | Only render content before `<!-- more -->` |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append caret to last text node |
| [`transformNode`](/rendering/vue#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |

#### `options`

Expand Down
30 changes: 30 additions & 0 deletions docs/content/3.rendering/5.react.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ Passing a document to `<Markdown>` skips parsing at runtime, but the **parser is
| [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append caret to last text node |
| [`data`](#data) | `Record<string, unknown>` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |
| `className` | `string` | `undefined` | CSS class for wrapper element |
| `...attributes` | `HTMLAttributes<HTMLDivElement>` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `<div>` |

Expand Down Expand Up @@ -239,6 +240,32 @@ export default function App() {
}
```

#### `transformNode`

Change an element's tag or props right before it renders, using values that are only known at render time. The function receives the node's `tag`, its resolved `props`, and the render context. It returns a new `tag`, new `props`, or nothing to keep the node as it is. See [Transforming nodes before render](/reference/reference#transforming-nodes-before-render) for the full rules.

```tsx [App.tsx]
import { Markdown } from '@comark/react'
import type { NodeTransform } from '@comark/react'

const user = { id: 42 }
const content = `::cta\nOpen your dashboard\n::`

// Render every `::cta` as a link to the user's dashboard
const transformNode: NodeTransform = ({ tag, props }) => {
if (tag !== 'cta') return
return { tag: 'a', props: { ...props, href: `/users/${user.id}/dashboard` } }
}

export default function App() {
return <Markdown value={content} transformNode={transformNode} />
}
```

Comark renders what the function returns as-is, without sanitizing it, and the [security plugin](/plugins/built-in/security) doesn't apply to it. Validate anything you build from untrusted data, such as URLs from `data`.

Define the function outside the component, or memoize it. A new array on every render makes the document render again. With `streaming`, `<Markdown>` renders through the client-only `MarkdownClient`, so a Server Component can't pass it a function. Pass `transformNode` from a Client Component instead.

### `defineMarkdownComponent`

Creates a pre-configured `<Markdown>` component with default options, plugins, and components baked in.
Expand Down Expand Up @@ -314,6 +341,7 @@ export default function App() {
| `registerDefaultPlugins` | `boolean` | `true` | Register default plugins (`frontmatter`, `html`, `alert`, `task-list`, `components`, `attributes`) |
| [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins |
| [`components`](#components) | `Record<string, ComponentType>` | `{}` | Custom React component mappings |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Node transforms that run before the instance's own `transformNode` |
| `className` | `string` | `undefined` | Additional CSS classes for the wrapper div |

#### `extends`
Expand Down Expand Up @@ -418,6 +446,7 @@ export default async function DocsPage({ params }: { params: { slug: string } })
| [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append a blinking caret to the last text node |
| [`data`](#data) | `Record<string, unknown>` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |
| `className` | `string` | `undefined` | CSS class for the wrapper `<div>` |
| `...attributes` | `HTMLAttributes<HTMLDivElement>` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `<div>` |

Expand Down Expand Up @@ -468,6 +497,7 @@ export default async function Page({ params }: { params: { slug: string } }) {
| [`extends`](#inheritance) | `ReturnType<typeof defineMarkdownDocumentComponent>` | `undefined` | Inherit component mappings from another renderer |
| `name` | `string` | `undefined` | Component name for debugging |
| [`components`](#components) | `Record<string, ComponentType>` | `{}` | Custom React component mappings |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Node transforms that run before the instance's own `transformNode` |
| `className` | `string` | `undefined` | Additional CSS classes for the wrapper div |

#### Inheritance
Expand Down
28 changes: 28 additions & 0 deletions docs/content/3.rendering/6.svelte.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ Passing a document to `<Markdown>` skips parsing at runtime, but the **parser is
| [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append caret to last text node |
| [`data`](#data) | `Record<string, unknown>` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |
| `class` | `string` | `''` | CSS class for wrapper element |
| `...attributes` | `HTMLAttributes<HTMLDivElement>` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `<div>` |

Expand Down Expand Up @@ -295,6 +296,32 @@ Expose runtime values to markdown authors. Any prop written with a `:` prefix is
<Markdown value={content} data={{ user }} />
```

#### `transformNode`

Change an element's tag or props right before it renders, using values that are only known at render time. The function receives the node's `tag`, its resolved `props`, and the render context. It returns a new `tag`, new `props`, or nothing to keep the node as it is. See [Transforming nodes before render](/reference/reference#transforming-nodes-before-render) for the full rules.

```svelte [App.svelte]
<script lang="ts">
import { Markdown } from '@comark/svelte'
import type { NodeTransform } from '@comark/svelte'

const user = { id: 42 }
const content = `::cta\nOpen your dashboard\n::`

// Render every `::cta` as a link to the user's dashboard
const transformNode: NodeTransform = ({ tag, props }) => {
if (tag !== 'cta') return
return { tag: 'a', props: { ...props, href: `/users/${user.id}/dashboard` } }
}
</script>

<Markdown value={content} {transformNode} />
```

Comark renders what the function returns as-is, without sanitizing it, and the [security plugin](/plugins/built-in/security) doesn't apply to it. Validate anything you build from untrusted data, such as URLs from `data`.

`<MarkdownAsync>` accepts `transformNode` too. The Svelte renderer doesn't pass `parent` to the function.

---

## `<MarkdownAsync>` (experimental)
Expand Down Expand Up @@ -405,6 +432,7 @@ export const load: PageLoad = async ({ params, fetch }) => {
| [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode |
| [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append a blinking caret to the last text node |
| [`data`](#data) | `Record<string, unknown>` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` |
| [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render |
| `class` | `string` | `''` | CSS class for wrapper element |
| `...attributes` | `HTMLAttributes<HTMLDivElement>` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `<div>` |

Expand Down
Loading
Loading