the editable site (validation-lab)

This commit is contained in:
kpgarrod committed 2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 files changed
+2227005

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
export type {Options} from './lib/index.js'
export {gfmTableFromMarkdown, gfmTableToMarkdown} from './lib/index.js'
// Add custom data tracked to turn markdown into a tree.
declare module 'mdast-util-from-markdown' {
interface CompileData {
/**
* Whether we’re currently in a table.
*/
inTable?: boolean | undefined
}
}
// Add custom data tracked to turn a syntax tree into markdown.
declare module 'mdast-util-to-markdown' {
interface ConstructNameMap {
/**
* Whole table.
*
* ```markdown
* > | | a |
* ^^^^^
* > | | - |
* ^^^^^
* ```
*/
table: 'table'
/**
* Table cell.
*
* ```markdown
* > | | a |
* ^^^^^
* | | - |
* ```
*/
tableCell: 'tableCell'
/**
* Table row.
*
* ```markdown
* > | | a |
* ^^^^^
* | | - |
* ```
*/
tableRow: 'tableRow'
}
}
// Note: `Table` is exposed from `@types/mdast`.
+2
View File
@@ -0,0 +1,2 @@
// Note: types exposed from `index.d.ts`.
export {gfmTableFromMarkdown, gfmTableToMarkdown} from './lib/index.js'
+41
View File
@@ -0,0 +1,41 @@
/**
* Create an extension for `mdast-util-from-markdown` to enable GFM tables in
* markdown.
*
* @returns {FromMarkdownExtension}
* Extension for `mdast-util-from-markdown` to enable GFM tables.
*/
export function gfmTableFromMarkdown(): FromMarkdownExtension;
/**
* Create an extension for `mdast-util-to-markdown` to enable GFM tables in
* markdown.
*
* @param {Options | null | undefined} [options]
* Configuration.
* @returns {ToMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable GFM tables.
*/
export function gfmTableToMarkdown(options?: Options | null | undefined): ToMarkdownExtension;
/**
* Configuration.
*/
export type Options = {
/**
* Whether to add a space of padding between delimiters and cells (default:
* `true`).
*/
tableCellPadding?: boolean | null | undefined;
/**
* Whether to align the delimiters (default: `true`).
*/
tablePipeAlign?: boolean | null | undefined;
/**
* Function to detect the length of table cell content, used when aligning
* the delimiters between cells (optional).
*/
stringLength?: MarkdownTableOptions["stringLength"] | null | undefined;
};
import type { Extension as FromMarkdownExtension } from 'mdast-util-from-markdown';
import type { Options as ToMarkdownExtension } from 'mdast-util-to-markdown';
import type { Options as MarkdownTableOptions } from 'markdown-table';
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAoCA;;;;;;GAMG;AACH,wCAHa,qBAAqB,CAmBjC;AA4GD;;;;;;;;GAQG;AACH,6CALW,OAAO,GAAG,IAAI,GAAG,SAAS,GAExB,mBAAmB,CA6N/B;;;;;;;;;uBAtXa,OAAO,GAAG,IAAI,GAAG,SAAS;;;;qBAG1B,OAAO,GAAG,IAAI,GAAG,SAAS;;;;;mBAE1B,oBAAoB,CAAC,cAAc,CAAC,GAAG,IAAI,GAAG,SAAS;;wDAlB3D,0BAA0B;oDAO1B,wBAAwB;qDAZgB,gBAAgB"}
+448
View File
@@ -0,0 +1,448 @@
/**
* @import {Heading, InlineCode, Table, TableCell, TableRow} from 'mdast'
* @import {Options as MarkdownTableOptions} from 'markdown-table'
* @import {
* CompileContext,
* Extension as FromMarkdownExtension,
* Handle as FromMarkdownHandle,
* } from 'mdast-util-from-markdown'
* @import {
* Options as ToMarkdownExtension,
* Handle as ToMarkdownHandle,
* Info,
* Join,
* State
* } from 'mdast-util-to-markdown'
*/
/**
* @typedef Options
* Configuration.
* @property {boolean | null | undefined} [tableCellPadding=true]
* Whether to add a space of padding between delimiters and cells (default:
* `true`).
* @property {boolean | null | undefined} [tablePipeAlign=true]
* Whether to align the delimiters (default: `true`).
* @property {MarkdownTableOptions['stringLength'] | null | undefined} [stringLength]
* Function to detect the length of table cell content, used when aligning
* the delimiters between cells (optional).
*/
import {ok as assert} from 'devlop'
import {markdownTable} from 'markdown-table'
import {defaultHandlers} from 'mdast-util-to-markdown'
import {toString} from 'mdast-util-to-string'
import {EXIT, visit} from 'unist-util-visit'
/**
* Create an extension for `mdast-util-from-markdown` to enable GFM tables in
* markdown.
*
* @returns {FromMarkdownExtension}
* Extension for `mdast-util-from-markdown` to enable GFM tables.
*/
export function gfmTableFromMarkdown() {
return {
enter: {
table: enterTable,
tableData: enterCell,
tableHeader: enterCell,
tableRow: enterRow
},
exit: {
codeText: exitCodeText,
table: exitTable,
tableData: exit,
tableHeader: exit,
tableRow: exit
}
}
}
/**
* Enter a table.
*
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterTable(token) {
const align = token._align
assert(align, 'expected `_align` on table')
// Trailing `position: undefined` keeps the table hidden class stable;
// mdast-util-from-markdown's enter() patches the field to a real value
// but the property already exists, so no shape transition fires.
this.enter(
{
type: 'table',
align: align.map(function (d) {
return d === 'none' ? null : d
}),
children: [],
position: undefined
},
token
)
this.data.inTable = true
}
/**
* Exit a table.
*
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitTable(token) {
this.exit(token)
this.data.inTable = undefined
}
/**
* Enter a row.
*
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterRow(token) {
// See enterTable above for the rationale on the trailing position field.
this.enter({type: 'tableRow', children: [], position: undefined}, token)
}
/**
* Exit a row or cell.
*
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exit(token) {
this.exit(token)
}
/**
* Enter a cell.
*
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterCell(token) {
// See enterTable above for the rationale on the trailing position field.
this.enter({type: 'tableCell', children: [], position: undefined}, token)
}
/**
* Exit code (text).
*
* Overwrites the default code text data handler to unescape escaped pipes
* when they are in tables.
*
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitCodeText(token) {
let value = this.resume()
if (this.data.inTable) {
value = value.replace(/\\([\\|])/g, replace)
}
const node = this.stack[this.stack.length - 1]
assert(node.type === 'inlineCode')
node.value = value
this.exit(token)
}
/**
* Unescape an escaped pipe.
*
* @param {string} $0
* Whole match.
* @param {string} $1
* Escaped character.
* @returns {string}
* Replacement.
*/
function replace($0, $1) {
// Pipes work, backslashes don’t (but can’t escape pipes).
return $1 === '|' ? $1 : $0
}
/**
* Create an extension for `mdast-util-to-markdown` to enable GFM tables in
* markdown.
*
* @param {Options | null | undefined} [options]
* Configuration.
* @returns {ToMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable GFM tables.
*/
export function gfmTableToMarkdown(options) {
const settings = options || {}
const {
tableCellPadding: padding,
tablePipeAlign: alignDelimiters,
stringLength
} = settings
const around = padding ? ' ' : '|'
return {
handlers: {
inlineCode: inlineCodeWithTable,
table: handleTable,
tableCell: handleTableCell,
tableRow: handleTableRow
},
join: [joinTable],
unsafe: [
{character: '\r', inConstruct: 'tableCell'},
{character: '\n', inConstruct: 'tableCell'},
// A pipe, when followed by a tab or space (padding), or a dash or colon
// (unpadded delimiter row), could result in a table.
{atBreak: true, character: '|', after: '[\t :-]'},
// A pipe in a cell must be encoded.
{character: '|', inConstruct: 'tableCell'},
// A colon must be followed by a dash, in which case it could start a
// delimiter row.
{atBreak: true, character: ':', after: '-'},
// A delimiter row can also start with a dash, when followed by more
// dashes, a colon, or a pipe.
// This is a stricter version than the built in check for lists, thematic
// breaks, and setex heading underlines though:
// <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>
{atBreak: true, character: '-', after: '[:|-]'}
]
}
/**
* Serialize a table.
*
* @type {ToMarkdownHandle}
* @param {Table} node
* Table.
*/
function handleTable(node, _, state, info) {
const matrix = handleTableAsData(node, state, info)
const head = matrix[0]
if (head) {
let columns = node.align ? node.align.length : 0
let index = -1
if (!columns) {
while (++index < matrix.length) {
if (matrix[index].length > columns) columns = matrix[index].length
}
}
while (head.length < columns) head.push('')
}
return serializeData(matrix, node.align)
}
/**
* This function isn’t really used normally, because we handle rows at the
* table level.
* But, if someone passes in a table row, this ensures we make somewhat sense.
*
* @type {ToMarkdownHandle}
* @param {TableRow} node
* Row.
*/
function handleTableRow(node, _, state, info) {
const row = handleTableRowAsData(node, state, info)
const value = serializeData([row])
// `markdown-table` will always add an align row
return value.slice(0, value.indexOf('\n'))
}
/**
* Serialize a cell.
*
* @type {ToMarkdownHandle}
* @param {TableCell} node
* Cell.
*/
function handleTableCell(node, _, state, info) {
const exit = state.enter('tableCell')
const subexit = state.enter('phrasing')
const value = state.containerPhrasing(node, {
...info,
before: around,
after: around
})
subexit()
exit()
return value
}
/**
* Serialize serialized cells as a table.
*
* @param {Array<Array<string>>} matrix
* Serialized cells.
* @param {Array<string | null | undefined> | null | undefined} [align]
* Alignment.
* @returns {string}
* Result.
*/
function serializeData(matrix, align) {
return markdownTable(matrix, {
align,
alignDelimiters,
fillRows: false,
padding,
stringLength
})
}
/**
* Serialize the cells of a table.
*
* @param {Table} node
* Table.
* @param {State} state
* State.
* @param {Info} info
* Info.
* @returns {Array<Array<string>>}
* Serialized cells.
*/
function handleTableAsData(node, state, info) {
const {children} = node
let index = -1
/** @type {Array<Array<string>>} */
const result = []
const subexit = state.enter('table')
while (++index < children.length) {
result[index] = handleTableRowAsData(children[index], state, info)
}
subexit()
return result
}
/**
* Serialize the cells of a row.
*
* @param {TableRow} node
* Row.
* @param {State} state
* State.
* @param {Info} info
* Info.
* @returns {Array<string>}
* Serialized cells.
*/
function handleTableRowAsData(node, state, info) {
const {children} = node
let index = -1
/** @type {Array<string>} */
const result = []
const subexit = state.enter('tableRow')
while (++index < children.length) {
// Note: the positional info as used here is incorrect.
// Making it correct would be impossible due to aligning cells?
// And it would need copy/pasting `markdown-table` into this project.
result[index] = handleTableCell(children[index], node, state, info)
}
subexit()
return result
}
/**
* Serialize inline code, escaping pipes in tables.
*
* @type {ToMarkdownHandle}
* @param {InlineCode} node
* Inline code.
*/
function inlineCodeWithTable(node, parent, state) {
const value = defaultHandlers.inlineCode(node, parent, state)
if (!state.stack.includes('tableCell')) return value
// In a cell, the backslash before a pipe is dropped, also in code.
// GitHub keeps a pipe in the cell when any backslash precedes it,
// but micromark only when an odd number do,
// as it sees `\\` as an escaped backslash
// (see <https://github.com/github/cmark-gfm/issues/277>).
/** @type {Array<string>} */
const result = []
let start = 0
let index = value.indexOf('|')
while (index !== -1) {
let before = index
while (before > start && value.charCodeAt(before - 1) === 92 /* `\` */) {
before--
}
result.push(value.slice(start, index))
if ((index - before) % 2 === 0) result.push('\\')
start = index
index = value.indexOf('|', index + 1)
}
result.push(value.slice(start))
return result.join('')
}
}
/**
* Join a table and the flow after it.
*
* In a tight list item there are no blank lines between flow,
* but text right after a table would be read as rows of it.
*
* @type {Join}
*/
function joinTable(left, right, parent, state) {
if (
left.type === 'table' &&
parent.type === 'listItem' &&
parent.spread === false &&
(right.type === 'definition' ||
(right.type === 'heading' && formatHeadingAsSetext(right, state)) ||
right.type === 'paragraph' ||
right.type === 'table')
) {
return 1
}
}
/**
* Check whether a heading is serialized as a setext heading,
* like `mdast-util-to-markdown` does.
*
* @param {Heading} node
* Heading.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the heading is serialized as a setext heading.
*/
function formatHeadingAsSetext(node, state) {
let literalWithBreak = false
visit(node, function (node) {
if (
node.type === 'break' ||
('value' in node && /\r?\n|\r/.test(node.value))
) {
literalWithBreak = true
return EXIT
}
})
return Boolean(
(!node.depth || node.depth < 3) &&
toString(node) &&
(state.options.setext || literalWithBreak)
)
}
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+88
View File
@@ -0,0 +1,88 @@
{
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"bugs": "https://github.com/syntax-tree/mdast-util-gfm-table/issues",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"dependencies": {
"@types/mdast": "^4.0.0",
"devlop": "^1.0.0",
"markdown-table": "^3.0.0",
"mdast-util-from-markdown": "^2.0.0",
"mdast-util-to-markdown": "^2.0.0",
"mdast-util-to-string": "^4.0.0",
"unist-util-visit": "^5.0.0"
},
"description": "mdast extension to parse and serialize GFM tables",
"devDependencies": {
"@types/node": "^26.0.0",
"c8": "^12.0.0",
"micromark-extension-gfm-table": "^2.0.0",
"prettier": "^3.0.0",
"remark-cli": "^12.0.0",
"remark-preset-wooorm": "^11.0.0",
"string-width": "^8.0.0",
"type-coverage": "^2.0.0",
"typescript": "^6.0.0",
"unist-util-remove-position": "^5.0.0",
"xo": "^5.0.0"
},
"exports": "./index.js",
"files": [
"lib/",
"index.d.ts",
"index.js"
],
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"keywords": [
"cell",
"column",
"gfm",
"markdown",
"markup",
"mdast-util",
"mdast",
"row",
"table",
"tabular",
"unist",
"utility",
"util"
],
"license": "MIT",
"name": "mdast-util-gfm-table",
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"remark-preset-wooorm"
]
},
"repository": "syntax-tree/mdast-util-gfm-table",
"scripts": {
"build": "tsc --build --clean && tsc --build && type-coverage",
"format": "remark --frail --output --quiet -- . && prettier --log-level warn --write -- . && xo --fix",
"prepack": "npm run build && npm run format",
"test-api-dev": "node --conditions development test.js",
"test-api-prod": "node --conditions production test.js",
"test-api": "npm run test-api-dev && npm run test-api-prod",
"test-coverage": "c8 --100 --reporter lcov -- npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"sideEffects": false,
"typeCoverage": {
"atLeast": 100,
"strict": true
},
"type": "module",
"version": "2.0.1"
}
+591
View File
@@ -0,0 +1,591 @@
# mdast-util-gfm-table
[![Build][badge-build-image]][badge-build-url]
[![Coverage][badge-coverage-image]][badge-coverage-url]
[![Downloads][badge-downloads-image]][badge-downloads-url]
[![Size][badge-size-image]][badge-size-url]
[mdast][github-mdast] extensions to parse and serialize [GFM][spec-gfm] tables.
## Contents
* [What is this?](#what-is-this)
* [When to use this](#when-to-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`gfmTableFromMarkdown`](#gfmtablefrommarkdown)
* [`gfmTableToMarkdown(options?)`](#gfmtabletomarkdownoptions)
* [`Options`](#options)
* [Examples](#examples)
* [Example: `stringLength`](#example-stringlength)
* [HTML](#html)
* [Syntax](#syntax)
* [Syntax tree](#syntax-tree)
* [Nodes](#nodes)
* [Enumeration](#enumeration)
* [Content model](#content-model)
* [Types](#types)
* [Compatibility](#compatibility)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This package contains two extensions that add support for GFM table syntax in
markdown to [mdast][github-mdast].
These extensions plug into
[`mdast-util-from-markdown`][github-mdast-util-from-markdown]
(to support parsing tables in markdown into a syntax tree) and
[`mdast-util-to-markdown`][github-mdast-util-to-markdown]
(to support serializing tables in syntax trees to markdown).
## When to use this
You can use these extensions when you are working with
`mdast-util-from-markdown` and `mdast-util-to-markdown` already.
When working with `mdast-util-from-markdown`, you must combine this package
with [`micromark-extension-gfm-table`][github-micromark-extension-gfm-table].
When you don’t need a syntax tree, you can use [`micromark`][github-micromark]
directly with `micromark-extension-gfm-table`.
When you are working with syntax trees and want all of GFM, use
[`mdast-util-gfm`][github-mdast-util-gfm] instead.
All these packages are used in [`remark-gfm`][github-remark-gfm], which
focusses on making it easier to transform content by abstracting these
internals away.
This utility does not handle how markdown is turned to HTML.
That’s done by [`mdast-util-to-hast`][github-mdast-util-to-hast].
## Install
This package is [ESM only][github-gist-esm].
In Node.js (version 16+), install with [npm][npmjs-install]:
```sh
npm install mdast-util-gfm-table
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'https://esm.sh/mdast-util-gfm-table@2?bundle'
</script>
```
## Use
Say our document `example.md` contains:
```markdown
| a | b | c | d |
| - | :- | -: | :-: |
| e | f |
| g | h | i | j | k |
```
…and our module `example.js` looks as follows:
```js
import fs from 'node:fs/promises'
import {gfmTable} from 'micromark-extension-gfm-table'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'
import {toMarkdown} from 'mdast-util-to-markdown'
const doc = await fs.readFile('example.md')
const tree = fromMarkdown(doc, {
extensions: [gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()]
})
console.log(tree)
const out = toMarkdown(tree, {extensions: [gfmTableToMarkdown()]})
console.log(out)
```
…now running `node example.js` yields (positional info removed for brevity):
```js
{
type: 'root',
children: [
{
type: 'table',
align: [null, 'left', 'right', 'center'],
children: [
{
type: 'tableRow',
children: [
{type: 'tableCell', children: [{type: 'text', value: 'a'}]},
{type: 'tableCell', children: [{type: 'text', value: 'b'}]},
{type: 'tableCell', children: [{type: 'text', value: 'c'}]},
{type: 'tableCell', children: [{type: 'text', value: 'd'}]}
]
},
{
type: 'tableRow',
children: [
{type: 'tableCell', children: [{type: 'text', value: 'e'}]},
{type: 'tableCell', children: [{type: 'text', value: 'f'}]}
]
},
{
type: 'tableRow',
children: [
{type: 'tableCell', children: [{type: 'text', value: 'g'}]},
{type: 'tableCell', children: [{type: 'text', value: 'h'}]},
{type: 'tableCell', children: [{type: 'text', value: 'i'}]},
{type: 'tableCell', children: [{type: 'text', value: 'j'}]},
{type: 'tableCell', children: [{type: 'text', value: 'k'}]}
]
}
]
}
]
}
```
```markdown
| a | b | c | d |
| - | :- | -: | :-: |
| e | f |
| g | h | i | j | k |
```
## API
This package exports the identifiers
[`gfmTableFromMarkdown`][api-gfm-table-from-markdown] and
[`gfmTableToMarkdown`][api-gfm-table-to-markdown].
There is no default export.
### `gfmTableFromMarkdown`
Create an extension for
[`mdast-util-from-markdown`][github-mdast-util-from-markdown]
to enable GFM tables in markdown.
###### Returns
Extension for `mdast-util-from-markdown` to enable GFM tables
([`FromMarkdownExtension`][github-mdast-util-from-markdown-extension]).
### `gfmTableToMarkdown(options?)`
Create an extension for
[`mdast-util-to-markdown`][github-mdast-util-to-markdown]
to enable GFM tables in markdown.
###### Parameters
* `options` ([`Options`][api-options], optional)
— configuration
###### Returns
Extension for `mdast-util-to-markdown` to enable GFM tables
([`ToMarkdownExtension`][github-mdast-util-to-markdown-options]).
### `Options`
Configuration (TypeScript type).
###### Fields
* `tableCellPadding` (`boolean`, default: `true`)
— whether to add a space of padding between delimiters and cells
* `tablePipeAlign` (`boolean`, default: `true`)
— whether to align the delimiters
* `stringLength` (`((value: string) => number)`, default: `s => s.length`)
— function to detect the length of table cell content, used when aligning
the delimiters between cells
## Examples
### Example: `stringLength`
It’s possible to align tables based on the visual width of cells.
First, let’s show the problem:
```js
import {gfmTable} from 'micromark-extension-gfm-table'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'
import {toMarkdown} from 'mdast-util-to-markdown'
const doc = `| Alpha | Bravo |
| - | - |
| 中文 | Charlie |
| 👩‍❤️‍👩 | Delta |`
const tree = fromMarkdown(doc, {
extensions: [gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()]
})
console.log(toMarkdown(tree, {extensions: [gfmTableToMarkdown()]}))
```
The above code shows how these utilities can be used to format markdown.
The output is as follows:
```markdown
| Alpha | Bravo |
| -------- | ------- |
| 中文 | Charlie |
| 👩‍❤️‍👩 | Delta |
```
To improve the alignment of these full-width characters and emoji, pass a
`stringLength` function that calculates the visual width of cells.
One such algorithm is [`string-width`][github-string-width].
It can be used like so:
```diff
@@ -2,6 +2,7 @@ import {gfmTable} from 'micromark-extension-gfm-table'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'
import {toMarkdown} from 'mdast-util-to-markdown'
+import stringWidth from 'string-width'
const doc = `| Alpha | Bravo |
| - | - |
@@ -13,4 +14,8 @@ const tree = fromMarkdown(doc, {
mdastExtensions: [gfmTableFromMarkdown()]
})
-console.log(toMarkdown(tree, {extensions: [gfmTableToMarkdown()]}))
+console.log(
+ toMarkdown(tree, {
+ extensions: [gfmTableToMarkdown({stringLength: stringWidth})]
+ })
+)
```
The output of our code with these changes is as follows:
```markdown
| Alpha | Bravo |
| ----- | ------- |
| 中文 | Charlie |
| 👩‍❤️‍👩 | Delta |
```
## HTML
This utility does not handle how markdown is turned to HTML.
That’s done by [`mdast-util-to-hast`][github-mdast-util-to-hast].
## Syntax
See [Syntax in
`micromark-extension-gfm-table`][github-micromark-extension-gfm-table-syntax].
## Syntax tree
The following interfaces are added to **[mdast][github-mdast]** by this utility.
### Nodes
#### `Table`
```idl
interface Table <: Parent {
type: 'table'
align: [alignType]?
children: [TableContent]
}
```
**Table** (**[Parent][github-mdast-parent]**) represents two-dimensional data.
**Table** can be used where **[flow][api-flow-content]** content is expected.
Its content model is **[table][api-table-content]** content.
The *[head][github-unist-head]* of the node represents the labels of the
columns.
An `align` field can be present.
If present, it must be a list of **[alignTypes][api-align-type]**.
It represents how cells in columns are aligned.
For example, the following markdown:
```markdown
| foo | bar |
| :-- | :-: |
| baz | qux |
```
Yields:
```js
{
type: 'table',
align: ['left', 'center'],
children: [
{
type: 'tableRow',
children: [
{
type: 'tableCell',
children: [{type: 'text', value: 'foo'}]
},
{
type: 'tableCell',
children: [{type: 'text', value: 'bar'}]
}
]
},
{
type: 'tableRow',
children: [
{
type: 'tableCell',
children: [{type: 'text', value: 'baz'}]
},
{
type: 'tableCell',
children: [{type: 'text', value: 'qux'}]
}
]
}
]
}
```
#### `TableRow`
```idl
interface TableRow <: Parent {
type: "tableRow"
children: [RowContent]
}
```
**TableRow** (**[Parent][github-mdast-parent]**) represents a row of cells in
a table.
**TableRow** can be used where **[table][api-table-content]** content is
expected.
Its content model is **[row][api-row-content]** content.
If the node is a *[head][github-unist-head]*,
it represents the labels of the columns for its parent **[Table][api-table]**.
For an example, see **[Table][api-table]**.
#### `TableCell`
```idl
interface TableCell <: Parent {
type: "tableCell"
children: [PhrasingContent]
}
```
**TableCell** (**[Parent][github-mdast-parent]**) represents a header cell in
a **[Table][api-table]**, if its parent is a *[head][github-unist-head]*,
or a data cell otherwise.
**TableCell** can be used where **[row][api-row-content]** content is expected.
Its content model is **[phrasing][github-mdast-phrasing-content]** content
excluding **[Break][github-mdast-break]** nodes.
For an example, see **[Table][api-table]**.
### Enumeration
#### `alignType`
```idl
enum alignType {
'center' | 'left' | 'right' | null
}
```
**alignType** represents how phrasing content is aligned
([\[CSSTEXT\]][spec-css-text]).
* **`'left'`**: See the [`left`][spec-css-text-align-left] value of the
`text-align` CSS property
* **`'right'`**: See the [`right`][spec-css-text-align-right] value of the
`text-align` CSS property
* **`'center'`**: See the [`center`][spec-css-text-align-center] value of
the `text-align` CSS property
* **`null`**: phrasing content is aligned as defined by the host environment
### Content model
#### `FlowContent` (GFM table)
```idl
type FlowContentGfm = Table | FlowContent
```
#### `TableContent`
```idl
type TableContent = TableRow
```
**Table** content represent the rows in a table.
#### `RowContent`
```idl
type RowContent = TableCell
```
**Row** content represent the cells in a row.
## Types
This package is fully typed with [TypeScript][].
It exports the additional type [`Options`][api-options].
The `Table`, `TableRow`, and `TableCell` types of the mdast nodes are exposed
from `@types/mdast`.
## Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, `mdast-util-gfm-table@^2`,
compatible with Node.js 16.
This utility works with `mdast-util-from-markdown` version 2+ and
`mdast-util-to-markdown` version 2+.
## Related
* [`remark-gfm`][github-remark-gfm]
— remark plugin to support GFM
* [`mdast-util-gfm`][github-mdast-util-gfm]
— same but all of GFM (autolink literals, footnotes, strikethrough, tables,
tasklists)
* [`micromark-extension-gfm-table`][github-micromark-extension-gfm-table]
— micromark extension to parse GFM tables
## Contribute
See [`contributing.md`][health-contributing] in
[`syntax-tree/.github`][health] for ways to get started.
See [`support.md`][health-support] for ways to get help.
This project has a [code of conduct][health-coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
## License
[MIT][file-license] © [Titus Wormer][wooorm]
<!-- Definitions -->
[api-align-type]: #aligntype
[api-flow-content]: #flowcontent-gfm-table
[api-gfm-table-from-markdown]: #gfmtablefrommarkdown
[api-gfm-table-to-markdown]: #gfmtabletomarkdownoptions
[api-options]: #options
[api-row-content]: #rowcontent
[api-table]: #table
[api-table-content]: #tablecontent
[badge-build-image]: https://github.com/syntax-tree/mdast-util-gfm-table/workflows/main/badge.svg
[badge-build-url]: https://github.com/syntax-tree/mdast-util-gfm-table/actions
[badge-coverage-image]: https://img.shields.io/codecov/c/github/syntax-tree/mdast-util-gfm-table.svg
[badge-coverage-url]: https://codecov.io/github/syntax-tree/mdast-util-gfm-table
[badge-downloads-image]: https://img.shields.io/npm/dm/mdast-util-gfm-table.svg
[badge-downloads-url]: https://www.npmjs.com/package/mdast-util-gfm-table
[badge-size-image]: https://img.shields.io/bundlejs/size/mdast-util-gfm-table
[badge-size-url]: https://bundlejs.com/?q=mdast-util-gfm-table
[esmsh]: https://esm.sh
[file-license]: license
[github-gist-esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[github-mdast]: https://github.com/syntax-tree/mdast
[github-mdast-break]: https://github.com/syntax-tree/mdast#break
[github-mdast-parent]: https://github.com/syntax-tree/mdast#parent
[github-mdast-phrasing-content]: https://github.com/syntax-tree/mdast#phrasingcontent
[github-mdast-util-from-markdown]: https://github.com/syntax-tree/mdast-util-from-markdown
[github-mdast-util-from-markdown-extension]: https://github.com/syntax-tree/mdast-util-from-markdown#extension
[github-mdast-util-gfm]: https://github.com/syntax-tree/mdast-util-gfm
[github-mdast-util-to-hast]: https://github.com/syntax-tree/mdast-util-to-hast
[github-mdast-util-to-markdown]: https://github.com/syntax-tree/mdast-util-to-markdown
[github-mdast-util-to-markdown-options]: https://github.com/syntax-tree/mdast-util-to-markdown#options
[github-micromark]: https://github.com/micromark/micromark
[github-micromark-extension-gfm-table]: https://github.com/micromark/micromark-extension-gfm-table
[github-micromark-extension-gfm-table-syntax]: https://github.com/micromark/micromark-extension-gfm-table#syntax
[github-remark-gfm]: https://github.com/remarkjs/remark-gfm
[github-string-width]: https://github.com/sindresorhus/string-width
[github-unist-head]: https://github.com/syntax-tree/unist#head
[health]: https://github.com/syntax-tree/.github
[health-coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
[health-contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
[health-support]: https://github.com/syntax-tree/.github/blob/main/support.md
[npmjs-install]: https://docs.npmjs.com/cli/install
[spec-css-text]: https://drafts.csswg.org/css-text/
[spec-css-text-align-center]: https://drafts.csswg.org/css-text/#valdef-text-align-center
[spec-css-text-align-left]: https://drafts.csswg.org/css-text/#valdef-text-align-left
[spec-css-text-align-right]: https://drafts.csswg.org/css-text/#valdef-text-align-right
[spec-gfm]: https://github.github.com/gfm/
[typescript]: https://www.typescriptlang.org
[wooorm]: https://wooorm.com