Giter Club home page Giter Club logo

tecfu / tty-table Goto Github PK

View Code? Open in Web Editor NEW
283.0 7.0 31.0 4.82 MB

Terminal table for Windows, Linux, and MacOS. Written in nodejs. Also works in browser console. Word wrap, padding, alignment, colors, Asian character support, per-column callbacks, and you can pass rows as objects or arrays. Backwards compatible with Automattic/cli-table.

Home Page: https://www.npmjs.com/package/tty-table

License: MIT License

JavaScript 100.00%
cli-table tty-table nodejs terminal-table table

tty-table's Introduction

tty-table 端子台

NPM version Coverage Status

Display your data in a table using a terminal, browser, or browser console.


See here for complete example list

To view all example output:

$ git clone https://github.com/tecfu/tty-table && cd tty-table && npm i
$ npm run view-examples

Terminal (Static)

examples/styles-and-formatting.js

Static

Terminal (Streaming)

$ node examples/data/fake-stream.js | tty-table --format json --header examples/config/header.js

Streaming

  • See the built-in help for the terminal version of tty-table with:
$ tty-table -h

Browser & Browser Console

Browser Console Example



API Reference

Table(header array, rows array, options object)

Param Type Description
header array Per-column configuration. An array of objects, one object for each column. Each object contains properties you can use to configure that particular column. See available properties
rows array Your data. An array of arrays or objects. See examples
options object Global table configuration. See available properties

header array of objects

Param Type Description
alias string Text to display in column header cell
align string default: "center"
color string default: terminal default color
footerAlign string default: "center"
footerColor string default: terminal default color
formatter function(cellValue, columnIndex, rowIndex, rowData, inputData Runs a callback on each cell value in the parent column.
Please note that fat arrow functions () => {} don't support scope overrides, and this feature won't work correctly within them.
@formatter configure function(object) Configure cell properties. For example:
this.configure({ truncate: false, align: "left" }) More here.
@formatter resetStyle function(cellValue) Removes ANSI escape sequences. For example:
this.resetStyle("�[32m� myText��[39m") // "myText"
@formatter style function(cellValue, effect) Style cell value. For example:
this.style("mytext", "bold", "green", "underline")
For a full list of options in the terminal: chalk. For a full list of options in the browser: kleur
headerAlign string default: "center"
headerColor string default: terminal's default color
marginLeft integer default: 0
marginTop integer default: 0
paddingBottom integer default: 0
paddingLeft integer default: 1
paddingRight integer default: 1
paddingTop integer default: 0
value string Name of the property to display in each cell when data passed as an array of objects
width string || integer default: "auto"
Can be a percentage of table width i.e. "20%" or a fixed number of columns i.e. "20".
When set to the default ("auto"), the column widths are made proportionate by the longest value in each column.
Note: Percentage columns and fixed value colums not intended to be mixed in the same table.

Example

let header = [{
  value: "item",
  headerColor: "cyan",
  color: "white",
  align: "left",
  width: 20
},
{
  value: "price",
  color: "red",
  width: 10,
  formatter: function (value) {
    let str = `$${value.toFixed(2)}`
    return (value > 5) ? this.style(str, "green", "bold") : 
      this.style(str, "red", "underline")
  }
}]


rows array

Example

  • each row an array
const rows = [
  ["hamburger",2.50],
]
  • each row an object
const rows = [
  {
    item: "hamburger",
    price: 2.50
  }
]


footer array

  • Footer is optional

Example

const footer = [
  "TOTAL",
  function (cellValue, columnIndex, rowIndex, rowData) {
    let total = rowData.reduce((prev, curr) => {
      return prev + curr[1]
    }, 0)
    .toFixed(2)

    return this.style(`$${total}`, "italic")
  }
]


options object

Param Type Description
borderStyle string default: "solid".
options: "solid", "dashed", "none"
borderColor string default: terminal default color
color string default: terminal default color
compact boolean default: false
Removes horizontal borders when true.
defaultErrorValue mixed default: '�'
defaultValue mixed default: '?'
errorOnNull boolean default: false
truncate mixed default: false
When this property is set to a string, cell contents will be truncated by that string instead of wrapped when they extend beyond of the width of the cell.
For example if:
"truncate":"..."
the cell will be truncated with "..."
Note: tty-table wraps overflowing cell text into multiple lines by default, so you would likely only utilize truncate for extremely long values.
width string default: "100%"
Width of the table. Can be a percentage of i.e. "50%" or a fixed number of columns in the terminal viewport i.e. "100".
Note: When you use a percentage, your table will be "responsive".

Example

const options = {
  borderStyle: "solid",
  borderColor: "blue",
  headerAlign: "center",
  align: "left",
  color: "white",
  truncate: "...",
  width: "90%"
}

Table.render() ⇒ String

Add method to render table to a string

Example

const out = Table(header,rows,options).render()
console.log(out); //prints output


Installation

$ npm install tty-table -g
  • Node Module
$ npm install tty-table
  • Browser
import Table from 'https://cdn.jsdelivr.net/gh/tecfu/tty-table/dist/tty-table.esm.js'
let Table = require('tty-table')   // https://cdn.jsdelivr.net/gh/tecfu/tty-table/dist/tty-table.cjs.js
let Table = TTY_Table;             // https://cdn.jsdelivr.net/gh/tecfu/tty-table/dist/tty-table.umd.js

Version Compatibility

Node Version tty-table Version
8 >= 2.0
0.11 >= 0.0

Running tests

$ npm test
$ npm run coverage

Saving the output of new unit tests

$ npm run save-tests

Dev Tips

  • To generate vim tags (make sure jsctags is installed globally)
$ npm run tags
  • To generate vim tags on file save
$ npm run watch-tags

Pull Requests

Pull requests are encouraged!

  • Please remember to add a unit test when necessary
  • Please format your commit messages according to the "Conventional Commits" specification

If you aren't familiar with Conventional Commits, here's a good article on the topic

TL/DR:

  • feat: a feature that is visible for end users.
  • fix: a bugfix that is visible for end users.
  • chore: a change that doesn't impact end users (e.g. chances to CI pipeline)
  • docs: a change in the README or documentation
  • refactor: a change in production code focused on readability, style and/or performance.

License

MIT License

Copyright 2015-2020, Tecfu.

tty-table's People

Contributors

andarist avatar arliang avatar dependabot[bot] avatar gcaufy avatar georapbox avatar ibmjanneme avatar jzakrzewski avatar mrwan200 avatar mscalora avatar ndelangen avatar s10akir avatar tecfu avatar vmarchaud avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

tty-table's Issues

Vertical table support - SOLVED

Are vertical tables supported? If yes, example should be added to documentation, since it
s not quite clear for new user like me. Thanks.

Table formatting not proper in ITERM

Problem Summary

an extra column is added when running from ITERM, however it works fine from terminal

Expected Result (screen shot if possible)

image

Actual Result (screen shot if possible)

image

Environment Information

  • OS: MacOS Mojave

  • Terminal Emulator:
    ITERM

Steps to Reproduce

  1. run the example code in ITERM

getAvailableWidth() should work without a width

Problem Summary

getAvailableWidth() should work without a width

This works:
node -e 'T=require("tty-table"); console.log(T([["a","b"]]).render())'

This now throws exception:
node -e 'T=require("tty-table"); console.log(T([["a","b"]]).render())' >/tmp/test.txt

Expected Result (screen shot if possible)

A reasonable table rendering

Should treat width as infinite (fit content) unless % columns are uses, then a reasonable default like 100 should be used.

Actual Result (screen shot if possible)

 node -e 'T=require("tty-table"); console.log(T([["a","b"]]).render())' >/tmp/test.txt

.../node_modules/tty-table/src/format.js:70
  throw new Error("Cannot auto discover available table width. Set table `width` option or export the environment variable COLUMNS")
  ^

Error: Cannot auto discover available table width. Set table `width` option or export the environment variable COLUMNS
    at getAvailableWidth (.../node_modules/tty-table/src/format.js:70:9)
    at Object.module.exports.getColumnWidths (.../node_modules/tty-table/src/format.js:207:26)
    at Object.module.exports.stringifyData (.../node_modules/tty-table/src/render.js:31:78)
    at Array.Factory.tableObject.render (.../node_modules/tty-table/src/factory.js:121:27)
    at [eval]:1:52
    at Script.runInThisContext (vm.js:116:20)
    at Object.runInThisContext (vm.js:306:38)
    at Object.<anonymous> ([eval]-wrapper:9:26)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at evalScript (internal/process/execution.js:80:25)

Environment Information

  • OS: Mac

  • Terminal Emulator: iTerm

Steps to Reproduce

  1. node -e 'T=require("tty-table"); console.log(T([["a","b"]]).render())' >/tmp/test.txt

Disable strict mode

Problem Summary

Short: Seems like tty-table is making the host use strict mode because of which my system is failing to make web pack build.

Detailed: my gulp task has dependency on 'css-loader' which is also using tty-table. css-loader relies on cssnano, which relies on postcss-filter-plugins, which relies on uniqid, which relies on macaddress. macaddress has a global leak in v0.2.8 but it has been fixed in v0.2.9 but uniqid hasn't updated its dependency version for macaddress.

Environment Information

  • OS: macOX Sierra

  • Terminal Emulator: Terminal

Steps to Reproduce

  1. Just import the uniqid and tty-table modules in same project.

screen shot 2018-04-23 at 5 14 23 pm

Resize code has several issues

Problem Summary

Resize code has several issues

  • Sometimes the table is too wide
  • The table is often more narrow than it needs to be
  • At very small sizes the formatting can be broken

Expected Result (screen shot if possible)

Formatting should always be correct and the table should always be the desired width

Actual Result (screen shot if possible)

See attached output of https://gist.github.com/mscalora/628b05731b7674a1993115752bafd1ee
resize-table.txt

Environment Information

  • OS: MacOS

  • Terminal Emulator: iTerm

Steps to Reproduce

  1. run: curl https://gist.githubusercontent.com/mscalora/628b05731b7674a1993115752bafd1ee/raw/41a1aab155d4235144513eebefe401fe10169456/resize-table.js | node -
  2. examine output

Fixes

I would like to take on fixing these issues and enhancing the table resize functionality with some addition options to better control how resize works:

  • Fix the proportional resize mode issue outline above
  • Add a resize mode that works like CSS flex layout "shrink" mechanism so one can specify which columns should be resized irrespective of content
  • Add a option for desired max output width that will override the terminal width (stdout.columns)
  • Add minimum column width option that can be set on all or specific columns
  • Maybe: Add an option to truncate the whole table if it can't fit in the max output width

Proposed new table options:

    maxTableWidth: "auto" (default) | "none" | number of char
    truncateTable: true (default, if > maxTableWidth) | false | # of char 
    minColWidth: number of char (4 default)
    resizeTable: "proportional" (default) | "shrink" (only used if natural width is > maxTableWidth)

Proposed new column (header) options:

    minWidth: number of char (default is global minColWidth)
    shrink: [optional] used to weight resizing in "shrink" resize mode

Notes:

  • minWidth would be respected by both resize modes

Shrink Mode

  Columns are reduced using the weighting of  shrink / sum(all shrinks)
    Col  |  Shink  | Proportion of resize
     A   |    0    |  none
     A   |    1    |  1/5 or 20%
     A   |    4    |  4/5 or 80%

Discussion

I've actually already started and have most of the work done. I planned on submitting a pull request but wanted to start a discussion and get feedback while I'm still working on it. I understand it may be a a lot of complexity for the scope of this project so I am happy to fork if it is judged to be beyond the desired scope since I need something like this. Also, I can fix some of the issues listed at the top without the new features but it would be a significant amount of extra work to pull that out. I was trying to implement a "legacy" mode but these issues I ran into make that difficult, the broken formatting may only be fixable with some changes like minWidth or using a truncated truncation string.

Column misaligned for wide tables (high number of columns) and narrow screen

Problem Summary

Column misaligned for wide tables (high number of columns) and narrow screen which causes some columns size < 2

Expected Result (screen shot if possible)

The columns should be aligned no matter how wide it is.

Actual Result (screen shot if possible)

Screen Shot 2021-07-25 at 6 31 32 PM

Environment Information

  • OS:

  • Terminal Emulator:

  • Node Version:

Steps to Reproduce

  1. Prepare a data file: data_wide.csv with following content:
F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10
F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F101212121212121212122121212121212121212121212121
  1. Run: cat data_wide.csv | tty-table --options-width 20
  2. It will generated the misaligned table as attached.

Proposed fix

In the resize, keep the minimum columns size to 2.

rendering issue if truncate is true and first header cell needs truncation

Problem Summary

rendering issue if truncate is true and first header cell needs truncation

Change examples/truncated-lines.js line 6 to:

value: "item name",

Expected Result (screen shot if possible)

Table 3 of :

┌──────────┬──────────┬──────────┐
│ item nam │  price   │ organic  │
├──────────┼──────────┼──────────┤
│ chocolat │   5.65   │    no    │
└──────────┴──────────┴──────────┘

Actual Result (screen shot if possible)

  ┌──────────┬──────────┬──────────┐
  │item nametrue│  price   │ organic  │
  ├──────────┼──────────┼──────────┤
  │ chocolat │   5.65   │    no    │
  └──────────┴──────────┴──────────┘

Environment Information

  • OS: Mac OS

  • Terminal Emulator: iTerm

Steps to Reproduce

  1. Change examples/truncated-lines.js line 6 to: value: "item name",
  2. Run examples/truncated-lines.js

Cause

Format.wrapCellContent mutates truncate values of true in config after the very first cell's cellOptions have been created, Format.handleTruncatedValue uses the untranslated truncate value as if it is always a string.

Fix

See pull request #48

Nested tables

Hi, I tried to return a table.render() in a formatter function but broke everything.
Is nesting tables possible?
Am I missing something?

Thanks!

Error: Number of columns is inconsistent on line 363

I have csv file with line number of 365.

When i remove line 363. It still throw the error until my csv total line become 362.

I think the only line it can read is 363?

Command i use to read is.
cat filename.csv | tty-table

environment: osx 10.12.6
node: v6.10.3

npm test OR node examples/cli-test.js fails

Problem Summary

tests are broken

Expected Result (screen shot if possible)

pass

Actual Result (screen shot if possible)

errors on every test

Environment Information

  • OS: Mac

  • Terminal Emulator: iTerm

Steps to Reproduce

  1. git clone [email protected]:tecfu/tty-table.git
  2. cd tty-table
  3. npm install
  4. npm test

Maybe smartwrap dependency is out of date?

when:
node examples/cli-test.js

I get:
...tty-table/node_modules/smartwrap/src/main.js:286
return processedLines.flat(2).join("\n")
TypeError: processedLines.flat is not a function

Using a falsy value like 0 in a cell displays nothing

Problem Summary

Using a falsy value like 0 in a cell displays nothing

Expected Result (screen shot if possible)

2020-12-06-194202_479x197_scrot

Actual Result (screen shot if possible)

2020-12-06-194112_493x211_scrot

Environment Information

  • OS: Ubuntu 20.04.1 LTS

  • Terminal Emulator: gnome terminal

  • Node Version: 12

Steps to Reproduce

  • Set a cell to 0
  • render

Table Headline and colspan?

Could be cool to add a headline like in a html fieldset the legend and also to add colspan if I want to have one table col across two.

emoji split in word wrap

Problem Summary

Emoji is being split in half nu the wordwrap mechanism

Expected Result (screen shot if possible)

emoji should wrap instead of being split

Actual Result (screen shot if possible)

illegal char error symbol
wrap-bug

Environment Information

  • OS: Mac

  • Terminal Emulator: iTerm

Steps to Reproduce

  1. run this code form example folder:
const Table = require("../")

process.stdout.columns = process.argv[2] && parseInt(process.argv[2]) || 25

console.log("Starting... (user CTRL-C to give up)")
console.log("\"fix\" by uncommenting line format.js:70")

let output = new Table([
  {minWidth: 6, shrink: 0},
  {minWidth: 12, shrink: 1},
  {minWidth: 24, shrink: 1000}
], [[
  "aaa bbb ccc",
  "aaa bbb ccc 😀😃😄😁 eee fff ggg hhh",
  "aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp qqq rrr sss ttt"
]], {
  paddingLeft: 0,
  paddingRight: 0,
  marginTop: 0
}).render()

console.log(output)

Discussion

I did not to dig into this one very much, not sure if the cause is in the smartwrap module

Pass styling when representing a JSON stream

I'm trying to represent a JSON stream, by piping my script with | tty-table --format=json
However the table is too little for it and it's not being visualized properly. Can i pass styling to it?

schermata 2016-11-28 alle 18 45 30

Also, it would seem that when the table has more than two rows it bugs out? Or am i doing something wrong?

schermata 2016-11-28 alle 19 22 02

Footer align does not work

Problem Summary

I am trying to align a footer cell to right.

Expected Result (screen shot if possible)

Actual Result (screen shot if possible)

Bildschirmfoto 2020-07-02 um 11 14 41

Environment Information

  • OS: latest public macOS

  • Terminal Emulator: iTerm2 with zsh and zprezto plugin

  • Node Version: LTS

Steps to Reproduce

  const header = [
    {
      value: 'Test',
      align: 'left',
      headerAlign: 'left',
      footerAlign: 'right',
    },
    {
      value: 'Score',
      align: 'left',
      headerAlign: 'left',
      footerAlign: 'left',
      formatter: (cellValue) => {
        return cellValue > 60 ? green(cellValue) : red(cellValue)
      },
    },
  ]
  const rows = [
    ['Performance', 64],
    ['Accessibility', 70],
    ['Best Practices', 30],
    ['SEO', 60],
    ['PWA', 100],
  ]
  const footer = [
    'Total',
    (cellValue, columnIndex, rowIndex, rowData) => {
      const total = Math.round(rowData.map((i) => i[1]).reduce((p, c) => p + c) / 5)
      return italic(total)
    },
  ]
  const renderedTable = Table(header, rows, footer).render()
  console.log(renderedTable)

Prevent truncating on specific cell

Hi, I'm using truncate: "..." and global parameter for my table and I'm trying to prevent truncation on a single cell. I Had no luck with truncate: false (default value) which sets the cell content to "false" (bug?)

Any idea?
Thanks!

Error when shell is too narrow - SOLVED

Hey, it took me a while to figure out why previously working code started failing - it turns out that if the terminal window is too narrow, tty-table chokes:

/Users/nfriedly/vzw/node_modules/tty-table/src/main.js:290
                        prop = prop.toFixed(2)-0.01;
                                    ^

TypeError: prop.toFixed is not a function
    at Object._private.getColumnWidths (/Users/nfriedly/vzw/node_modules/tty-table/src/main.js:290:16)
    at Object._private.setup (/Users/nfriedly/vzw/node_modules/tty-table/src/main.js:323:42)
    at module.exports (/Users/nfriedly/vzw/node_modules/tty-table/src/main.js:460:20)
    at printTable (/Users/nfriedly/vzw/index.js:30:17)
    at Object.<anonymous> (/Users/nfriedly/vzw/index.js:40:1)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)

You can see my full code at https://gist.github.com/nfriedly/b80b569e2be2d2c86c18#file-3-analysis-js and I'm using http://fishshell.com/ (inside of webstorm, on OS X) if it makes a difference.

Version 2.8.12 breaks backwards compatibility with version 2.8.11

Problem Summary

Upgrading from 2.8.11 to 2.8.12 broke my application. After investigating, I noticed that chalk was replaced with kleur in version 2.8.12. I was using whiteBright as a header color, which is supported by chalk, but not kleur. This is a backwards compatibility break, and I think it should have caused in a major version bump.

In addition to the BC break, it's no longer possible to use bright/bold colors in headers as far as I can tell. I think you'd need to introduce a header equivalent to the formatter option to restore that functionality.

Expected Result (screen shot if possible)

Using whiteBright as a header color should continue to work when upgrading from 2.8.11 to 2.8.12.

Actual Result (screen shot if possible)

Using whiteBright as a header color throws the following error:

TypeError: kleur[color] is not a function
    at /path/to/project/node_modules/tty-table/src/style.js:6:24
    at Array.reduce (<anonymous>:null:null)
    at Object.module.exports.color (/path/to/project/node_modules/tty-table/src/style.js:5:17)
    at Object.module.exports.colorizeCell (/path/to/project/node_modules/tty-table/src/style.js:28:19)
    at Object.module.exports.buildCell (/path/to/project/node_modules/tty-table/src/render.js:275:21)
    at Object.module.exports.buildRow (/path/to/project/node_modules/tty-table/src/render.js:177:21)
    at /path/to/project/node_modules/tty-table/src/render.js:45:24
    at Array.map (<anonymous>:null:null)
    at Object.module.exports.stringifyData (/path/to/project/node_modules/tty-table/src/render.js:44:45)
    at Array.Factory.tableObject.render (/path/to/project/node_modules/tty-table/src/factory.js:175:25)
    at outputSites (/path/to/project/node_modules/@codeworx/sparse-dev/src/server.js:112:34)
    at run (/path/to/project/node_modules/@codeworx/sparse-dev/src/server.js:69:15)
    at runMicrotasks (<anonymous>:null:null)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Environment Information

  • OS: N/A
  • Terminal Emulator: N/A

Steps to Reproduce

Run this code using 2.8.11, then 2.8.12. Observe that the upgrade breaks BC:

const Table = require('tty-table')

const header = [
  {
    value: 'Heading',
    headerColor: 'whiteBright',
  },
]
const rows = [['Row']]
const table = new Table(header, rows)

console.log(table.render())

Options 'truncate' doesn't play well with Chinese

Hi, I've been using this package recently, and I have to say it's an excellent package.

But I have a bit of a problem with the 'truncate' option:

const table = table (header, rows, {
  truncate: '... '
});

I've defined a 'table' object, but it doesn't seem to work properly with truncation issues like Chinese

e.g

As you can see it's not truncated correctly

Thank you very much if you can repair it in time

Embedded ansi

Problem Summary

Embedded ansi styling causes problems with column widths and line breaking doesn't work correctly.

Expected Result (screen shot if possible)

  • Columns should be sized to the text
  • Styling should be contained within cells and not bleed over into borders and other cells

Actual Result (screen shot if possible)

Columns are sized wrong and styling bleeds across lines and out of cells

Environment Information

  • OS: MacOS

  • Terminal Emulator: iTerm

Steps to Reproduce

run:

    const example = require("../test/example-utils.js"),
      kleur = require("kleur"),
      Table = require("../")
    
    const rows1 = [
        ["plain test", `one ${kleur.red("red")} word`, `some ${kleur.bold("bold")} and ${kleur.dim("dim")} words`]
      ],
      rows2 = [
        ["plain test", `a ${kleur.red("few red words in")} here`]
      ]
    
    function test(testName, tableWidth, rows, config) {
      console.log(`\n${kleur.cyan(testName)}`)
      example.init(`Test: ${testName}`, tableWidth)
      let table = new Table(rows, config),
        output = table.render()
    
      console.log(output)
      console.log("")
    }
    
    test("Embedded ansi column width", 100, rows1, {})
    
    test("Embedded ansi breaking", 20, rows2, {})

emoji bug

Hello everyone!

I have a problem with Windows and emoji =S

image

How can I fix it?

Access to entire row within formatter function

Hello, I have a formatter function defined on a header. Now the color I want to send depends on other fields within the row.

I want to do something like this:

const header = [
  {
    value: 'price',
    formatter(value) {
      const row = .....;   // How to get the whole row?

      if(!row.enabled) _color = 'gray';
      if(row.important) _color = 'red';

      return color(_color, value);
    }
  }
];

const rows [
  { item: 'banana', price: 1.99, important: true, enabled: true },
  { price: 'grapes', 2.99, important: false, enabled: false },
];

Is there a way to do it?

Breaks when used in browser with browserify

When using in browser with browserify, recent builds break with the message:

>> Error: Cannot find module 'spawn-sync' from './node_modules/cross-spawn'

The issue is, that there is no spawn-sync for browsers as spawning is not possible, I guess. So cross-spawn only works in node. I don't know if it was ever intended, but previous versions (until 2.2.x) worked great in the browsers console...
From Version 2.3.0 until the most recent versions, it does not work anymore.

$ npm ls cross-spawn
analyzer
└─┬ [email protected]
  └─┬ [email protected]
    └─┬ [email protected]
      └─┬ [email protected]
        └── [email protected] 

For now I am sticking with version 2.2.5, as my module must work in node.js and browsers, using the table as debug output.

infinite loop in line wrapping

Problem Summary

infinite loop in line wrapping when wide char are not handled correctly

Expected Result (screen shot if possible)

program terminating

Actual Result (screen shot if possible)

program never terminates

Environment Information

  • OS: Mac

  • Terminal Emulator: iTerm

Steps to Reproduce

  1. run this from examples folder:
    const Table = require("../")
    
    process.stdout.columns = 25
    
    console.log("Starting... (user CTRL-C to give up)")
    console.log("\"fix\" by uncommenting line format.js:70")
    
    let output = new Table([
      {minWidth: 6, shrink: 0},
      {minWidth: 12, shrink: 1},
      {minWidth: 24, shrink: 1000}
    ], [[
      "aaa bbb ccc",
      "aaa bbb ccc ddd eee fff ggg hhh",
      "aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp qqq rrr sss ttt"
    ], [
      "汉堡包",
      "特制的酱汁",
      "2玉米饼, 大米和豆类, 大米和豆类, 大米和豆类, 奶酪"
    ]], {
      paddingLeft: 0,
      paddingRight: 0,
      marginTop: 0
    }).render()
    
    console.log(output)

Note: uncommenting line format.js:70 prevents the infinite loop, it appears that the wide char detection is not working correctly. I'm not sure why the detation was changed to the RegExp, the commit message does not explain. Performance perhaps?

Automatic width not correct when using formatter

Problem Summary

I'm using a formatter function to add 'USD' to a money amount. The automatic column width is determined by the value before the formatter instead of the string returned by the formatter.

Expected Result (screen shot if possible)

Automatic column width should be wider.

Actual Result (screen shot if possible)

It's the width based on the original value before the formatter.

Steps to Reproduce

  1. Basic table code without specifying column widths
  2. formatter: (cellValue) => { return cellValue + ' USD' }
  3. Column is not wide enough.

Incorrect number of columns

Problem Summary

Version 2.5.6 introduce the following issue: It is not possible to have multiple tables with a different number of columns. Version 2.5.5. is ok.

Consider this code:

import table from 'tty-table';

const header = [
  { value: 'col1' },
  { value: 'col2' }
];

const rows = [[1, 2]];
console.log(table(header, rows).render());

const header2 = [
  { value: 'col1' },
  { value: 'col2' },
  { value: 'col3' }
];

const rows2 = [[1, 2, 3]];
console.log(table(header2, rows2).render());

Expected Result

image

Actual Result

image

Environment Information

  • OS: macOS High Sierra
  • Terminal: iTerm2

dependencies: merge performance

Problem Summary

The merge module is slow, the cli that i'm building depend on it to render few lines, i'm seing a ~4x difference between Object.assign and merge :
Object.assign:

/home/vmarchaud/****/bin/pmp.js status  0,48s user 0,04s system 40% cpu 1,276 total

Merge:

/home/vmarchaud/****/bin/pmp.js status  2,06s user 0,06s system 78% cpu 2,696 total

Expected Result (screen shot if possible)

image

Actual Result (screen shot if possible)

image

Environment Information

  • OS: Uubuntu 17.10

  • Terminal Emulator:
    Vscode (xterm.js)

Steps to Reproduce

  1. Have a CLI using tty-table
  2. Replace Merge here by Object.assign
  3. Profit

Conclusion

Would it be possible to use Object.assign when available ? I dont mind making a PR if needed

Markdown output

Hey, is there any way to make this thing output GitHub flavored markdown so that GitHub can render it?

Installation error

Problem Summary

npm ERR! Linux 4.4.0-18362-Microsoft
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "i"
npm ERR! node v8.10.0
npm ERR! npm v3.5.2
npm ERR! code EMISSINGARG

Expected Result (screen shot if possible)

Successful installation

Actual Result (screen shot if possible)

image

Environment Information

  • OS: Windows10 WSL2 ubuntu18.04

  • Terminal Emulator: bash

  • Node Version: v8.10.0

Steps to Reproduce

  1. git clone https://github.com/tecfu/tty-table && cd tty-table && npm i

Example code throws 'undefined'

Running code in examples/data/fake-stream.js with node process_name | tty-table --format=json

Output via console.log(JSON.stringify(array))

Throws undefined

Node v8.1.4

unexpected random newlines

Problem Summary

Sorry if the problem have already been adressed, altough I already looked at issues.

I use your package a lot and every time I use it, I get random newlines

Expected Result (screen shot if possible)

The same as below, expect -g on its line.

Actual Result (screen shot if possible)

tty-table-bug

Environment Information

  • OS: Windows, Linux

Steps to Reproduce

let Table = require('tty-table');

const rows = [[`The use of the secure-rm CLI is deprecated.
Migrate over -> secure-rm-cli. Run:
npm un secure-rm -g
npm i secure-rm-cli -g`]]

    const t1 = Table([], rows, {
      borderStyle: 1,
      borderColor: 'yellow',
      paddingBottom: 0,
      headerAlign: 'center',
      headerColor: 'yellow',
      align: 'center',
      color: 'white'
      // truncate: "..."
    })

    const str1 = t1.render()
    console.log(str1)
```

Single column tables display header value, not object value

Not sure if this is me or a bug. When using an array of objects with ONE property, the header "value" is used as the cell value.

var Table = require('tty-table');

var header = [
  {
    alias : "Is organic?",
    value : "organic",
    width : 15
  }
];

//Example with objects as rows
var rows = [
  {
    organic : "no"
  },
  {
    organic : "yes"
  },
  {
    organic : "no"
  },
  {
    organic : "yes"
  },
  {
    organic : "no"
  },
  {
    organic : "no"
  }
];

var t2 = Table(header,rows,{
  borderStyle : 1,
  paddingBottom : 0
});

var str2 = t2.render();
console.log(str2);

Produces:


  ┌──────────────┐
  │ Is organic?  │
  ├──────────────┤
  │   organic    │
  ├──────────────┤
  │   organic    │
  ├──────────────┤
  │   organic    │
  ├──────────────┤
  │   organic    │
  ├──────────────┤
  │   organic    │
  ├──────────────┤
  │   organic    │
  └──────────────┘

ignore excessive newlines

It it possible to get rid of excess new lines at the beginning of the table ? and around the heading ?

untitled

Also how to disable colors for the heading ?

  • OS: Windows 10 (Creator's Update)

  • Terminal Emulator: ConEmu

Thanks

Execption if there are no rows

Problem Summary

If I render a table that has no rows I become an exception.

Expected Result (screen shot if possible)

This is ideal (note the reduced row size):

  ┌─────────┬───────┬─────────┐
  │ Setting │ Value │ Default │
  ├─────────┼───────┼─────────┤
  └─────────┴───────┴─────────┘

Actual Result (screen shot if possible)

    let z = new Array(iterable[0].length); //create a new empty row
                                  ^

TypeError: Cannot read property 'length' of undefined
    at Object.Format.inferColumnWidth (/somewhere/node_modules/tty-table/src/format.js:196:35)
    at /somewhere/node_modules/tty-table/src/format.js:237:25
    at Array.map (<anonymous>)
    at Object.Format.getColumnWidths (/somewhere/node_modules/tty-table/src/format.js:222:25)
    at Object.Render.stringifyData (/somewhere/node_modules/tty-table/src/render.js:36:79)
    at Array.Factory.tableObject.render (/somewhere/node_modules/tty-table/src/factory.js:196:25)

Environment Information

  • OS: any

  • Terminal Emulator: any

Steps to Reproduce

const header = [
            {value: 'Setting', align: 'left'},
            {value: 'Value'},
            {value: 'Default'},
        ];
const rows = [];
return Table(header, rows, {compact: false}).render();

In reality the rows are generated from an external source and just evaluate to an empty array.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.