### Installation
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Install the mdast-util-to-hast package using npm.
```APIDOC
## Installation
```bash
npm install mdast-util-to-hast
```
```
--------------------------------
### Install mdast-util-to-hast
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Install the mdast-util-to-hast package using npm.
```bash
npm install mdast-util-to-hast
```
--------------------------------
### Support HTML in Markdown
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example demonstrating how to enable raw HTML processing during the conversion from MDAST to HAST.
```js
import {fromMarkdown} from 'mdast-util-from-markdown'
import {toHast} from 'mdast-util-to-hast'
import {toHtml} from 'hast-util-to-html'
const markdown = 'It works! '
const mdast = fromMarkdown(markdown)
const hast = toHast(mdast, {allowDangerousHtml: true})
const html = toHtml(hast, {allowDangerousHtml: true})
console.log(html)
```
```html
It works!
It works!
` and `` elements for a code block, including a language class.
```html
backtick.fences('for blocks')
```
--------------------------------
### HTML Footnote Example
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example of HTML elements for a footnote reference, including a superscript link.
```html
With a 1.
…
```
--------------------------------
### Convert markdown with GFM footnotes to HTML
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
This example demonstrates converting markdown with GitHub Flavored Markdown (GFM) footnotes into an HTML structure using `mdast-util-from-markdown`, `mdast-util-gfm`, and `mdast-util-to-hast`.
```js
import {toHtml} from 'hast-util-to-html'
import {gfm} from 'micromark-extension-gfm'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {gfmFromMarkdown} from 'mdast-util-gfm'
import {toHast} from 'mdast-util-to-hast'
const markdown = 'Bonjour[^1]\n\n[^1]: Monde!'
const mdast = fromMarkdown(markdown, {
extensions: [gfm()],
mdastExtensions: [gfmFromMarkdown()]
})
const hast = toHast(mdast)
const html = toHtml(hast)
console.log(html)
```
--------------------------------
### HTML Delete Example
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example of an HTML `` element for deleted text, corresponding to Markdown strikethrough.
```html
Two tildes for delete.
```
--------------------------------
### HTML Emphasis Example
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example of an HTML `` element for emphasized text, corresponding to Markdown emphasis.
```html
Some asterisks for emphasis.
```
--------------------------------
### HTML Blockquote Example
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example of an HTML blockquote containing a paragraph, corresponding to a Markdown blockquote.
```html
A greater than…
```
--------------------------------
### Style footnotes with CSS
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example CSS to style footnote sections to match GitHub's rendering.
```css
/* Style the footnotes section. */
.footnotes {
font-size: smaller;
color: #8b949e;
border-top: 1px solid #30363d;
}
/* Hide the section label for visual users. */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
word-wrap: normal;
border: 0;
}
/* Place `[` and `]` around footnote calls. */
[data-footnote-ref]::before {
content: '[';
}
[data-footnote-ref]::after {
content: ']';
}
```
--------------------------------
### HTML Break Example
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Example of an HTML paragraph containing a line break (`
`), corresponding to a Markdown line break.
```html
A backslash
before a line break…
```
--------------------------------
### DOM Clobbering Example
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Illustrates DOM clobbering where an HTML element with an ID is referenced by a script. Using a prefix is a recommended solution.
```html
```
--------------------------------
### Safely process raw HTML in markdown
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Use `hast-util-raw` to convert raw HTML embedded in markdown to proper HTML nodes. This example chains `mdast-util-to-hast` with `allowDangerousHtml: true`, then `hast-util-raw`, and finally `hast-util-sanitize` to ensure safe HTML output.
```js
import {raw} from 'hast-util-raw'
import {sanitize} from 'hast-util-sanitize'
import {toHtml} from 'hast-util-to-html'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {toHast} from 'mdast-util-to-hast'
const markdown = 'It works!
const mdast = fromMarkdown(markdown)
const hast = raw(toHast(mdast, {allowDangerousHtml: true}))
const safeHast = sanitize(hast)
const html = toHtml(safeHast)
console.log(html)
```
--------------------------------
### Override Element Tag Name with data.hName
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Use `data.hName` on an mdast node to specify a custom HTML element tag name for the transformation. This example overrides `strong` to use ``.
```javascript
import {toHast} from 'mdast-util-to-hast'
// Override strong to use instead of
const mdast = {
type: 'strong',
data: {hName: 'b'},
children: [{type: 'text', value: 'Bold text'}]
}
const hast = toHast(mdast)
console.log(hast)
// {
// type: 'element',
// tagName: 'b',
// properties: {},
// children: [{ type: 'text', value: 'Bold text' }]
// }
```
--------------------------------
### Options Configuration
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Configure the transformation behavior with various options.
```APIDOC
## Options Configuration
### Description
Configure the transformation behavior with options including handlers, footnote settings, HTML handling, and clobbering prefix for security.
### Method
Function call with options object
### Endpoint
N/A (JavaScript function)
### Parameters
#### Request Body (Options Object)
- **allowDangerousHtml** (boolean) - Optional - Enable dangerous HTML passthrough.
- **clobberPrefix** (string) - Optional - Prevent DOM clobbering.
- **footnoteLabel** (string) - Optional - The label for footnotes.
- **footnoteLabelTagName** (string) - Optional - The tag name for the footnote label.
- **footnoteLabelProperties** (object) - Optional - Properties for the footnote label element.
### Request Example
```javascript
import {toHast} from 'mdast-util-to-hast'
import {toHtml} from 'hast-util-to-html'
const mdast = {
type: 'root',
children: [
{
type: 'paragraph',
children: [
{type: 'text', value: 'Check out '},
{type: 'html', value: 'inline'},
{type: 'text', value: ' HTML.'}
]
}
]
}
// Enable dangerous HTML passthrough
const hast = toHast(mdast, {
allowDangerousHtml: true,
clobberPrefix: 'user-content-', // Prevent DOM clobbering
footnoteLabel: 'Footnotes',
footnoteLabelTagName: 'h2',
footnoteLabelProperties: {className: ['sr-only']}
})
const html = toHtml(hast, {allowDangerousHtml: true})
console.log(html)
// Output: Check out inline HTML.
```
```
--------------------------------
### Import toHast from mdast-util-to-hast in Deno
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Import the `toHast` function from `mdast-util-to-hast` using esm.sh for use in Deno.
```js
import {toHast} from 'https://esm.sh/mdast-util-to-hast@13'
```
--------------------------------
### Import toHast from mdast-util-to-hast in the browser
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Import the `toHast` function from `mdast-util-to-hast` using esm.sh for use in web browsers. The `?bundle` query parameter is used for bundling.
```html
```
--------------------------------
### mdast-util-to-hast Options
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Configuration options for mdast-util-to-hast.
```APIDOC
## Options
Configuration (TypeScript type).
### Fields
* **allowDangerousHtml** (`boolean`, default: `false`) - whether to persist raw HTML in markdown in the hast tree
* **clobberPrefix** (`string`, default: `'user-content-'`) - prefix to use before the `id` property on footnotes to prevent them from *clobbering*
* **file** ([`VFile`](vfile), optional) - corresponding virtual file representing the input document
* **footnoteBackContent** ([`FootnoteBackContentTemplate`](api-footnote-back-content-template) or `string`, default: [`defaultFootnoteBackContent`](api-default-footnote-back-content]) - content of the backreference back to references
* **footnoteBackLabel** ([`FootnoteBackLabelTemplate`](api-footnote-back-label-template) or `string`, default: [`defaultFootnoteBackLabel`](api-default-footnote-back-label]) - label to describe the backreference back to references
* **footnoteLabel** (`string`, default: `'Footnotes'`) - label to use for the footnotes section (affects screen readers)
* **footnoteLabelProperties** ([`Properties`](properties), default: `{className: ['sr-only']}`) - properties to use on the footnote label (note that `id: 'footnote-label'` is always added as footnote calls use it with `aria-describedby` to provide an accessible label)
* **footnoteLabelTagName** (`string`, default: `h2`) - tag name to use for the footnote label
* **handlers** ([`Handlers`](api-handlers), optional) - extra handlers for nodes
* **passThrough** (`Array`, optional) - list of custom mdast node types to pass through (keep) in hast (note that the node itself is passed, but eventual children are transformed)
* **unknownHandler** ([`Handler`](api-handler), optional) - handle all unknown nodes
```
--------------------------------
### Configure HTML Passthrough and Security Options
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Enable dangerous HTML passthrough and configure security options like `clobberPrefix` for the transformation. Also shows footnote configuration.
```javascript
import {toHast} from 'mdast-util-to-hast'
import {toHtml} from 'hast-util-to-html'
const mdast = {
type: 'root',
children: [
{
type: 'paragraph',
children: [
{type: 'text', value: 'Check out '},
{type: 'html', value: 'inline'},
{type: 'text', value: ' HTML.'}
]
}
]
}
// Enable dangerous HTML passthrough
const hast = toHast(mdast, {
allowDangerousHtml: true,
clobberPrefix: 'user-content-', // Prevent DOM clobbering
footnoteLabel: 'Footnotes',
footnoteLabelTagName: 'h2',
footnoteLabelProperties: {className: ['sr-only']}
})
const html = toHtml(hast, {allowDangerousHtml: true})
console.log(html)
// Output: Check out inline HTML.
```
--------------------------------
### HTML Handling
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Explains how raw HTML in mdast is handled as 'raw' nodes in hast and how utilities like hast-util-to-html and hast-util-raw interact with them.
```APIDOC
## HTML Handling
Raw HTML is available in mdast as [`html`][mdast-html] nodes and can be embedded in hast as semistandard `raw` nodes.
### Utilities
* **`hast-util-to-html`**: Has an `allowDangerousHtml` option to output raw HTML. This is generally discouraged but useful if authors are fully trusted.
* **`hast-util-raw`**: Parses raw embedded HTML strings into standard hast nodes (`element`, `text`, etc.). This requires a full HTML parser and is the only way to support untrusted content.
```
--------------------------------
### Frontmatter mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
TOML and YAML frontmatter are typically ignored.
```markdown
+++
fenced = true
+++
```
```markdown
---
fenced: yes
---
```
--------------------------------
### Execute a full markdown to HTML pipeline
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Combine mdast-util-from-markdown, mdast-util-to-hast, and hast-util-to-html to process markdown strings with GFM support.
```javascript
import {toHast} from 'mdast-util-to-hast'
import {toHtml} from 'hast-util-to-html'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {gfm} from 'micromark-extension-gfm'
import {gfmFromMarkdown} from 'mdast-util-gfm'
const markdown = `
# Hello World
This is a **bold** statement with a [link](https://example.com).
| Name | Age |
| ----- | --- |
| Alice | 30 |
| Bob | 25 |
Here's a footnote[^1].
[^1]: This is the footnote content.
`
// Parse markdown to mdast with GFM extensions
const mdast = fromMarkdown(markdown, {
extensions: [gfm()],
mdastExtensions: [gfmFromMarkdown()]
})
// Transform to hast
const hast = toHast(mdast, {
allowDangerousHtml: false,
clobberPrefix: 'user-content-'
})
// Convert to HTML
const html = toHtml(hast)
console.log(html)
// Hello World
// This is a bold statement with a link.
//
// Name Age
// Alice 30 Bob 25
//
// Here's a footnote1.
// ...
```
--------------------------------
### Transform Markdown to HTML AST
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Parse markdown to mdast, transform mdast to hast, and then convert hast to an HTML string. Requires `mdast-util-from-markdown` and `hast-util-to-html`.
```javascript
import {toHast} from 'mdast-util-to-hast'
import {toHtml} from 'hast-util-to-html'
import {fromMarkdown} from 'mdast-util-from-markdown'
// Parse markdown to mdast
const markdown = '## Hello **World**!'
const mdast = fromMarkdown(markdown)
// Transform mdast to hast
const hast = toHast(mdast)
// Convert hast to HTML string
const html = toHtml(hast)
console.log(html)
// Output: Hello World!
```
--------------------------------
### DOM Clobbering
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Explains the DOM clobbering problem introduced by footnotes, where generated `id` attributes from user content can lead to security risks by making elements available on the `window` object. It suggests using a prefix to solve this.
```APIDOC
## DOM Clobbering
Footnotes can cause DOM clobbering because `id` attributes generated from user content link footnote calls to definitions. This makes elements available on the `window` object, posing a security risk.
### Solution
Using a prefix for generated `id` attributes solves the DOM clobbering problem. More information can be found in [Example: headings (DOM clobbering) in `rehype-sanitize`][clobber-example].
```
--------------------------------
### toHast(tree, options)
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
The main function to transform an mdast tree to a hast tree. It accepts an mdast node and optional configuration, returning the corresponding hast node structure.
```APIDOC
## toHast(tree, options)
### Description
The main function that transforms an mdast tree to a hast tree. It accepts a mdast node as input and optional configuration, returning the corresponding hast node structure.
### Method
Function call
### Endpoint
N/A (JavaScript function)
### Request Example
```javascript
import {toHast} from 'mdast-util-to-hast'
import {toHtml} from 'hast-util-to-html'
import {fromMarkdown} from 'mdast-util-from-markdown'
// Parse markdown to mdast
const markdown = '## Hello **World**!'
const mdast = fromMarkdown(markdown)
// Transform mdast to hast
const hast = toHast(mdast)
// Convert hast to HTML string
const html = toHtml(hast)
console.log(html)
// Output: Hello World!
```
```
--------------------------------
### Unknown Nodes
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Describes the default behavior for handling unknown nodes (those not in `handlers` or `passThrough`) and how this behavior can be customized using an `unknownHandler`.
```APIDOC
## Unknown Nodes
Unknown nodes are nodes with a type not present in `handlers` or `passThrough`.
### Default Behavior
* If the node has a `value` (and no `data.hName`, `data.hProperties`, or `data.hChildren`), a hast `text` node is created.
* Otherwise, a `` element is created (this can be changed with `data.hName`), with its children mapped from mdast to hast.
### Customization
This behavior can be changed by passing an `unknownHandler`.
```
--------------------------------
### Executing Unsafe Code with allowDangerousHtml: true
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Demonstrates how unsafe embedded HTML can be executed if 'allowDangerousHtml: true' is also passed to 'hast-util-to-html' (or 'rehype-stringify').
```html
Hello
```
--------------------------------
### Image node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Standard images and image references are converted to img elements.
```markdown

```
```markdown
![Alt text][logo]
[logo]: /logo.png "title"
```
```html

```
--------------------------------
### Import and Visit Raw Node Type in TypeScript
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Import necessary types and utilities to work with the 'raw' node type. Ensure 'mdast-util-to-hast' is imported to register the node type.
```js
/**
* @import {Root} from 'hast'
* @import {} from 'mdast-util-to-hast'
*/
import {visit} from 'unist-util-visit'
/** @type {Root} */
const tree = { /* … */ }
visit(tree, function (node) {
// `node` can now be `raw`.
})
```
--------------------------------
### Link node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Links and link references are converted to anchor elements.
```markdown
[Example](https://example.com "title")
```
```markdown
[Example][]
[example]: https://example.com "title"
```
```html
```
--------------------------------
### Use default handlers
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Access the default handlers provided by the utility for converting mdast nodes to hast nodes. These handlers cover standard markdown elements.
```js
defaultHandlers
```
--------------------------------
### Default Handling of Embedded HTML
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Illustrates the default behavior of mdast-util-to-hast when encountering embedded HTML. By default, unsafe scripts are escaped and not rendered as executable code.
```html
# Hello
```
--------------------------------
### API Functions
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
This section details the functions exported by the mdast-util-to-hast package.
```APIDOC
## `defaultFootnoteBackContent(referenceIndex, rereferenceIndex)`
### Description
Generate the default content that GitHub uses on backreferences.
### Parameters
#### Path Parameters
- `referenceIndex` (number) - Required - index of the definition in the order that they are first referenced, 0-indexed
- `rereferenceIndex` (number) - Required - index of calls to the same definition, 0-indexed
### Returns
Content (`Array`)
## `defaultFootnoteBackLabel(referenceIndex, rereferenceIndex)`
### Description
Generate the default label that GitHub uses on backreferences.
### Parameters
#### Path Parameters
- `referenceIndex` (number) - Required - index of the definition in the order that they are first referenced, 0-indexed
- `rereferenceIndex` (number) - Required - index of calls to the same definition, 0-indexed
### Returns
Label (`string`)
## `defaultHandlers`
### Description
Default handlers for nodes ([`Handlers`][api-handlers]).
### Returns
[`Handlers`][api-handlers]
## `toHast(tree[, options])`
### Description
Transform mdast to hast.
### Parameters
#### Path Parameters
- `tree` ([`MdastNode`][mdast-node]) - Required - mdast tree
- `options` ([`Options`][api-options]) - Optional - configuration
### Returns
hast tree ([`HastNode`][hast-node])
```
--------------------------------
### Add Custom Node Handler for 'mark'
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Use a handler to convert a custom 'mark' mdast node to a 'mark' hast element. This requires importing `toHtml` and `toHast`.
```js
import {toHtml} from 'hast-util-to-html'
import {toHast} from 'mdast-util-to-hast'
const mdast = {
type: 'paragraph',
children: [{type: 'mark', children: [{type: 'text', value: 'x'}]}]
}
const hast = toHast(mdast, {
handlers: {
mark(state, node) {
return {
type: 'element',
tagName: 'mark',
properties: {},
children: state.all(node)
}
}
}
})
console.log(toHtml(hast))
```
--------------------------------
### Generate default footnote back content
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Generates the default content for footnote backreferences, mimicking GitHub's behavior. It takes the index of the definition and the index of the call to that definition as parameters.
```js
defaultFootnoteBackContent(referenceIndex, rereferenceIndex)
```
--------------------------------
### Strong emphasis mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Strong emphasis is converted to strong elements.
```markdown
Two **asterisks** for strong.
```
```html
Two asterisks for strong.
```
--------------------------------
### Injecting Script Tag via hName
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Demonstrates how a script tag can be injected by setting the 'hName' property on a 'code' node's data. This can lead to XSS attacks if not sanitized.
```js
const code = {type: 'code', value: 'alert(1)'}
code.data = {hName: 'script'}
```
--------------------------------
### Customize footnote back-references
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Use the footnoteBackContent option to override the default generation of footnote return links.
```javascript
import {toHast, defaultFootnoteBackContent} from 'mdast-util-to-hast'
// Default behavior: returns ↩ with optional superscript for multiple references
console.log(defaultFootnoteBackContent(0, 1))
// [{ type: 'text', value: '↩' }]
console.log(defaultFootnoteBackContent(0, 2))
// [
// { type: 'text', value: '↩' },
// { type: 'element', tagName: 'sup', properties: {}, children: [{ type: 'text', value: '2' }] }
// ]
// Custom footnote back content
const mdast = {
type: 'root',
children: [
{type: 'paragraph', children: [
{type: 'text', value: 'Text'},
{type: 'footnoteReference', identifier: '1'}
]},
{type: 'footnoteDefinition', identifier: '1', children: [
{type: 'paragraph', children: [{type: 'text', value: 'Footnote content'}]}
]}
]
}
const hast = toHast(mdast, {
footnoteBackContent(referenceIndex, rereferenceIndex) {
return `[${referenceIndex + 1}${rereferenceIndex > 1 ? '.' + rereferenceIndex : ''}]`
}
})
```
--------------------------------
### Transform nodes using the state object
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
The state object provides helper methods like one(), all(), patch(), and applyData() to facilitate custom node transformations within handlers.
```javascript
import {toHast} from 'mdast-util-to-hast'
const mdast = {
type: 'paragraph',
children: [{type: 'text', value: 'Example'}],
position: {start: {line: 1, column: 1}, end: {line: 1, column: 8}}
}
const hast = toHast(mdast, {
handlers: {
paragraph(state, node) {
// state.all(node) - transform all children
const children = state.all(node)
// Create result element
const result = {
type: 'element',
tagName: 'p',
properties: {className: ['prose']},
children
}
// state.patch(from, to) - copy position info
state.patch(node, result)
// state.applyData(from, to) - apply data.hName, data.hProperties, data.hChildren
return state.applyData(node, result)
}
}
})
console.log(hast)
// {
// type: 'element',
// tagName: 'p',
// properties: { className: ['prose'] },
// children: [{ type: 'text', value: 'Example' }],
// position: { start: { line: 1, column: 1 }, end: { line: 1, column: 8 } }
// }
```
--------------------------------
### HTML node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Raw HTML nodes are typically ignored unless allowDangerousHtml is enabled.
```html
CMD+S
```
--------------------------------
### Transform mdast tree to hast tree
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
The core function `toHast` transforms an mdast (markdown) syntax tree into a hast (HTML) syntax tree. It accepts the mdast tree and optional configuration options.
```js
toHast(tree[, options])
```
--------------------------------
### Paragraph node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Paragraphs are converted to p elements.
```markdown
Just some text…
```
```html
Just some text…
```
--------------------------------
### Root and Text node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Root and text nodes are mapped to their respective hast types.
```markdown
Anything!
```
```html
Anything!
```
--------------------------------
### Footnotes
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Details the support for footnotes, which are not part of CommonMark but are enabled by mdast-util-gfm. It covers options for natural language explanations and ARIA attributes.
```APIDOC
## Footnotes
Footnotes are supported when enabled with [`mdast-util-gfm`][mdast-util-gfm].
### Options
* **`footnoteBackLabel`** (`string`): Natural language for footnote backreferences, hidden for sighted users but shown to assistive technology. Must be translated if the page is not in English.
* **`footnoteLabel`** (`string`): Natural language for the footnote section label, hidden with an `sr-only` class. Can be customized with `footnoteLabelProperties` to be shown to sighted users.
### ARIA Attributes
Back references use ARIA attributes. The section label uses a heading hidden with an `sr-only` class.
```
--------------------------------
### Customize element children with hChildren
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Use hChildren to manually define the child nodes of an element.
```js
{
type: 'code',
lang: 'js',
data: {
hChildren: [
{
type: 'element',
tagName: 'span',
properties: {className: ['hljs-meta']},
children: [{type: 'text', value: '"use strict"'}]
},
{type: 'text', value: ';'}
]
},
value: '"use strict";'
}
```
```js
{
type: 'element',
tagName: 'pre',
properties: {},
children: [{
type: 'element',
tagName: 'code',
properties: {className: ['language-js']},
children: [
{
type: 'element',
tagName: 'span',
properties: {className: ['hljs-meta']},
children: [{type: 'text', value: '"use strict"'}]
},
{type: 'text', value: ';'}
]
}]
}
```
--------------------------------
### Custom Node Handlers
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Define handlers for custom mdast node types to extend transformation capabilities.
```APIDOC
## Custom Node Handlers
### Description
Define handlers for custom mdast node types to extend the transformation with your own node implementations.
### Method
Using the `handlers` option in `toHast`
### Endpoint
N/A (JavaScript function)
### Parameters
#### Request Body (Options Object)
- **handlers** (object) - Optional - An object where keys are node types and values are handler functions.
- **handlerFunction(state, node)** - Function - Transforms a specific node type.
### Request Example
```javascript
import {toHast} from 'mdast-util-to-hast'
// Custom mdast tree with a 'mark' node type
const mdast = {
type: 'paragraph',
children: [
{type: 'text', value: 'This is '},
{type: 'mark', children: [{type: 'text', value: 'highlighted'}]},
{type: 'text', value: ' text.'}
]
}
const hast = toHast(mdast, {
handlers: {
mark(state, node) {
return {
type: 'element',
tagName: 'mark',
properties: {},
children: state.all(node)
}
}
}
})
console.log(hast)
// {
// type: 'element',
// tagName: 'p',
// properties: {},
// children: [
// { type: 'text', value: 'This is ' },
// { type: 'element', tagName: 'mark', properties: {}, children: [{ type: 'text', value: 'highlighted' }] },
// { type: 'text', value: ' text.' }
// ]
// }
```
```
--------------------------------
### Customize element properties with hProperties
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Use hProperties to define extra attributes or classes on the resulting hast node.
```js
{
type: 'image',
src: 'circle.svg',
alt: 'Big red circle on a black background',
data: {hProperties: {className: ['responsive']}}
}
```
```js
{
type: 'element',
tagName: 'img',
properties: {
src: 'circle.svg',
alt: 'Big red circle on a black background',
className: ['responsive']
},
children: []
}
```
--------------------------------
### FootnoteBackContentTemplate Function
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Details the `FootnoteBackContentTemplate` function, which generates content for footnote backreferences dynamically. It explains the parameters and return type.
```APIDOC
## `FootnoteBackContentTemplate`
Generates content for the backreference dynamically.
### Parameters
* **`referenceIndex`** (`number`) - Index of the definition in the order they are first referenced (0-indexed).
* **`rereferenceIndex`** (`number`) - Index of calls to the same definition (0-indexed).
### Returns
Content for the backreference when linking back from definitions to their reference (`Array`, `ElementContent`, or `string`).
```
--------------------------------
### Table node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Tables are converted to table, thead, tbody, tr, th, and td elements.
```markdown
| Pipes |
| ----- |
```
```html
Pipes
```
--------------------------------
### Define Raw node interface
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Interface definition for the Raw node type in hast.
```idl
interface Raw <: Literal {
type: 'raw'
}
```
--------------------------------
### Define Custom Node Handler for 'mark' Type
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Create a custom handler for a 'mark' node type to transform it into a `` HTML element. This allows for custom markdown syntax extensions.
```javascript
import {toHast} from 'mdast-util-to-hast'
// Custom mdast tree with a 'mark' node type
const mdast = {
type: 'paragraph',
children: [
{type: 'text', value: 'This is '},
{type: 'mark', children: [{type: 'text', value: 'highlighted'}]},
{type: 'text', value: ' text.'}
]
}
const hast = toHast(mdast, {
handlers: {
mark(state, node) {
return {
type: 'element',
tagName: 'mark',
properties: {},
children: state.all(node)
}
}
}
})
console.log(hast)
// {
// type: 'element',
// tagName: 'p',
// properties: {},
// children: [
// { type: 'text', value: 'This is ' },
// { type: 'element', tagName: 'mark', properties: {}, children: [{ type: 'text', value: 'highlighted' }] },
// { type: 'text', value: ' text.' }
// ]
// }
```
--------------------------------
### List node mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Lists are converted to ul or ol elements with li children.
```markdown
* asterisks for unordered items
1. decimals and a dot for ordered items
```
```html
- asterisks for unordered items
- decimals and a dot for ordered items
```
--------------------------------
### Handle unknown node types
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Define a custom unknownHandler function to process node types that are not natively supported by the converter.
```javascript
import {toHast} from 'mdast-util-to-hast'
const mdast = {
type: 'paragraph',
children: [
{type: 'customNode', value: 'custom content'},
{type: 'text', value: ' and normal text'}
]
}
const hast = toHast(mdast, {
unknownHandler(state, node) {
// Wrap unknown nodes in a span with a data attribute
return {
type: 'element',
tagName: 'span',
properties: {dataNodeType: node.type},
children: node.value ? [{type: 'text', value: node.value}] : state.all(node)
}
}
})
console.log(hast)
// {
// type: 'element',
// tagName: 'p',
// properties: {},
// children: [
// { type: 'element', tagName: 'span', properties: { dataNodeType: 'customNode' }, children: [{ type: 'text', value: 'custom content' }] },
// { type: 'text', value: ' and normal text' }
// ]
// }
```
--------------------------------
### Internationalize footnote labels in markdown to HTML conversion
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Customize footnote labels for non-English markdown by passing `footnoteLabel` and `footnoteBackLabel` options to `mdast-util-to-hast`. This ensures better accessibility for screen readers in different languages.
```js
import {toHtml} from 'hast-util-to-html'
import {gfm} from 'micromark-extension-gfm'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {gfmFromMarkdown} from 'mdast-util-gfm'
import {toHast} from 'mdast-util-to-hast'
const markdown = 'Bonjour[^1]\n\n[^1]: Monde!'
const mdast = fromMarkdown(markdown, {
extensions: [gfm()],
mdastExtensions: [gfmFromMarkdown()]
})
const hast = toHast(mdast, {
footnoteLabel: 'Notes de bas de page',
footnoteBackLabel(referenceIndex, rereferenceIndex) {
return (
'Retour à la référence ' +
(referenceIndex + 1) +
(rereferenceIndex > 1 ? '-' + rereferenceIndex : '')
)
}
})
const html = toHtml(hast)
console.log(html)
```
--------------------------------
### Injecting Script Tag via onError Property
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Shows how an image's 'onError' property can be manipulated to execute JavaScript, exploiting potential XSS vulnerabilities. This occurs when an image fails to load.
```js
const image = {type: 'image', url: 'existing.png'}
image.data = {hProperties: {src: 'missing', onError: 'alert(2)'}}
```
--------------------------------
### Heading elements mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Markdown headings are converted to h1 through h6 elements.
```html
One number sign…
Six number signs…
```
--------------------------------
### Inline code mapping
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Inline code blocks are converted to code elements.
```markdown
Some `backticks` for inline code.
```
```html
Some backticks for inline code.
```
--------------------------------
### FootnoteBackLabelTemplate Function
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Details the `FootnoteBackLabelTemplate` function, which generates a back label dynamically for footnote references. It explains the parameters and return type.
```APIDOC
## `FootnoteBackLabelTemplate`
Generates a back label dynamically.
### Parameters
* **`referenceIndex`** (`number`) - Index of the definition in the order they are first referenced (0-indexed).
* **`rereferenceIndex`** (`number`) - Index of calls to the same definition (0-indexed).
### Returns
Back label to use when linking back from definitions to their reference (`string`).
```
--------------------------------
### Generate default footnote back label
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Generates the default label for footnote backreferences, similar to GitHub's implementation. It requires the index of the definition and the index of the call to that definition.
```js
defaultFootnoteBackLabel(referenceIndex, rereferenceIndex)
```
--------------------------------
### Add custom HTML attributes with data.hProperties
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Use the hProperties object within a node's data property to define custom HTML attributes for the resulting hast element.
```javascript
import {toHast} from 'mdast-util-to-hast'
const mdast = {
type: 'image',
url: 'photo.jpg',
alt: 'A photo',
data: {
hProperties: {
className: ['responsive-image', 'lazy-load'],
loading: 'lazy',
width: 800,
height: 600
}
}
}
const hast = toHast(mdast)
console.log(hast)
// {
// type: 'element',
// tagName: 'img',
// properties: {
// src: 'photo.jpg',
// alt: 'A photo',
// className: ['responsive-image', 'lazy-load'],
// loading: 'lazy',
// width: 800,
// height: 600
// },
// children: []
// }
```
--------------------------------
### Markdown Break to HTML
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Converts a Markdown line break (backslash followed by newline) to an HTML `
` element within a paragraph. This is a default handling.
```markdown
A backslash\
before a line break…
```
--------------------------------
### Support Custom Node via Data Field
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Configure a custom 'mark' mdast node to be converted to a 'mark' hast element by setting the `hName` property within the node's `data` field. This method avoids the need for explicit handlers.
```js
import {toHtml} from 'hast-util-to-html'
import {toHast} from 'mdast-util-to-hast'
const mdast = {
type: 'paragraph',
children: [
{
type: 'mark',
children: [{type: 'text', value: 'x'}],
data: {hName: 'mark'}
}
]
}
console.log(toHtml(toHast(mdast)))
```
--------------------------------
### Handling Embedded HTML with allowDangerousHtml: true
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Shows the output when 'allowDangerousHtml: true' is passed to mdast-util-to-hast. Unsafe HTML is still escaped by default by hast-util-to-html.
```html
Hello
<script>alert(3)</script>
```
--------------------------------
### Pass through custom node types
Source: https://context7.com/syntax-tree/mdast-util-to-hast/llms.txt
Use the passThrough option to keep specific mdast node types in the output tree without transformation.
```javascript
import {toHast} from 'mdast-util-to-hast'
const mdast = {
type: 'paragraph',
children: [
{type: 'customEmbed', url: 'https://example.com/video', children: []},
{type: 'text', value: ' with text'}
]
}
const hast = toHast(mdast, {
passThrough: ['customEmbed']
})
console.log(hast)
// {
// type: 'element',
// tagName: 'p',
// properties: {},
// children: [
// { type: 'customEmbed', url: 'https://example.com/video', children: [] },
// { type: 'text', value: ' with text' }
// ]
// }
```
--------------------------------
### mdast-util-to-hast Internal Types
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Internal TypeScript types used by mdast-util-to-hast.
```APIDOC
## Types
### `Handlers`
```ts
type Handlers = Partial>
```
### `Raw`
Raw string of HTML embedded into HTML AST (TypeScript type).
```ts
import type {Data, Literal} from 'hast'
interface Raw extends Literal {
type: 'raw'
data?: RawData | undefined
}
interface RawData extends Data {}
```
### `State`
Info passed around about the current state (TypeScript type).
#### Fields
* **all** (`(node: MdastNode) => Array`) - transform the children of an mdast parent to hast
* **applyData** (`(from: MdastNode, to: Type) => Type | HastElement`) - honor the `data` of `from` and maybe generate an element instead of `to`
* **definitionById** (`Map`) - definitions by their uppercased identifier
* **footnoteById** (`Map`) - footnote definitions by their uppercased identifier
* **footnoteCounts** (`Map`) - counts for how often the same footnote was called
* **footnoteOrder** (`Array`) - identifiers of order when footnote calls first appear in tree order
* **handlers** ([`Handlers`](api-handlers)) - applied node handlers
* **one** (`(node: MdastNode, parent: MdastNode | undefined) => HastNode | Array | undefined`) - transform an mdast node to hast
* **options** ([`Options`](api-options)) - configuration
* **patch** (`(from: MdastNode, to: HastNode) => undefined`)
* **wrap** (`(nodes: Array, loose?: boolean) => Array`) - wrap `nodes` with line endings between each node, adds initial/final line endings when `loose`
```
--------------------------------
### Markdown Delete to HTML
Source: https://github.com/syntax-tree/mdast-util-to-hast/blob/main/readme.md
Converts a Markdown strikethrough (using double tildes) to an HTML `` element. This is a GFM extension.
```markdown
Two ~~tildes~~ for delete.
```