Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: wooorm/markdown-table
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 3.0.1
Choose a base ref
...
head repository: wooorm/markdown-table
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: 3.0.2
Choose a head ref
  • 5 commits
  • 4 files changed
  • 2 contributors

Commits on Nov 14, 2021

  1. Fix typo

    Closes GH-26.
    
    Reviewed-by: Titus Wormer <tituswormer@gmail.com>
    hugovk authored Nov 14, 2021
    Copy the full SHA
    b9871fb View commit details

Commits on Dec 4, 2021

  1. Update dev-dependencies

    wooorm committed Dec 4, 2021
    Copy the full SHA
    5818440 View commit details
  2. Refactor

    wooorm committed Dec 4, 2021
    Copy the full SHA
    d1cd6fa View commit details

Commits on Dec 5, 2021

  1. Update docs

    wooorm committed Dec 5, 2021
    Copy the full SHA
    17921de View commit details
  2. 3.0.2

    wooorm committed Dec 5, 2021
    Copy the full SHA
    f50801f View commit details
Showing with 303 additions and 101 deletions.
  1. +3 −3 .gitignore
  2. +193 −70 index.js
  3. +9 −9 package.json
  4. +98 −19 readme.md
6 changes: 3 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.DS_Store
*.d.ts
*.log
coverage/
node_modules/
*.d.ts
*.log
.DS_Store
yarn.lock
263 changes: 193 additions & 70 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,189 @@
/**
* @typedef MarkdownTableOptions
* @property {string|null|Array.<string|null|undefined>} [align]
* @typedef Options
* Configuration (optional).
* @property {string|null|Array<string|null|undefined>} [align]
* One style for all columns, or styles for their respective columns.
* Each style is either `'l'` (left), `'r'` (right), or `'c'` (center).
* Other values are treated as `''`, which doesn’t place the colon in the
* alignment row but does align left.
* *Only the lowercased first character is used, so `Right` is fine.*
* @property {boolean} [padding=true]
* Whether to add a space of padding between delimiters and cells.
*
* When `true`, there is padding:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there is no padding:
*
* ```markdown
* |Alpha|B |
* |-----|-----|
* |C |Delta|
* ```
* @property {boolean} [delimiterStart=true]
* @property {boolean} [delimiterStart=true]
* Whether to begin each row with the delimiter.
*
* > 👉 **Note**: please don’t use this: it could create fragile structures
* > that aren’t understandable to some markdown parsers.
*
* When `true`, there are starting delimiters:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there are no starting delimiters:
*
* ```markdown
* Alpha | B |
* ----- | ----- |
* C | Delta |
* ```
* @property {boolean} [delimiterEnd=true]
* Whether to end each row with the delimiter.
*
* > 👉 **Note**: please don’t use this: it could create fragile structures
* > that aren’t understandable to some markdown parsers.
*
* When `true`, there are ending delimiters:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there are no ending delimiters:
*
* ```markdown
* | Alpha | B
* | ----- | -----
* | C | Delta
* ```
* @property {boolean} [alignDelimiters=true]
* Whether to align the delimiters.
* By default, they are aligned:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* Pass `false` to make them staggered:
*
* ```markdown
* | Alpha | B |
* | - | - |
* | C | Delta |
* ```
* @property {(value: string) => number} [stringLength]
* Function to detect the length of table cell content.
* This is used when aligning the delimiters (`|`) between table cells.
* Full-width characters and emoji mess up delimiter alignment when viewing
* the markdown source.
* To fix this, you can pass this function, which receives the cell content
* and returns its “visible” size.
* Note that what is and isn’t visible depends on where the text is displayed.
*
* Without such a function, the following:
*
* ```js
* markdownTable([
* ['Alpha', 'Bravo'],
* ['中文', 'Charlie'],
* ['👩‍❤️‍👩', 'Delta']
* ])
* ```
*
* Yields:
*
* ```markdown
* | Alpha | Bravo |
* | - | - |
* | 中文 | Charlie |
* | 👩‍❤️‍👩 | Delta |
* ```
*
* With [`string-width`](https://github.com/sindresorhus/string-width):
*
* ```js
* import stringWidth from 'string-width'
*
* markdownTable(
* [
* ['Alpha', 'Bravo'],
* ['中文', 'Charlie'],
* ['👩‍❤️‍👩', 'Delta']
* ],
* {stringLength: stringWidth}
* )
* ```
*
* Yields:
*
* ```markdown
* | Alpha | Bravo |
* | ----- | ------- |
* | 中文 | Charlie |
* | 👩‍❤️‍👩 | Delta |
* ```
*/

/**
* @typedef {Options} MarkdownTableOptions
* @todo
* Remove next major.
*/

/**
* Create a table from a matrix of strings.
* Generate a markdown ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables)) table..
*
* @param {Array.<Array.<string|null|undefined>>} table
* @param {MarkdownTableOptions} [options]
* @param {Array<Array<string|null|undefined>>} table
* Table data (matrix of strings).
* @param {Options} [options]
* Configuration (optional).
* @returns {string}
*/
export function markdownTable(table, options) {
const settings = options || {}
const align = (settings.align || []).concat()
const stringLength = settings.stringLength || defaultStringLength
/** @type {number[]} Character codes as symbols for alignment per column. */
export function markdownTable(table, options = {}) {
const align = (options.align || []).concat()
const stringLength = options.stringLength || defaultStringLength
/** @type {Array<number>} Character codes as symbols for alignment per column. */
const alignments = []
let rowIndex = -1
/** @type {string[][]} Cells per row. */
/** @type {Array<Array<string>>} Cells per row. */
const cellMatrix = []
/** @type {number[][]} Sizes of each cell per row. */
/** @type {Array<Array<number>>} Sizes of each cell per row. */
const sizeMatrix = []
/** @type {number[]} */
/** @type {Array<number>} */
const longestCellByColumn = []
let mostCellsPerRow = 0
/** @type {number} */
let columnIndex
/** @type {string[]} Cells of current row */
let row
/** @type {number[]} Sizes of current row */
let sizes
/** @type {number} Sizes of current cell */
let size
/** @type {string} Current cell */
let cell
/** @type {string[]} Chunks of current line. */
let line
/** @type {string} */
let before
/** @type {string} */
let after
/** @type {number} */
let code
let rowIndex = -1

// This is a superfluous loop if we don’t align delimiters, but otherwise we’d
// do superfluous work when aligning, so optimize for aligning.
while (++rowIndex < table.length) {
columnIndex = -1
row = []
sizes = []
/** @type {Array<string>} */
const row = []
/** @type {Array<number>} */
const sizes = []
let columnIndex = -1

if (table[rowIndex].length > mostCellsPerRow) {
mostCellsPerRow = table[rowIndex].length
}

while (++columnIndex < table[rowIndex].length) {
cell = serialize(table[rowIndex][columnIndex])
const cell = serialize(table[rowIndex][columnIndex])

if (settings.alignDelimiters !== false) {
size = stringLength(cell)
if (options.alignDelimiters !== false) {
const size = stringLength(cell)
sizes[columnIndex] = size

if (
@@ -83,14 +202,14 @@ export function markdownTable(table, options) {
}

// Figure out which alignments to use.
columnIndex = -1
let columnIndex = -1

if (typeof align === 'object' && 'length' in align) {
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = toAlignment(align[columnIndex])
}
} else {
code = toAlignment(align)
const code = toAlignment(align)

while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = code
@@ -99,13 +218,15 @@ export function markdownTable(table, options) {

// Inject the alignment row.
columnIndex = -1
row = []
sizes = []
/** @type {Array<string>} */
const row = []
/** @type {Array<number>} */
const sizes = []

while (++columnIndex < mostCellsPerRow) {
code = alignments[columnIndex]
before = ''
after = ''
const code = alignments[columnIndex]
let before = ''
let after = ''

if (code === 99 /* `c` */) {
before = ':'
@@ -117,17 +238,17 @@ export function markdownTable(table, options) {
}

// There *must* be at least one hyphen-minus in each alignment cell.
size =
settings.alignDelimiters === false
let size =
options.alignDelimiters === false
? 1
: Math.max(
1,
longestCellByColumn[columnIndex] - before.length - after.length
)

cell = before + '-'.repeat(size) + after
const cell = before + '-'.repeat(size) + after

if (settings.alignDelimiters !== false) {
if (options.alignDelimiters !== false) {
size = before.length + size + after.length

if (size > longestCellByColumn[columnIndex]) {
@@ -145,23 +266,25 @@ export function markdownTable(table, options) {
sizeMatrix.splice(1, 0, sizes)

rowIndex = -1
/** @type {string[]} */
/** @type {Array<string>} */
const lines = []

while (++rowIndex < cellMatrix.length) {
row = cellMatrix[rowIndex]
sizes = sizeMatrix[rowIndex]
const row = cellMatrix[rowIndex]
const sizes = sizeMatrix[rowIndex]
columnIndex = -1
line = []
/** @type {Array<string>} */
const line = []

while (++columnIndex < mostCellsPerRow) {
cell = row[columnIndex] || ''
before = ''
after = ''
const cell = row[columnIndex] || ''
let before = ''
let after = ''

if (settings.alignDelimiters !== false) {
size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)
code = alignments[columnIndex]
if (options.alignDelimiters !== false) {
const size =
longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)
const code = alignments[columnIndex]

if (code === 114 /* `r` */) {
before = ' '.repeat(size)
@@ -178,44 +301,44 @@ export function markdownTable(table, options) {
}
}

if (settings.delimiterStart !== false && !columnIndex) {
if (options.delimiterStart !== false && !columnIndex) {
line.push('|')
}

if (
settings.padding !== false &&
options.padding !== false &&
// Don’t add the opening space if we’re not aligning and the cell is
// empty: there will be a closing space.
!(settings.alignDelimiters === false && cell === '') &&
(settings.delimiterStart !== false || columnIndex)
!(options.alignDelimiters === false && cell === '') &&
(options.delimiterStart !== false || columnIndex)
) {
line.push(' ')
}

if (settings.alignDelimiters !== false) {
if (options.alignDelimiters !== false) {
line.push(before)
}

line.push(cell)

if (settings.alignDelimiters !== false) {
if (options.alignDelimiters !== false) {
line.push(after)
}

if (settings.padding !== false) {
if (options.padding !== false) {
line.push(' ')
}

if (
settings.delimiterEnd !== false ||
options.delimiterEnd !== false ||
columnIndex !== mostCellsPerRow - 1
) {
line.push('|')
}
}

lines.push(
settings.delimiterEnd === false
options.delimiterEnd === false
? line.join('').replace(/ +$/, '')
: line.join('')
)
@@ -245,7 +368,7 @@ function defaultStringLength(value) {
* @returns {number}
*/
function toAlignment(value) {
const code = typeof value === 'string' ? value.charCodeAt(0) : 0
const code = typeof value === 'string' ? value.codePointAt(0) : 0

return code === 67 /* `C` */ || code === 99 /* `c` */
? 99 /* `c` */
18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "markdown-table",
"version": "3.0.1",
"description": "Markdown tables",
"version": "3.0.2",
"description": "Generate a markdown (GFM) table",
"license": "MIT",
"keywords": [
"text",
@@ -32,23 +32,23 @@
"devDependencies": {
"@types/tape": "^4.0.0",
"c8": "^7.0.0",
"chalk": "^4.0.0",
"chalk": "^5.0.0",
"prettier": "^2.0.0",
"remark-cli": "^9.0.0",
"remark-preset-wooorm": "^8.0.0",
"remark-cli": "^10.0.0",
"remark-preset-wooorm": "^9.0.0",
"rimraf": "^3.0.0",
"strip-ansi": "^7.0.0",
"tape": "^5.0.0",
"type-coverage": "^2.0.0",
"typescript": "^4.0.0",
"xo": "^0.39.0"
"xo": "^0.47.0"
},
"scripts": {
"prepack": "npm run build && npm run format",
"prepublishOnly": "npm run build && npm run format",
"build": "rimraf \"*.d.ts\" && tsc && type-coverage",
"format": "remark . -qfo && prettier . -w --loglevel warn && xo --fix",
"test-api": "node test.js",
"test-coverage": "c8 --check-coverage --branches 100 --functions 100 --lines 100 --statements 100 --reporter lcov node test.js",
"test-api": "node --conditions development test.js",
"test-coverage": "c8 --check-coverage --branches 100 --functions 100 --lines 100 --statements 100 --reporter lcov npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"prettier": {
117 changes: 98 additions & 19 deletions readme.md
Original file line number Diff line number Diff line change
@@ -5,19 +5,62 @@
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]

Generate fancy [Markdown][fancy] tables.
Generate a markdown ([GFM][]) table.

## Install
## Contents

* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`markdownTable(table[, options])`](#markdowntabletable-options)
* [Types](#types)
* [Compatibility](#compatibility)
* [Security](#security)
* [Inspiration](#inspiration)
* [Contribute](#contribute)
* [License](#license)

## What is this?

This is a simple package that takes table data and generates a [GitHub flavored
markdown (GFM)][gfm] table.

This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c):
Node 12+ is needed to use it and it must be `import`ed instead of `require`d.
## When should I use this?

You can use this package when you want to generate the source code of a GFM
table from some data.

This is a simple solution in that it doesn’t handle escapes or HTML or any of
that.
For a complete but heavier solution, build an AST and serialize it with
[`mdast-util-to-markdown`][mdast-util-to-markdown] (with
[`mdast-util-gfm`][mdast-util-gfm]).

## Install

[npm][]:
This package is [ESM only][esm].
In Node.js (version 12.20+, 14.14+, or 16.0+), install with [npm][]:

```sh
npm install markdown-table
```

In Deno with [Skypack][]:

```js
import {markdownTable} from 'https://cdn.skypack.dev/markdown-table@3?dts'
```

In browsers with [Skypack][]:

```html
<script type="module">
import {markdownTable} from 'https://cdn.skypack.dev/markdown-table@3?min'
</script>
```

## Use

Typical usage (defaults to align left):
@@ -74,14 +117,16 @@ There is no default export.

### `markdownTable(table[, options])`

Turns a given matrix of strings (an array of arrays of strings) into a table.
Generate a markdown table from table data (matrix of strings).

##### `options`

Configuration (optional).

###### `options.align`

One style for all columns, or styles for their respective columns (`string` or
`string[]`).
`Array<string>`).
Each style is either `'l'` (left), `'r'` (right), or `'c'` (center).
Other values are treated as `''`, which doesn’t place the colon in the alignment
row but does align left.
@@ -112,8 +157,8 @@ When `false`, there is no padding:

Whether to begin each row with the delimiter (`boolean`, default: `true`).

Note: please don’t use this: it could create fragile structures that aren’t
understandable to some Markdown parsers.
> 👉 **Note**: please don’t use this: it could create fragile structures that
> aren’t understandable to some markdown parsers.
When `true`, there are starting delimiters:

@@ -135,8 +180,8 @@ C | Delta |

Whether to end each row with the delimiter (`boolean`, default: `true`).

Note: please don’t use this: it could create fragile structures that aren’t
understandable to some Markdown parsers.
> 👉 **Note**: please don’t use this: it could create fragile structures that
> aren’t understandable to some markdown parsers.
When `true`, there are ending delimiters:

@@ -175,12 +220,14 @@ Pass `false` to make them staggered:

###### `options.stringLength`

Method to detect the length of a cell (`Function`, default: `s => s.length`).

Full-width characters and ANSI-sequences all mess up delimiter alignment
when viewing the Markdown source.
To fix this, you have to pass in a `stringLength` option to detect the “visible”
length of a cell (note that what is and isn’t visible depends on your editor).
Function to detect the length of table cell content (`Function`, default:
`s => s.length`).
This is used when aligning the delimiters (`|`) between table cells.
Full-width characters and emoji mess up delimiter alignment when viewing the
markdown source.
To fix this, you can pass this function, which receives the cell content and
returns its “visible” size.
Note that what is and isn’t visible depends on where the text is displayed.

Without such a function, the following:

@@ -212,7 +259,7 @@ markdownTable(
['中文', 'Charlie'],
['👩‍❤️‍👩', 'Delta']
],
{stringLength: width}
{stringLength: stringWidth}
)
```

@@ -225,11 +272,31 @@ Yields:
| 👩‍❤️‍👩 | Delta |
```

## Types

This package is fully typed with [TypeScript][].
It exports additional `Options` type that models its respective interface.

## Compatibility

This package is at least compatible with all maintained versions of Node.js.
As of now, that is Node.js 12.20+, 14.14+, and 16.0+.
It also works in Deno and modern browsers.

## Security

This package is safe.

## Inspiration

The original idea and basic implementation was inspired by James Halliday’s
[`text-table`][text-table] library.

## Contribute

Yes please!
See [How to Contribute to Open Source][contribute].

## License

[MIT][license] © [Titus Wormer][author]
@@ -254,12 +321,24 @@ The original idea and basic implementation was inspired by James Halliday’s

[npm]: https://docs.npmjs.com/cli/install

[skypack]: https://www.skypack.dev

[license]: license

[author]: https://wooorm.com

[fancy]: https://help.github.com/articles/github-flavored-markdown/#tables
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

[typescript]: https://www.typescriptlang.org

[contribute]: https://opensource.guide/how-to-contribute/

[gfm]: https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables

[text-table]: https://github.com/substack/text-table

[string-width]: https://github.com/sindresorhus/string-width

[mdast-util-to-markdown]: https://github.com/syntax-tree/mdast-util-to-markdown

[mdast-util-gfm]: https://github.com/syntax-tree/mdast-util-gfm