From a0f155defca060fd1bc21a925058884329f45b60 Mon Sep 17 00:00:00 2001 From: Tobias Bieniek Date: Sun, 10 Jun 2018 17:30:43 +0200 Subject: [PATCH] Add Prettier --- .eslintrc.js | 22 +- examples/basic-usage-examples.js | 214 +++++------ examples/col-and-row-span-examples.js | 341 +++++++---------- lib/print-example.js | 89 +++-- package.json | 12 +- src/cell.js | 234 ++++++------ src/layout-manager.js | 144 ++++--- src/table.js | 61 ++- src/utils.js | 194 +++++----- test/cell-test.js | 432 +++++++++++---------- test/example-tests.js | 4 +- test/layout-manager-test.js | 132 +++---- test/original-cli-table-index-tests.js | 467 +++++++++++------------ test/original-cli-table-newlines-test.js | 84 ++-- test/table-layout-test.js | 395 ++++++++----------- test/table-test.js | 68 ++-- test/utils-test.js | 311 +++++++-------- test/verify-legacy-compatibility-test.js | 146 ++++--- yarn.lock | 29 ++ 19 files changed, 1574 insertions(+), 1805 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 73a3e21..fb8b85b 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -3,19 +3,21 @@ module.exports = { ecmaVersion: 6, }, env: { - 'node': true, + node: true, }, - extends: 'eslint:recommended', + extends: ['eslint:recommended', 'prettier'], + plugins: ['prettier'], rules: { + 'prettier/prettier': 'error', 'no-control-regex': 'off', }, - overrides: [{ - // tests - files: [ - 'test/**/*.js', - ], - env: { - jest: true, + overrides: [ + { + // tests + files: ['test/**/*.js'], + env: { + jest: true, + }, }, - }], + ], }; diff --git a/examples/basic-usage-examples.js b/examples/basic-usage-examples.js index 0542b17..159788f 100644 --- a/examples/basic-usage-examples.js +++ b/examples/basic-usage-examples.js @@ -2,208 +2,200 @@ var Table = require('../src/table'); var colors = require('colors/safe'); module.exports = function(runTest) { - function it(name, fn) { var result = fn(); runTest(name, result[0], result[1], result[2]); } - it('Basic Usage',function(){ - function makeTable(){ + it('Basic Usage', function() { + function makeTable() { // By default, headers will be red, and borders will be grey - var table = new Table({head:['a','b']}); + var table = new Table({ head: ['a', 'b'] }); - table.push(['c','d']); + table.push(['c', 'd']); return table; } var expected = [ - colors.gray('┌───') + colors.gray('┬───┐') - , colors.gray('│') + colors.red(' a ') + colors.gray('│') + colors.red(' b ') + colors.gray('│') - , colors.gray('├───') + colors.gray('┼───┤') - , colors.gray('│') + (' c ') + colors.gray('│') + (' d ') + colors.gray('│') - , colors.gray('└───') + colors.gray('┴───┘') + colors.gray('┌───') + colors.gray('┬───┐'), + colors.gray('│') + colors.red(' a ') + colors.gray('│') + colors.red(' b ') + colors.gray('│'), + colors.gray('├───') + colors.gray('┼───┤'), + colors.gray('│') + ' c ' + colors.gray('│') + ' d ' + colors.gray('│'), + colors.gray('└───') + colors.gray('┴───┘'), ]; - return [makeTable,expected,'basic-usage-with-colors']; + return [makeTable, expected, 'basic-usage-with-colors']; }); - it('Basic Usage - disable colors - (used often in the examples and tests)', function (){ - function makeTable(){ + it('Basic Usage - disable colors - (used often in the examples and tests)', function() { + function makeTable() { // For most of these examples, and most of the unit tests we disable colors. // It makes unit tests easier to write/understand, and allows these pages to // display the examples as text instead of screen shots. var table = new Table({ - head: ['Rel', 'Change', 'By', 'When'] - , style: { - head: [] //disable colors in header cells - , border: [] //disable colors for the border - } - , colWidths: [6, 21, 25, 17] //set the widths of each column (optional) + head: ['Rel', 'Change', 'By', 'When'], + style: { + head: [], //disable colors in header cells + border: [], //disable colors for the border + }, + colWidths: [6, 21, 25, 17], //set the widths of each column (optional) }); table.push( - ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '7 minutes ago'] - , ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '8 minutes ago'] + ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '7 minutes ago'], + ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '8 minutes ago'] ); return table; } var expected = [ - '┌──────┬─────────────────────┬─────────────────────────┬─────────────────┐' - , '│ Rel │ Change │ By │ When │' - , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤' - , '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 7 minutes ago │' - , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤' - , '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 8 minutes ago │' - , '└──────┴─────────────────────┴─────────────────────────┴─────────────────┘' + '┌──────┬─────────────────────┬─────────────────────────┬─────────────────┐', + '│ Rel │ Change │ By │ When │', + '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤', + '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 7 minutes ago │', + '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤', + '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 8 minutes ago │', + '└──────┴─────────────────────┴─────────────────────────┴─────────────────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); it('Create vertical tables by adding objects a that specify key-value pairs', function() { - function makeTable(){ - var table = new Table({ style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); + function makeTable() { + var table = new Table({ + style: { 'padding-left': 0, 'padding-right': 0, head: [], border: [] }, + }); - table.push( - {'v0.1': 'Testing something cool'} - , {'v0.1': 'Testing something cool'} - ); + table.push({ 'v0.1': 'Testing something cool' }, { 'v0.1': 'Testing something cool' }); return table; } var expected = [ - '┌────┬──────────────────────┐' - , '│v0.1│Testing something cool│' - , '├────┼──────────────────────┤' - , '│v0.1│Testing something cool│' - , '└────┴──────────────────────┘' + '┌────┬──────────────────────┐', + '│v0.1│Testing something cool│', + '├────┼──────────────────────┤', + '│v0.1│Testing something cool│', + '└────┴──────────────────────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); it('Cross tables are similar to vertical tables, but include an empty string for the first header', function() { - function makeTable(){ - var table = new Table({ head: ["", "Header 1", "Header 2"], style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output + function makeTable() { + var table = new Table({ + head: ['', 'Header 1', 'Header 2'], + style: { 'padding-left': 0, 'padding-right': 0, head: [], border: [] }, + }); // clear styles to prevent color output table.push( - {"Header 3": ['v0.1', 'Testing something cool'] } - , {"Header 4": ['v0.1', 'Testing something cool'] } + { 'Header 3': ['v0.1', 'Testing something cool'] }, + { 'Header 4': ['v0.1', 'Testing something cool'] } ); return table; } var expected = [ - '┌────────┬────────┬──────────────────────┐' - , '│ │Header 1│Header 2 │' - , '├────────┼────────┼──────────────────────┤' - , '│Header 3│v0.1 │Testing something cool│' - , '├────────┼────────┼──────────────────────┤' - , '│Header 4│v0.1 │Testing something cool│' - , '└────────┴────────┴──────────────────────┘' + '┌────────┬────────┬──────────────────────┐', + '│ │Header 1│Header 2 │', + '├────────┼────────┼──────────────────────┤', + '│Header 3│v0.1 │Testing something cool│', + '├────────┼────────┼──────────────────────┤', + '│Header 4│v0.1 │Testing something cool│', + '└────────┴────────┴──────────────────────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('Stylize the table with custom border characters', function (){ - function makeTable(){ + it('Stylize the table with custom border characters', function() { + function makeTable() { var table = new Table({ chars: { - 'top': '═' - , 'top-mid': '╤' - , 'top-left': '╔' - , 'top-right': '╗' - , 'bottom': '═' - , 'bottom-mid': '╧' - , 'bottom-left': '╚' - , 'bottom-right': '╝' - , 'left': '║' - , 'left-mid': '╟' - , 'right': '║' - , 'right-mid': '╢' + top: '═', + 'top-mid': '╤', + 'top-left': '╔', + 'top-right': '╗', + bottom: '═', + 'bottom-mid': '╧', + 'bottom-left': '╚', + 'bottom-right': '╝', + left: '║', + 'left-mid': '╟', + right: '║', + 'right-mid': '╢', }, style: { - head: [] - , border: [] - } + head: [], + border: [], + }, }); - table.push( - ['foo', 'bar', 'baz'] - , ['frob', 'bar', 'quuz'] - ); + table.push(['foo', 'bar', 'baz'], ['frob', 'bar', 'quuz']); return table; } var expected = [ - '╔══════╤═════╤══════╗' - , '║ foo │ bar │ baz ║' - , '╟──────┼─────┼──────╢' - , '║ frob │ bar │ quuz ║' - , '╚══════╧═════╧══════╝' + '╔══════╤═════╤══════╗', + '║ foo │ bar │ baz ║', + '╟──────┼─────┼──────╢', + '║ frob │ bar │ quuz ║', + '╚══════╧═════╧══════╝', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('Use ansi colors (i.e. colors.js) to style text within the cells at will, even across multiple lines',function(){ - function makeTable(){ - var table = new Table({style:{border:[],header:[]}}); + it('Use ansi colors (i.e. colors.js) to style text within the cells at will, even across multiple lines', function() { + function makeTable() { + var table = new Table({ style: { border: [], header: [] } }); - table.push([ - colors.red('Hello\nhow\nare\nyou?'), - colors.blue('I\nam\nfine\nthanks!') - ]); + table.push([colors.red('Hello\nhow\nare\nyou?'), colors.blue('I\nam\nfine\nthanks!')]); return table; } var expected = [ - '┌───────┬─────────┐' - , '│ ' + colors.red('Hello') + ' │ ' + colors.blue('I') + ' │' - , '│ ' + colors.red('how') + ' │ ' + colors.blue('am') + ' │' - , '│ ' + colors.red('are') + ' │ ' + colors.blue('fine') + ' │' - , '│ ' + colors.red('you?') + ' │ ' + colors.blue('thanks!') + ' │' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│ ' + colors.red('Hello') + ' │ ' + colors.blue('I') + ' │', + '│ ' + colors.red('how') + ' │ ' + colors.blue('am') + ' │', + '│ ' + colors.red('are') + ' │ ' + colors.blue('fine') + ' │', + '│ ' + colors.red('you?') + ' │ ' + colors.blue('thanks!') + ' │', + '└───────┴─────────┘', ]; - return [makeTable,expected,'multi-line-colors']; + return [makeTable, expected, 'multi-line-colors']; }); - it('Set `wordWrap` to true to make lines of text wrap instead of being truncated',function(){ - function makeTable(){ + it('Set `wordWrap` to true to make lines of text wrap instead of being truncated', function() { + function makeTable() { var table = new Table({ - style:{border:[],header:[]}, - colWidths:[7,9], - wordWrap:true + style: { border: [], header: [] }, + colWidths: [7, 9], + wordWrap: true, }); - table.push([ - 'Hello how are you?', - 'I am fine thanks!' - ]); + table.push(['Hello how are you?', 'I am fine thanks!']); return table; } var expected = [ - '┌───────┬─────────┐' - , '│ Hello │ I am │' - , '│ how │ fine │' - , '│ are │ thanks! │' - , '│ you? │ │' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│ Hello │ I am │', + '│ how │ fine │', + '│ are │ thanks! │', + '│ you? │ │', + '└───────┴─────────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); }; @@ -219,4 +211,4 @@ module.exports = function(runTest) { , '│ │ … │ │ │' , '└──┴───┴──┴──┘' ]; - */ \ No newline at end of file + */ diff --git a/examples/col-and-row-span-examples.js b/examples/col-and-row-span-examples.js index 9cd6c1a..b9764f5 100644 --- a/examples/col-and-row-span-examples.js +++ b/examples/col-and-row-span-examples.js @@ -2,70 +2,61 @@ var Table = require('../src/table'); var colors = require('colors/safe'); module.exports = function(runTest) { - - function it(name,fn) { + function it(name, fn) { var result = fn(); - runTest(name,result[0],result[1],result[2]); + runTest(name, result[0], result[1], result[2]); } - it('use colSpan to span columns - (colSpan above normal cell)',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('use colSpan to span columns - (colSpan above normal cell)', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); - table.push( - [{colSpan:2,content:'greetings'}], - [{colSpan:2,content:'greetings'}], - ['hello','howdy'] - ); + table.push([{ colSpan: 2, content: 'greetings' }], [{ colSpan: 2, content: 'greetings' }], ['hello', 'howdy']); return table; } var expected = [ - '┌───────────────┐' - , '│ greetings │' - , '├───────────────┤' - , '│ greetings │' - , '├───────┬───────┤' - , '│ hello │ howdy │' - , '└───────┴───────┘' + '┌───────────────┐', + '│ greetings │', + '├───────────────┤', + '│ greetings │', + '├───────┬───────┤', + '│ hello │ howdy │', + '└───────┴───────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('use colSpan to span columns - (colSpan below normal cell)',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('use colSpan to span columns - (colSpan below normal cell)', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); - table.push( - ['hello','howdy'], - [{colSpan:2,content:'greetings'}], - [{colSpan:2,content:'greetings'}] - ); + table.push(['hello', 'howdy'], [{ colSpan: 2, content: 'greetings' }], [{ colSpan: 2, content: 'greetings' }]); return table; } var expected = [ - '┌───────┬───────┐' - , '│ hello │ howdy │' - , '├───────┴───────┤' - , '│ greetings │' - , '├───────────────┤' - , '│ greetings │' - , '└───────────────┘' + '┌───────┬───────┐', + '│ hello │ howdy │', + '├───────┴───────┤', + '│ greetings │', + '├───────────────┤', + '│ greetings │', + '└───────────────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('use rowSpan to span rows - (rowSpan on the left side)',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('use rowSpan to span rows - (rowSpan on the left side)', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); table.push( - [{rowSpan:2,content:'greetings'},{rowSpan:2,content:'greetings',vAlign:'center'},'hello'], + [{ rowSpan: 2, content: 'greetings' }, { rowSpan: 2, content: 'greetings', vAlign: 'center' }, 'hello'], ['howdy'] ); @@ -73,23 +64,22 @@ module.exports = function(runTest) { } var expected = [ - '┌───────────┬───────────┬───────┐' - , '│ greetings │ │ hello │' - , '│ │ greetings ├───────┤' - , '│ │ │ howdy │' - , '└───────────┴───────────┴───────┘' + '┌───────────┬───────────┬───────┐', + '│ greetings │ │ hello │', + '│ │ greetings ├───────┤', + '│ │ │ howdy │', + '└───────────┴───────────┴───────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - - it('use rowSpan to span rows - (rowSpan on the right side)',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('use rowSpan to span rows - (rowSpan on the right side)', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); table.push( - ['hello',{rowSpan:2,content:'greetings'},{rowSpan:2,content:'greetings',vAlign:'bottom'}], + ['hello', { rowSpan: 2, content: 'greetings' }, { rowSpan: 2, content: 'greetings', vAlign: 'bottom' }], ['howdy'] ); @@ -97,48 +87,48 @@ module.exports = function(runTest) { } var expected = [ - '┌───────┬───────────┬───────────┐' - , '│ hello │ greetings │ │' - , '├───────┤ │ │' - , '│ howdy │ │ greetings │' - , '└───────┴───────────┴───────────┘' + '┌───────┬───────────┬───────────┐', + '│ hello │ greetings │ │', + '├───────┤ │ │', + '│ howdy │ │ greetings │', + '└───────┴───────────┴───────────┘', ]; - return[makeTable,expected]; + return [makeTable, expected]; }); - it('mix rowSpan and colSpan together for complex table layouts',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('mix rowSpan and colSpan together for complex table layouts', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); table.push( - [{content:'hello',colSpan:2},{rowSpan:2, colSpan:2,content:'sup'},{rowSpan:3,content:'hi'}], - [{content:'howdy',colSpan:2}], - ['o','k','',''] + [{ content: 'hello', colSpan: 2 }, { rowSpan: 2, colSpan: 2, content: 'sup' }, { rowSpan: 3, content: 'hi' }], + [{ content: 'howdy', colSpan: 2 }], + ['o', 'k', '', ''] ); return table; } var expected = [ - '┌───────┬─────┬────┐' - , '│ hello │ sup │ hi │' - , '├───────┤ │ │' - , '│ howdy │ │ │' - , '├───┬───┼──┬──┤ │' - , '│ o │ k │ │ │ │' - , '└───┴───┴──┴──┴────┘' + '┌───────┬─────┬────┐', + '│ hello │ sup │ hi │', + '├───────┤ │ │', + '│ howdy │ │ │', + '├───┬───┼──┬──┤ │', + '│ o │ k │ │ │ │', + '└───┴───┴──┴──┴────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('multi-line content will flow across rows in rowSpan cells',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('multi-line content will flow across rows in rowSpan cells', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); table.push( - ['hello',{rowSpan:2,content:'greetings\nfriends'},{rowSpan:2,content:'greetings\nfriends'}], + ['hello', { rowSpan: 2, content: 'greetings\nfriends' }, { rowSpan: 2, content: 'greetings\nfriends' }], ['howdy'] ); @@ -146,201 +136,164 @@ module.exports = function(runTest) { } var expected = [ - '┌───────┬───────────┬───────────┐' - , '│ hello │ greetings │ greetings │' - , '├───────┤ friends │ friends │' - , '│ howdy │ │ │' - , '└───────┴───────────┴───────────┘' + '┌───────┬───────────┬───────────┐', + '│ hello │ greetings │ greetings │', + '├───────┤ friends │ friends │', + '│ howdy │ │ │', + '└───────┴───────────┴───────────┘', ]; return [makeTable, expected]; }); - it('multi-line content will flow across rows in rowSpan cells - (complex layout)',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('multi-line content will flow across rows in rowSpan cells - (complex layout)', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); table.push( - [{content:'hello',colSpan:2},{rowSpan:2, colSpan:2,content:'sup\nman\nhey'},{rowSpan:3,content:'hi\nyo'}], - [{content:'howdy',colSpan:2}], - ['o','k','',''] + [ + { content: 'hello', colSpan: 2 }, + { rowSpan: 2, colSpan: 2, content: 'sup\nman\nhey' }, + { rowSpan: 3, content: 'hi\nyo' }, + ], + [{ content: 'howdy', colSpan: 2 }], + ['o', 'k', '', ''] ); return table; } var expected = [ - '┌───────┬─────┬────┐' - , '│ hello │ sup │ hi │' - , '├───────┤ man │ yo │' - , '│ howdy │ hey │ │' - , '├───┬───┼──┬──┤ │' - , '│ o │ k │ │ │ │' - , '└───┴───┴──┴──┴────┘' + '┌───────┬─────┬────┐', + '│ hello │ sup │ hi │', + '├───────┤ man │ yo │', + '│ howdy │ hey │ │', + '├───┬───┼──┬──┤ │', + '│ o │ k │ │ │ │', + '└───┴───┴──┴──┴────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('rowSpan cells can have a staggered layout',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('rowSpan cells can have a staggered layout', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); - table.push( - [{content:'a',rowSpan:2},'b'], - [{content:'c',rowSpan:2}], - ['d'] - ); + table.push([{ content: 'a', rowSpan: 2 }, 'b'], [{ content: 'c', rowSpan: 2 }], ['d']); return table; } - var expected = [ - '┌───┬───┐' - , '│ a │ b │' - , '│ ├───┤' - , '│ │ c │' - , '├───┤ │' - , '│ d │ │' - , '└───┴───┘' - ]; + var expected = ['┌───┬───┐', '│ a │ b │', '│ ├───┤', '│ │ c │', '├───┤ │', '│ d │ │', '└───┴───┘']; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('the layout manager automatically create empty cells to fill in the table',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('the layout manager automatically create empty cells to fill in the table', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); //notice we only create 3 cells here, but the table ends up having 6. - table.push( - [{content:'a',rowSpan:3,colSpan:2},'b'], - [], - [{content:'c',rowSpan:2,colSpan:2}], - [] - ); + table.push([{ content: 'a', rowSpan: 3, colSpan: 2 }, 'b'], [], [{ content: 'c', rowSpan: 2, colSpan: 2 }], []); return table; } var expected = [ - '┌───┬───┬──┐' - , '│ a │ b │ │' // top-right and bottom-left cells are automatically created to fill the empty space - , '│ ├───┤ │' - , '│ │ │ │' - , '│ ├───┴──┤' - , '│ │ c │' - , '├───┤ │' - , '│ │ │' - , '└───┴──────┘' + '┌───┬───┬──┐', + '│ a │ b │ │', // top-right and bottom-left cells are automatically created to fill the empty space + '│ ├───┤ │', + '│ │ │ │', + '│ ├───┴──┤', + '│ │ c │', + '├───┤ │', + '│ │ │', + '└───┴──────┘', ]; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('use table `rowHeights` option to fix row height. The truncation symbol will be shown on the last line.',function(){ - function makeTable(){ - var table = new Table({rowHeights:[2],style:{head:[],border:[]}}); + it('use table `rowHeights` option to fix row height. The truncation symbol will be shown on the last line.', function() { + function makeTable() { + var table = new Table({ + rowHeights: [2], + style: { head: [], border: [] }, + }); table.push(['hello\nhi\nsup']); return table; } - var expected = [ - '┌───────┐' - , '│ hello │' - , '│ hi… │' - , '└───────┘' - ]; + var expected = ['┌───────┐', '│ hello │', '│ hi… │', '└───────┘']; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('if `colWidths` is not specified, the layout manager will automatically widen rows to fit the content',function(){ - function makeTable(){ - var table = new Table({style:{head:[],border:[]}}); + it('if `colWidths` is not specified, the layout manager will automatically widen rows to fit the content', function() { + function makeTable() { + var table = new Table({ style: { head: [], border: [] } }); - table.push( - [{colSpan:2,content:'hello there'}], - ['hi', 'hi'] - ); + table.push([{ colSpan: 2, content: 'hello there' }], ['hi', 'hi']); return table; } - var expected = [ - '┌─────────────┐' - , '│ hello there │' - , '├──────┬──────┤' - , '│ hi │ hi │' - , '└──────┴──────┘' - ]; + var expected = ['┌─────────────┐', '│ hello there │', '├──────┬──────┤', '│ hi │ hi │', '└──────┴──────┘']; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('you can specify a column width for only the first row, other rows will be automatically widened to fit content',function(){ - function makeTable(){ - var table = new Table({colWidths:[4],style:{head:[],border:[]}}); + it('you can specify a column width for only the first row, other rows will be automatically widened to fit content', function() { + function makeTable() { + var table = new Table({ + colWidths: [4], + style: { head: [], border: [] }, + }); - table.push( - [{colSpan:2,content:'hello there'}], - ['hi',{hAlign:'center',content:'hi'}] - ); + table.push([{ colSpan: 2, content: 'hello there' }], ['hi', { hAlign: 'center', content: 'hi' }]); return table; } - var expected = [ - '┌─────────────┐' - , '│ hello there │' - , '├────┬────────┤' - , '│ hi │ hi │' - , '└────┴────────┘' - ]; + var expected = ['┌─────────────┐', '│ hello there │', '├────┬────────┤', '│ hi │ hi │', '└────┴────────┘']; return [makeTable, expected]; }); - it('a column with a null column width will be automatically widened to fit content',function(){ - function makeTable(){ - var table = new Table({colWidths:[null, 4],style:{head:[],border:[]}}); + it('a column with a null column width will be automatically widened to fit content', function() { + function makeTable() { + var table = new Table({ + colWidths: [null, 4], + style: { head: [], border: [] }, + }); - table.push( - [{colSpan:2,content:'hello there'}], - [{hAlign:'right',content:'hi'}, 'hi'] - ); + table.push([{ colSpan: 2, content: 'hello there' }], [{ hAlign: 'right', content: 'hi' }, 'hi']); return table; } - var expected = [ - '┌─────────────┐' - , '│ hello there │' - , '├────────┬────┤' - , '│ hi │ hi │' - , '└────────┴────┘' - ]; + var expected = ['┌─────────────┐', '│ hello there │', '├────────┬────┤', '│ hi │ hi │', '└────────┴────┘']; - return [makeTable,expected]; + return [makeTable, expected]; }); - it('feel free to use colors in your content strings, column widths will be calculated correctly',function(){ - function makeTable(){ - var table = new Table({colWidths:[5],style:{head:[],border:[]}}); + it('feel free to use colors in your content strings, column widths will be calculated correctly', function() { + function makeTable() { + var table = new Table({ + colWidths: [5], + style: { head: [], border: [] }, + }); table.push([colors.red('hello')]); return table; } - var expected = [ - '┌─────┐' - , '│ ' + colors.red('he') + '… │' - , '└─────┘' - ]; + var expected = ['┌─────┐', '│ ' + colors.red('he') + '… │', '└─────┘']; - return [makeTable,expected,'truncation-with-colors']; + return [makeTable, expected, 'truncation-with-colors']; }); }; @@ -355,4 +308,4 @@ module.exports = function(runTest) { , '│ │ … │ │ │' , '└──┴───┴──┴──┘' ]; - */ \ No newline at end of file + */ diff --git a/lib/print-example.js b/lib/print-example.js index 1bbb38f..614900f 100644 --- a/lib/print-example.js +++ b/lib/print-example.js @@ -5,52 +5,61 @@ var colors = require('colors/safe'); var fs = require('fs'); var git = require('git-rev'); -function logExample(fn){ - runPrintingExample(fn, - function logName(name){ +function logExample(fn) { + runPrintingExample( + fn, + function logName(name) { console.log(colors.gray('========= ') + name + colors.gray(' ================')); }, - console.log, //logTable - console.log, //logCode - console.log, //logSeparator - identity //screenShot - ) + console.log, //logTable + console.log, //logCode + console.log, //logSeparator + identity //screenShot + ); } -function mdExample(fn,file,cb){ - git.long(function(commitHash){ +function mdExample(fn, file, cb) { + git.long(function(commitHash) { var buffer = []; - runPrintingExample(fn, - function logName(name){ + runPrintingExample( + fn, + function logName(name) { buffer.push('##### ' + name); }, - function logTable(table){ + function logTable(table) { //md files won't render color strings properly. table = stripColors(table); // indent table so is displayed preformatted text - table = ' ' + (table.split('\n').join('\n ')); + table = ' ' + table.split('\n').join('\n '); buffer.push(table); }, - function logCode(code){ + function logCode(code) { buffer.push('```javascript'); buffer.push(stripColors(code)); buffer.push('```'); }, - function logSeparator(sep){ + function logSeparator(sep) { buffer.push(stripColors(sep)); }, - function logScreenShot(image){ - buffer.push('![table image](https://cdn.rawgit.com/jamestalmage/cli-table2/' - + commitHash + '/examples/screenshots/' + image + '.png)'); + function logScreenShot(image) { + buffer.push( + '![table image](https://cdn.rawgit.com/jamestalmage/cli-table2/' + + commitHash + + '/examples/screenshots/' + + image + + '.png)' + ); } ); - fs.writeFileSync(file,buffer.join('\n')); + fs.writeFileSync(file, buffer.join('\n')); - if(cb){cb();} + if (cb) { + cb(); + } }); } @@ -59,15 +68,15 @@ function mdExample(fn,file,cb){ * @param name of the test suite, used in the mocha.describe call. * @param fn a function which creates the test suite. */ -function runTest(name,fn){ - function testExample(name,fn,expected){ - it(name,function(){ +function runTest(name, fn) { + function testExample(name, fn, expected) { + it(name, function() { expect(fn().toString()).toEqual(expected.join('\n')); }); } - describe(name,function () { - fn(testExample,identity); + describe(name, function() { + fn(testExample, identity); }); } @@ -80,8 +89,7 @@ function runTest(name,fn){ * @param logSeparator - callback to print extra whitespace between demos. * @param logScreenShot - write out a link to the screenShot image. */ -function runPrintingExample(fn,logName,logTable,logCode,logSeparator,logScreenShot){ - +function runPrintingExample(fn, logName, logTable, logCode, logSeparator, logScreenShot) { /** * Called by every test/demo * @param name - the name of this test. @@ -89,14 +97,17 @@ function runPrintingExample(fn,logName,logTable,logCode,logSeparator,logScreenSh * @param expected - The expected result. * @param screenshot - If present, there is an image containing a screenshot of the output */ - function printExample(name,makeTable,expected,screenshot){ - var code = makeTable.toString().split('\n').slice(1,-2).join('\n'); + function printExample(name, makeTable, expected, screenshot) { + var code = makeTable + .toString() + .split('\n') + .slice(1, -2) + .join('\n'); logName(name); - if(screenshot && logScreenShot){ + if (screenshot && logScreenShot) { logScreenShot(screenshot); - } - else { + } else { logTable(makeTable().toString()); } logCode(code); @@ -107,17 +118,17 @@ function runPrintingExample(fn,logName,logTable,logCode,logSeparator,logScreenSh } // removes all the color characters from a string -function stripColors(str){ - return str.split( /\u001b\[(?:\d*;){0,5}\d*m/g).join(''); +function stripColors(str) { + return str.split(/\u001b\[(?:\d*;){0,5}\d*m/g).join(''); } // returns the first arg - used as snapshot function -function identity(str){ +function identity(str) { return str; } module.exports = { - mdExample:mdExample, - logExample:logExample, - runTest:runTest + mdExample: mdExample, + logExample: logExample, + runTest: runTest, }; diff --git a/package.json b/package.json index 9eb0354..7e04788 100644 --- a/package.json +++ b/package.json @@ -18,15 +18,19 @@ "devDependencies": { "ansi-256-colors": "^1.1.0", "cli-table": "^0.3.1", + "eslint-config-prettier": "^2.9.0", + "eslint-plugin-prettier": "^2.6.0", "git-rev": "^0.2.1", "gulp": "^3.9.0", "jest": "^23.1.0", - "jest-runner-eslint": "^0.6.0" + "jest-runner-eslint": "^0.6.0", + "prettier": "1.13.5" }, "optionalDependencies": { "colors": "^1.1.2" }, "scripts": { + "prettier": "prettier --write '{examples,lib,src,test}/**/*.js'", "test": "jest --color", "test:watch": "jest --color --watchAll --notify" }, @@ -74,5 +78,11 @@ ] } ] + }, + "prettier": { + "printWidth": 120, + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "es5" } } diff --git a/src/cell.js b/src/cell.js index 1360b95..bc0cc41 100644 --- a/src/cell.js +++ b/src/cell.js @@ -8,13 +8,13 @@ var utils = require('./utils'); * @param options * @constructor */ -function Cell(options){ +function Cell(options) { this.setOptions(options); } -Cell.prototype.setOptions = function(options){ - if(['boolean', 'number', 'string'].indexOf(kindOf(options)) !== -1){ - options = {content:''+options}; +Cell.prototype.setOptions = function(options) { + if (['boolean', 'number', 'string'].indexOf(kindOf(options)) !== -1) { + options = { content: '' + options }; } options = options || {}; this.options = options; @@ -24,25 +24,25 @@ Cell.prototype.setOptions = function(options){ } else if (!content) { this.content = ''; } else { - throw new Error('Content needs to be a primitive, got: ' + (typeof content)); + throw new Error('Content needs to be a primitive, got: ' + typeof content); } this.colSpan = options.colSpan || 1; this.rowSpan = options.rowSpan || 1; }; -Cell.prototype.mergeTableOptions = function(tableOptions,cells){ +Cell.prototype.mergeTableOptions = function(tableOptions, cells) { this.cells = cells; var optionsChars = this.options.chars || {}; var tableChars = tableOptions.chars; - var chars = this.chars = {}; - CHAR_NAMES.forEach(function(name){ - setOption(optionsChars,tableChars,name,chars); + var chars = (this.chars = {}); + CHAR_NAMES.forEach(function(name) { + setOption(optionsChars, tableChars, name, chars); }); this.truncate = this.options.truncate || tableOptions.truncate; - var style = this.options.style = this.options.style || {}; + var style = (this.options.style = this.options.style || {}); var tableStyle = tableOptions.style; setOption(style, tableStyle, 'padding-left', this); setOption(style, tableStyle, 'padding-right', this); @@ -50,18 +50,17 @@ Cell.prototype.mergeTableOptions = function(tableOptions,cells){ this.border = style.border || tableStyle.border; var fixedWidth = tableOptions.colWidths[this.x]; - if(tableOptions.wordWrap && fixedWidth){ + if (tableOptions.wordWrap && fixedWidth) { fixedWidth -= this.paddingLeft + this.paddingRight; - if(this.colSpan){ + if (this.colSpan) { var i = 1; - while(i= (padTop + this.lines.length))){ - return this.drawEmpty(this.drawRight,spanningCell); + if (lineNum < padTop || lineNum >= padTop + this.lines.length) { + return this.drawEmpty(this.drawRight, spanningCell); } - var forceTruncation = (this.lines.length > this.height) && (lineNum + 1 >= this.height); - return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation,spanningCell); + var forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; + return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); }; /** @@ -136,48 +135,46 @@ Cell.prototype.draw = function(lineNum,spanningCell){ * @param drawRight - true if this method should render the right edge of the cell. * @returns {String} */ -Cell.prototype.drawTop = function(drawRight){ +Cell.prototype.drawTop = function(drawRight) { var content = []; - if(this.cells){ //TODO: cells should always exist - some tests don't fill it in though - this.widths.forEach(function(width,index){ + if (this.cells) { + //TODO: cells should always exist - some tests don't fill it in though + this.widths.forEach(function(width, index) { content.push(this._topLeftChar(index)); - content.push( - utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'],width) - ); - },this); - } - else { + content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width)); + }, this); + } else { content.push(this._topLeftChar(0)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'],this.width)); + content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width)); } - if(drawRight){ + if (drawRight) { content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); } - return this.wrapWithStyleColors('border',content.join('')); + return this.wrapWithStyleColors('border', content.join('')); }; -Cell.prototype._topLeftChar = function(offset){ - var x = this.x+offset; +Cell.prototype._topLeftChar = function(offset) { + var x = this.x + offset; var leftChar; - if(this.y == 0){ - leftChar = x == 0 ? 'topLeft' : (offset == 0 ? 'topMid' : 'top'); - } else { - if(x == 0){ + if (this.y == 0) { + leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top'; + } else { + if (x == 0) { leftChar = 'leftMid'; - } - else { + } else { leftChar = offset == 0 ? 'midMid' : 'bottomMid'; - if(this.cells){ //TODO: cells should always exist - some tests don't fill it in though - var spanAbove = this.cells[this.y-1][x] instanceof Cell.ColSpanCell; - if(spanAbove){ + if (this.cells) { + //TODO: cells should always exist - some tests don't fill it in though + var spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell; + if (spanAbove) { leftChar = offset == 0 ? 'topMid' : 'mid'; } - if(offset == 0){ + if (offset == 0) { var i = 1; - while(this.cells[this.y][x-i] instanceof Cell.ColSpanCell){ + while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) { i++; } - if(this.cells[this.y][x-i] instanceof Cell.RowSpanCell){ + if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) { leftChar = 'leftMid'; } } @@ -187,19 +184,18 @@ Cell.prototype._topLeftChar = function(offset){ return this.chars[leftChar]; }; -Cell.prototype.wrapWithStyleColors = function(styleProperty,content){ - if(this[styleProperty] && this[styleProperty].length){ +Cell.prototype.wrapWithStyleColors = function(styleProperty, content) { + if (this[styleProperty] && this[styleProperty].length) { try { var colors = require('colors/safe'); - for(var i = this[styleProperty].length - 1; i >= 0; i--){ + for (var i = this[styleProperty].length - 1; i >= 0; i--) { colors = colors[this[styleProperty][i]]; } return colors(content); } catch (e) { return content; } - } - else { + } else { return content; } }; @@ -215,34 +211,34 @@ Cell.prototype.wrapWithStyleColors = function(styleProperty,content){ * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. * @returns {String} */ -Cell.prototype.drawLine = function(lineNum,drawRight,forceTruncationSymbol,spanningCell){ +Cell.prototype.drawLine = function(lineNum, drawRight, forceTruncationSymbol, spanningCell) { var left = this.chars[this.x == 0 ? 'left' : 'middle']; - if(this.x && spanningCell && this.cells){ - var cellLeft = this.cells[this.y+spanningCell][this.x-1]; - while(cellLeft instanceof ColSpanCell){ - cellLeft = this.cells[cellLeft.y][cellLeft.x-1]; + if (this.x && spanningCell && this.cells) { + var cellLeft = this.cells[this.y + spanningCell][this.x - 1]; + while (cellLeft instanceof ColSpanCell) { + cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; } - if(!(cellLeft instanceof RowSpanCell)){ + if (!(cellLeft instanceof RowSpanCell)) { left = this.chars['rightMid']; } } var leftPadding = utils.repeat(' ', this.paddingLeft); - var right = (drawRight ? this.chars['right'] : ''); + var right = drawRight ? this.chars['right'] : ''; var rightPadding = utils.repeat(' ', this.paddingRight); var line = this.lines[lineNum]; var len = this.width - (this.paddingLeft + this.paddingRight); - if(forceTruncationSymbol) line += this.truncate || '…'; - var content = utils.truncate(line,len,this.truncate); + if (forceTruncationSymbol) line += this.truncate || '…'; + var content = utils.truncate(line, len, this.truncate); content = utils.pad(content, len, ' ', this.hAlign); content = leftPadding + content + rightPadding; - return this.stylizeLine(left,content,right); + return this.stylizeLine(left, content, right); }; -Cell.prototype.stylizeLine = function(left,content,right){ - left = this.wrapWithStyleColors('border',left); - right = this.wrapWithStyleColors('border',right); - if(this.y === 0){ - content = this.wrapWithStyleColors('head',content); +Cell.prototype.stylizeLine = function(left, content, right) { + left = this.wrapWithStyleColors('border', left); + right = this.wrapWithStyleColors('border', right); + if (this.y === 0) { + content = this.wrapWithStyleColors('head', content); } return left + content + right; }; @@ -252,11 +248,11 @@ Cell.prototype.stylizeLine = function(left,content,right){ * @param drawRight - true if this method should render the right edge of the cell. * @returns {String} */ -Cell.prototype.drawBottom = function(drawRight){ +Cell.prototype.drawBottom = function(drawRight) { var left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid']; - var content = utils.repeat(this.chars.bottom,this.width); + var content = utils.repeat(this.chars.bottom, this.width); var right = drawRight ? this.chars['bottomRight'] : ''; - return this.wrapWithStyleColors('border',left + content + right); + return this.wrapWithStyleColors('border', left + content + right); }; /** @@ -265,20 +261,20 @@ Cell.prototype.drawBottom = function(drawRight){ * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. * @returns {String} */ -Cell.prototype.drawEmpty = function(drawRight,spanningCell){ +Cell.prototype.drawEmpty = function(drawRight, spanningCell) { var left = this.chars[this.x == 0 ? 'left' : 'middle']; - if(this.x && spanningCell && this.cells){ - var cellLeft = this.cells[this.y+spanningCell][this.x-1]; - while(cellLeft instanceof ColSpanCell){ - cellLeft = this.cells[cellLeft.y][cellLeft.x-1]; + if (this.x && spanningCell && this.cells) { + var cellLeft = this.cells[this.y + spanningCell][this.x - 1]; + while (cellLeft instanceof ColSpanCell) { + cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; } - if(!(cellLeft instanceof RowSpanCell)){ + if (!(cellLeft instanceof RowSpanCell)) { left = this.chars['rightMid']; } } - var right = (drawRight ? this.chars['right'] : ''); - var content = utils.repeat(' ',this.width); - return this.stylizeLine(left , content , right); + var right = drawRight ? this.chars['right'] : ''; + var content = utils.repeat(' ', this.width); + return this.stylizeLine(left, content, right); }; /** @@ -286,14 +282,13 @@ Cell.prototype.drawEmpty = function(drawRight,spanningCell){ * Used as a placeholder in column spanning. * @constructor */ -function ColSpanCell(){} +function ColSpanCell() {} -ColSpanCell.prototype.draw = function(){ +ColSpanCell.prototype.draw = function() { return ''; }; -ColSpanCell.prototype.init = function(/* tableOptions */){}; - +ColSpanCell.prototype.init = function(/* tableOptions */) {}; /** * A placeholder Cell for a Cell that spans multiple rows. @@ -301,70 +296,69 @@ ColSpanCell.prototype.init = function(/* tableOptions */){}; * @param originalCell * @constructor */ -function RowSpanCell(originalCell){ +function RowSpanCell(originalCell) { this.originalCell = originalCell; } -RowSpanCell.prototype.init = function(tableOptions){ +RowSpanCell.prototype.init = function(tableOptions) { var y = this.y; var originalY = this.originalCell.y; this.cellOffset = y - originalY; - this.offset = findDimension(tableOptions.rowHeights,originalY,this.cellOffset); + this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); }; -RowSpanCell.prototype.draw = function(lineNum){ - if(lineNum == 'top'){ - return this.originalCell.draw(this.offset,this.cellOffset); +RowSpanCell.prototype.draw = function(lineNum) { + if (lineNum == 'top') { + return this.originalCell.draw(this.offset, this.cellOffset); } - if(lineNum == 'bottom'){ + if (lineNum == 'bottom') { return this.originalCell.draw('bottom'); } return this.originalCell.draw(this.offset + 1 + lineNum); }; -ColSpanCell.prototype.mergeTableOptions = -RowSpanCell.prototype.mergeTableOptions = function(){}; +ColSpanCell.prototype.mergeTableOptions = RowSpanCell.prototype.mergeTableOptions = function() {}; // HELPER FUNCTIONS -function setOption(objA,objB,nameB,targetObj){ +function setOption(objA, objB, nameB, targetObj) { var nameA = nameB.split('-'); - if(nameA.length > 1) { + if (nameA.length > 1) { nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1); nameA = nameA.join(''); targetObj[nameA] = objA[nameA] || objA[nameB] || objB[nameA] || objB[nameB]; - } - else { + } else { targetObj[nameB] = objA[nameB] || objB[nameB]; } } -function findDimension(dimensionTable, startingIndex, span){ +function findDimension(dimensionTable, startingIndex, span) { var ret = dimensionTable[startingIndex]; - for(var i = 1; i < span; i++){ + for (var i = 1; i < span; i++) { ret += 1 + dimensionTable[startingIndex + i]; } return ret; } -function sumPlusOne(a,b){ - return a+b+1; +function sumPlusOne(a, b) { + return a + b + 1; } -var CHAR_NAMES = [ 'top' - , 'top-mid' - , 'top-left' - , 'top-right' - , 'bottom' - , 'bottom-mid' - , 'bottom-left' - , 'bottom-right' - , 'left' - , 'left-mid' - , 'mid' - , 'mid-mid' - , 'right' - , 'right-mid' - , 'middle' +var CHAR_NAMES = [ + 'top', + 'top-mid', + 'top-left', + 'top-right', + 'bottom', + 'bottom-mid', + 'bottom-left', + 'bottom-right', + 'left', + 'left-mid', + 'mid', + 'mid-mid', + 'right', + 'right-mid', + 'middle', ]; module.exports = Cell; module.exports.ColSpanCell = ColSpanCell; diff --git a/src/layout-manager.js b/src/layout-manager.js index 098df3a..44f71df 100644 --- a/src/layout-manager.js +++ b/src/layout-manager.js @@ -4,18 +4,18 @@ var Cell = require('./cell'); var RowSpanCell = Cell.RowSpanCell; var ColSpanCell = Cell.ColSpanCell; -(function(){ - function layoutTable(table){ - table.forEach(function(row,rowIndex){ - row.forEach(function(cell,columnIndex){ +(function() { + function layoutTable(table) { + table.forEach(function(row, rowIndex) { + row.forEach(function(cell, columnIndex) { cell.y = rowIndex; cell.x = columnIndex; - for(var y = rowIndex; y >= 0; y--){ + for (var y = rowIndex; y >= 0; y--) { var row2 = table[y]; - var xMax = (y === rowIndex) ? columnIndex : row2.length; - for(var x = 0; x < xMax; x++){ + var xMax = y === rowIndex ? columnIndex : row2.length; + for (var x = 0; x < xMax; x++) { var cell2 = row2[x]; - while(cellsConflict(cell,cell2)){ + while (cellsConflict(cell, cell2)) { cell.x++; } } @@ -26,41 +26,41 @@ var ColSpanCell = Cell.ColSpanCell; function maxWidth(table) { var mw = 0; - table.forEach(function (row) { - row.forEach(function (cell) { - mw = Math.max(mw,cell.x + (cell.colSpan || 1)); + table.forEach(function(row) { + row.forEach(function(cell) { + mw = Math.max(mw, cell.x + (cell.colSpan || 1)); }); }); return mw; } - function maxHeight(table){ + function maxHeight(table) { return table.length; } - function cellsConflict(cell1,cell2){ + function cellsConflict(cell1, cell2) { var yMin1 = cell1.y; var yMax1 = cell1.y - 1 + (cell1.rowSpan || 1); var yMin2 = cell2.y; var yMax2 = cell2.y - 1 + (cell2.rowSpan || 1); var yConflict = !(yMin1 > yMax2 || yMin2 > yMax1); - var xMin1= cell1.x; + var xMin1 = cell1.x; var xMax1 = cell1.x - 1 + (cell1.colSpan || 1); - var xMin2= cell2.x; + var xMin2 = cell2.x; var xMax2 = cell2.x - 1 + (cell2.colSpan || 1); var xConflict = !(xMin1 > xMax2 || xMin2 > xMax1); return yConflict && xConflict; } - function conflictExists(rows,x,y){ - var i_max = Math.min(rows.length-1,y); - var cell = {x:x,y:y}; - for(var i = 0; i <= i_max; i++){ + function conflictExists(rows, x, y) { + var i_max = Math.min(rows.length - 1, y); + var cell = { x: x, y: y }; + for (var i = 0; i <= i_max; i++) { var row = rows[i]; - for(var j = 0; j < row.length; j++){ - if(cellsConflict(cell,row[j])){ + for (var j = 0; j < row.length; j++) { + if (cellsConflict(cell, row[j])) { return true; } } @@ -68,31 +68,31 @@ var ColSpanCell = Cell.ColSpanCell; return false; } - function allBlank(rows,y,xMin,xMax){ - for(var x = xMin; x < xMax; x++){ - if(conflictExists(rows,x,y)){ + function allBlank(rows, y, xMin, xMax) { + for (var x = xMin; x < xMax; x++) { + if (conflictExists(rows, x, y)) { return false; } } return true; } - function addRowSpanCells(table){ - table.forEach(function(row,rowIndex){ - row.forEach(function(cell){ - for(var i = 1; i < cell.rowSpan; i++){ + function addRowSpanCells(table) { + table.forEach(function(row, rowIndex) { + row.forEach(function(cell) { + for (var i = 1; i < cell.rowSpan; i++) { var rowSpanCell = new RowSpanCell(cell); rowSpanCell.x = cell.x; rowSpanCell.y = cell.y + i; rowSpanCell.colSpan = cell.colSpan; - insertCell(rowSpanCell,table[rowIndex+i]); + insertCell(rowSpanCell, table[rowIndex + i]); } }); }); } - function addColSpanCells(cellRows){ - for(var rowIndex = cellRows.length-1; rowIndex >= 0; rowIndex--) { + function addColSpanCells(cellRows) { + for (var rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) { var cellColumns = cellRows[rowIndex]; for (var columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) { var cell = cellColumns[columnIndex]; @@ -106,28 +106,28 @@ var ColSpanCell = Cell.ColSpanCell; } } - function insertCell(cell,row){ + function insertCell(cell, row) { var x = 0; - while(x < row.length && (row[x].x < cell.x)) { + while (x < row.length && row[x].x < cell.x) { x++; } - row.splice(x,0,cell); + row.splice(x, 0, cell); } - function fillInTable(table){ + function fillInTable(table) { var h_max = maxHeight(table); var w_max = maxWidth(table); - for(var y = 0; y < h_max; y++){ - for(var x = 0; x < w_max; x++){ - if(!conflictExists(table,x,y)){ - var opts = {x:x,y:y,colSpan:1,rowSpan:1}; + for (var y = 0; y < h_max; y++) { + for (var x = 0; x < w_max; x++) { + if (!conflictExists(table, x, y)) { + var opts = { x: x, y: y, colSpan: 1, rowSpan: 1 }; x++; - while(x < w_max && !conflictExists(table,x,y)){ + while (x < w_max && !conflictExists(table, x, y)) { opts.colSpan++; x++; } var y2 = y + 1; - while(y2 < h_max && allBlank(table,y2,opts.x,opts.x+opts.colSpan)){ + while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) { opts.rowSpan++; y2++; } @@ -135,32 +135,31 @@ var ColSpanCell = Cell.ColSpanCell; var cell = new Cell(opts); cell.x = opts.x; cell.y = opts.y; - insertCell(cell,table[y]); + insertCell(cell, table[y]); } } } } - function generateCells(rows){ - return rows.map(function(row){ - if(kindOf(row) !== 'array'){ + function generateCells(rows) { + return rows.map(function(row) { + if (kindOf(row) !== 'array') { var key = Object.keys(row)[0]; row = row[key]; - if(kindOf(row) === 'array'){ + if (kindOf(row) === 'array') { row = row.slice(); row.unshift(key); - } - else { - row = [key,row]; + } else { + row = [key, row]; } } - return row.map(function(cell){ + return row.map(function(cell) { return new Cell(cell); }); }); } - function makeTableLayout(rows){ + function makeTableLayout(rows) { var cellRows = generateCells(rows); layoutTable(cellRows); fillInTable(cellRows); @@ -173,52 +172,51 @@ var ColSpanCell = Cell.ColSpanCell; makeTableLayout: makeTableLayout, layoutTable: layoutTable, addRowSpanCells: addRowSpanCells, - maxWidth:maxWidth, - fillInTable:fillInTable, - computeWidths:makeComputeWidths('colSpan','desiredWidth','x',1), - computeHeights:makeComputeWidths('rowSpan','desiredHeight','y',1) + maxWidth: maxWidth, + fillInTable: fillInTable, + computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), + computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), }; })(); -function makeComputeWidths(colSpan,desiredWidth,x,forcedMin){ - return function(vals,table){ +function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) { + return function(vals, table) { var result = []; var spanners = []; - table.forEach(function(row){ - row.forEach(function(cell){ - if((cell[colSpan] || 1) > 1){ + table.forEach(function(row) { + row.forEach(function(cell) { + if ((cell[colSpan] || 1) > 1) { spanners.push(cell); - } - else { + } else { result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin); } }); }); - vals.forEach(function(val,index){ - if(kindOf(val) === 'number'){ + vals.forEach(function(val, index) { + if (kindOf(val) === 'number') { result[index] = val; } }); //spanners.forEach(function(cell){ - for(var k = spanners.length - 1; k >=0; k--){ + for (var k = spanners.length - 1; k >= 0; k--) { var cell = spanners[k]; var span = cell[colSpan]; var col = cell[x]; var existingWidth = result[col]; var editableCols = kindOf(vals[col]) === 'number' ? 0 : 1; - for(var i = 1; i < span; i ++){ + for (var i = 1; i < span; i++) { existingWidth += 1 + result[col + i]; - if(kindOf(vals[col + i]) !== 'number'){ + if (kindOf(vals[col + i]) !== 'number') { editableCols++; } } - if(cell[desiredWidth] > existingWidth){ + if (cell[desiredWidth] > existingWidth) { i = 0; - while(editableCols > 0 && cell[desiredWidth] > existingWidth){ - if(kindOf(vals[col+i]) !== 'number'){ - var dif = Math.round( (cell[desiredWidth] - existingWidth) / editableCols ); + while (editableCols > 0 && cell[desiredWidth] > existingWidth) { + if (kindOf(vals[col + i]) !== 'number') { + var dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols); existingWidth += dif; result[col + i] += dif; editableCols--; @@ -228,8 +226,8 @@ function makeComputeWidths(colSpan,desiredWidth,x,forcedMin){ } } - objectAssign(vals,result); - for(var j = 0; j < vals.length; j++){ + objectAssign(vals, result); + for (var j = 0; j < vals.length; j++) { vals[j] = Math.max(forcedMin, vals[j] || 0); } }; diff --git a/src/table.js b/src/table.js index 67daba0..06b15f0 100644 --- a/src/table.js +++ b/src/table.js @@ -1,75 +1,74 @@ var utils = require('./utils'); var tableLayout = require('./layout-manager'); -function Table(options){ +function Table(options) { this.options = utils.mergeOptions(options); } Table.prototype.__proto__ = Array.prototype; -Table.prototype.toString = function(){ +Table.prototype.toString = function() { var array = this; var headersPresent = this.options.head && this.options.head.length; - if(headersPresent){ + if (headersPresent) { array = [this.options.head]; - if(this.length){ - array.push.apply(array,this); + if (this.length) { + array.push.apply(array, this); } - } - else { - this.options.style.head=[]; + } else { + this.options.style.head = []; } var cells = tableLayout.makeTableLayout(array); - cells.forEach(function(row){ - row.forEach(function(cell){ - cell.mergeTableOptions(this.options,cells); - },this); - },this); + cells.forEach(function(row) { + row.forEach(function(cell) { + cell.mergeTableOptions(this.options, cells); + }, this); + }, this); - tableLayout.computeWidths(this.options.colWidths,cells); - tableLayout.computeHeights(this.options.rowHeights,cells); + tableLayout.computeWidths(this.options.colWidths, cells); + tableLayout.computeHeights(this.options.rowHeights, cells); - cells.forEach(function(row){ - row.forEach(function(cell){ + cells.forEach(function(row) { + row.forEach(function(cell) { cell.init(this.options); - },this); - },this); + }, this); + }, this); var result = []; - for(var rowIndex = 0; rowIndex < cells.length; rowIndex++){ + for (var rowIndex = 0; rowIndex < cells.length; rowIndex++) { var row = cells[rowIndex]; var heightOfRow = this.options.rowHeights[rowIndex]; - if(rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)){ - doDraw(row,'top',result); + if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { + doDraw(row, 'top', result); } - for(var lineNum = 0; lineNum < heightOfRow; lineNum++){ - doDraw(row,lineNum,result); + for (var lineNum = 0; lineNum < heightOfRow; lineNum++) { + doDraw(row, lineNum, result); } - if(rowIndex + 1 == cells.length){ - doDraw(row,'bottom',result); + if (rowIndex + 1 == cells.length) { + doDraw(row, 'bottom', result); } } return result.join('\n'); }; -function doDraw(row,lineNum,result){ +function doDraw(row, lineNum, result) { var line = []; - row.forEach(function(cell){ + row.forEach(function(cell) { line.push(cell.draw(lineNum)); }); var str = line.join(''); - if(str.length) result.push(str); + if (str.length) result.push(str); } -Table.prototype.__defineGetter__('width', function (){ - var str = this.toString().split("\n"); +Table.prototype.__defineGetter__('width', function() { + var str = this.toString().split('\n'); return str[0].length; }); diff --git a/src/utils.js b/src/utils.js index be56bc5..a85023e 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,18 +1,20 @@ var objectAssign = require('object-assign'); var stringWidth = require('string-width'); -function codeRegex(capture){ - return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g +function codeRegex(capture) { + return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; } -function strlen(str){ +function strlen(str) { var code = codeRegex(); - var stripped = ("" + str).replace(code,''); - var split = stripped.split("\n"); - return split.reduce(function (memo, s) { return (stringWidth(s) > memo) ? stringWidth(s) : memo }, 0); + var stripped = ('' + str).replace(code, ''); + var split = stripped.split('\n'); + return split.reduce(function(memo, s) { + return stringWidth(s) > memo ? stringWidth(s) : memo; + }, 0); } -function repeat(str,times){ +function repeat(str, times) { return Array(times + 1).join(str); } @@ -26,13 +28,13 @@ function pad(str, len, pad, dir) { break; case 'center': - var right = Math.ceil((padlen) / 2); + var right = Math.ceil(padlen / 2); var left = padlen - right; str = repeat(pad, left) + str + repeat(pad, right); break; - default : - str = str + repeat(pad,padlen); + default: + str = str + repeat(pad, padlen); break; } } @@ -41,12 +43,12 @@ function pad(str, len, pad, dir) { var codeCache = {}; -function addToCodeCache(name,on,off){ +function addToCodeCache(name, on, off) { on = '\u001b[' + on + 'm'; off = '\u001b[' + off + 'm'; - codeCache[on] = {set:name,to:true}; - codeCache[off] = {set:name,to:false}; - codeCache[name] = {on:on,off:off}; + codeCache[on] = { set: name, to: true }; + codeCache[off] = { set: name, to: false }; + codeCache[name] = { on: on, off: off }; } //https://github.com/Marak/colors.js/blob/master/lib/styles.js @@ -56,18 +58,13 @@ addToCodeCache('underline', 4, 24); addToCodeCache('inverse', 7, 27); addToCodeCache('strikethrough', 9, 29); - -function updateState(state, controlChars){ +function updateState(state, controlChars) { var controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0; - if ( (controlCode >= 30 && controlCode <= 39) - || (controlCode >= 90 && controlCode <= 97) - ) { + if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) { state.lastForegroundAdded = controlChars[0]; return; } - if ( (controlCode >= 40 && controlCode <= 49) - || (controlCode >= 100 && controlCode <= 107) - ) { + if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) { state.lastBackgroundAdded = controlChars[0]; return; } @@ -86,76 +83,76 @@ function updateState(state, controlChars){ } } -function readState(line){ +function readState(line) { var code = codeRegex(true); var controlChars = code.exec(line); var state = {}; - while(controlChars !== null){ + while (controlChars !== null) { updateState(state, controlChars); controlChars = code.exec(line); } return state; } -function unwindState(state,ret){ +function unwindState(state, ret) { var lastBackgroundAdded = state.lastBackgroundAdded; var lastForegroundAdded = state.lastForegroundAdded; delete state.lastBackgroundAdded; delete state.lastForegroundAdded; - Object.keys(state).forEach(function(key){ - if(state[key]){ + Object.keys(state).forEach(function(key) { + if (state[key]) { ret += codeCache[key].off; } }); - if(lastBackgroundAdded && (lastBackgroundAdded != '\u001b[49m')){ + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { ret += '\u001b[49m'; } - if(lastForegroundAdded && (lastForegroundAdded != '\u001b[39m')){ + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { ret += '\u001b[39m'; } return ret; } -function rewindState(state,ret){ +function rewindState(state, ret) { var lastBackgroundAdded = state.lastBackgroundAdded; var lastForegroundAdded = state.lastForegroundAdded; delete state.lastBackgroundAdded; delete state.lastForegroundAdded; - Object.keys(state).forEach(function(key){ - if(state[key]){ + Object.keys(state).forEach(function(key) { + if (state[key]) { ret = codeCache[key].on + ret; } }); - if(lastBackgroundAdded && (lastBackgroundAdded != '\u001b[49m')){ + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { ret = lastBackgroundAdded + ret; } - if(lastForegroundAdded && (lastForegroundAdded != '\u001b[39m')){ + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { ret = lastForegroundAdded + ret; } return ret; } -function truncateWidth(str, desiredLength){ +function truncateWidth(str, desiredLength) { if (str.length === strlen(str)) { return str.substr(0, desiredLength); } - while (strlen(str) > desiredLength){ + while (strlen(str) > desiredLength) { str = str.slice(0, -1); } return str; } -function truncateWidthWithAnsi(str, desiredLength){ +function truncateWidthWithAnsi(str, desiredLength) { var code = codeRegex(true); var split = str.split(codeRegex()); var splitIndex = 0; @@ -164,30 +161,32 @@ function truncateWidthWithAnsi(str, desiredLength){ var myArray; var state = {}; - while(retLen < desiredLength){ + while (retLen < desiredLength) { myArray = code.exec(str); var toAdd = split[splitIndex]; splitIndex++; - if (retLen + strlen(toAdd) > desiredLength){ + if (retLen + strlen(toAdd) > desiredLength) { toAdd = truncateWidth(toAdd, desiredLength - retLen); } ret += toAdd; retLen += strlen(toAdd); - if(retLen < desiredLength){ - if (!myArray) { break; } // full-width chars may cause a whitespace which cannot be filled + if (retLen < desiredLength) { + if (!myArray) { + break; + } // full-width chars may cause a whitespace which cannot be filled ret += myArray[0]; - updateState(state,myArray); + updateState(state, myArray); } } - return unwindState(state,ret); + return unwindState(state, ret); } -function truncate(str, desiredLength, truncateChar){ +function truncate(str, desiredLength, truncateChar) { truncateChar = truncateChar || '…'; var lengthOfStr = strlen(str); - if(lengthOfStr <= desiredLength){ + if (lengthOfStr <= desiredLength) { return str; } desiredLength -= strlen(truncateChar); @@ -197,43 +196,42 @@ function truncate(str, desiredLength, truncateChar){ return ret + truncateChar; } - -function defaultOptions(){ - return{ +function defaultOptions() { + return { chars: { - 'top': '─' - , 'top-mid': '┬' - , 'top-left': '┌' - , 'top-right': '┐' - , 'bottom': '─' - , 'bottom-mid': '┴' - , 'bottom-left': '└' - , 'bottom-right': '┘' - , 'left': '│' - , 'left-mid': '├' - , 'mid': '─' - , 'mid-mid': '┼' - , 'right': '│' - , 'right-mid': '┤' - , 'middle': '│' - } - , truncate: '…' - , colWidths: [] - , rowHeights: [] - , colAligns: [] - , rowAligns: [] - , style: { - 'padding-left': 1 - , 'padding-right': 1 - , head: ['red'] - , border: ['grey'] - , compact : false - } - , head: [] + top: '─', + 'top-mid': '┬', + 'top-left': '┌', + 'top-right': '┐', + bottom: '─', + 'bottom-mid': '┴', + 'bottom-left': '└', + 'bottom-right': '┘', + left: '│', + 'left-mid': '├', + mid: '─', + 'mid-mid': '┼', + right: '│', + 'right-mid': '┤', + middle: '│', + }, + truncate: '…', + colWidths: [], + rowHeights: [], + colAligns: [], + rowAligns: [], + style: { + 'padding-left': 1, + 'padding-right': 1, + head: ['red'], + border: ['grey'], + compact: false, + }, + head: [], }; } -function mergeOptions(options,defaults){ +function mergeOptions(options, defaults) { options = options || {}; defaults = defaults || defaultOptions(); var ret = objectAssign({}, defaults, options); @@ -242,7 +240,7 @@ function mergeOptions(options,defaults){ return ret; } -function wordWrap(maxLength,input){ +function wordWrap(maxLength, input) { var lines = []; var split = input.split(/(\s+)/g); var line = []; @@ -254,8 +252,8 @@ function wordWrap(maxLength,input){ if (lineLength > 0 && whitespace) { newLength += whitespace.length; } - if(newLength > maxLength){ - if(lineLength !== 0){ + if (newLength > maxLength) { + if (lineLength !== 0) { lines.push(line.join('')); } line = [word]; @@ -264,41 +262,41 @@ function wordWrap(maxLength,input){ line.push(whitespace || '', word); lineLength = newLength; } - whitespace = split[i+1]; + whitespace = split[i + 1]; } - if(lineLength){ + if (lineLength) { lines.push(line.join('')); } return lines; } -function multiLineWordWrap(maxLength, input){ +function multiLineWordWrap(maxLength, input) { var output = []; input = input.split('\n'); - for(var i = 0; i < input.length; i++){ - output.push.apply(output,wordWrap(maxLength,input[i])); + for (var i = 0; i < input.length; i++) { + output.push.apply(output, wordWrap(maxLength, input[i])); } return output; } -function colorizeLines(input){ +function colorizeLines(input) { var state = {}; var output = []; - for(var i = 0; i < input.length; i++){ - var line = rewindState(state,input[i]) ; + for (var i = 0; i < input.length; i++) { + var line = rewindState(state, input[i]); state = readState(line); - var temp = objectAssign({},state); - output.push(unwindState(temp,line)); + var temp = objectAssign({}, state); + output.push(unwindState(temp, line)); } return output; } module.exports = { - strlen:strlen, - repeat:repeat, - pad:pad, - truncate:truncate, - mergeOptions:mergeOptions, - wordWrap:multiLineWordWrap, - colorizeLines:colorizeLines + strlen: strlen, + repeat: repeat, + pad: pad, + truncate: truncate, + mergeOptions: mergeOptions, + wordWrap: multiLineWordWrap, + colorizeLines: colorizeLines, }; diff --git a/test/cell-test.js b/test/cell-test.js index b857b52..06ae5f3 100644 --- a/test/cell-test.js +++ b/test/cell-test.js @@ -1,113 +1,113 @@ -describe('Cell',function(){ +describe('Cell', function() { var colors = require('colors'); var Cell = require('../src/cell'); var RowSpanCell = Cell.RowSpanCell; var ColSpanCell = Cell.ColSpanCell; var mergeOptions = require('../src/utils').mergeOptions; - function defaultOptions(){ + function defaultOptions() { //overwrite coloring of head and border by default for easier testing. - return mergeOptions({style:{head:[],border:[]}}); + return mergeOptions({ style: { head: [], border: [] } }); } - function defaultChars(){ + function defaultChars() { return { - 'top': '─' - , 'topMid': '┬' - , 'topLeft': '┌' - , 'topRight': '┐' - , 'bottom': '─' - , 'bottomMid': '┴' - , 'bottomLeft': '└' - , 'bottomRight': '┘' - , 'left': '│' - , 'leftMid': '├' - , 'mid': '─' - , 'midMid': '┼' - , 'right': '│' - , 'rightMid': '┤' - , 'middle': '│' + top: '─', + topMid: '┬', + topLeft: '┌', + topRight: '┐', + bottom: '─', + bottomMid: '┴', + bottomLeft: '└', + bottomRight: '┘', + left: '│', + leftMid: '├', + mid: '─', + midMid: '┼', + right: '│', + rightMid: '┤', + middle: '│', }; } - describe('constructor',function(){ - it('colSpan and rowSpan default to 1',function(){ + describe('constructor', function() { + it('colSpan and rowSpan default to 1', function() { var cell = new Cell(); expect(cell.colSpan).toEqual(1); expect(cell.rowSpan).toEqual(1); }); - it('colSpan and rowSpan can be set via constructor',function(){ - var cell = new Cell({rowSpan:2,colSpan:3}); + it('colSpan and rowSpan can be set via constructor', function() { + var cell = new Cell({ rowSpan: 2, colSpan: 3 }); expect(cell.rowSpan).toEqual(2); expect(cell.colSpan).toEqual(3); }); - it('content can be set as a string',function(){ + it('content can be set as a string', function() { var cell = new Cell('hello\nworld'); expect(cell.content).toEqual('hello\nworld'); }); - it('content can be set as a options property',function(){ - var cell = new Cell({content:'hello\nworld'}); + it('content can be set as a options property', function() { + var cell = new Cell({ content: 'hello\nworld' }); expect(cell.content).toEqual('hello\nworld'); }); - it('default content is an empty string',function(){ + it('default content is an empty string', function() { var cell = new Cell(); expect(cell.content).toEqual(''); }); - it('new Cell(null) will have empty string content',function(){ + it('new Cell(null) will have empty string content', function() { var cell = new Cell(null); expect(cell.content).toEqual(''); }); - it('new Cell({content: null}) will have empty string content',function(){ - var cell = new Cell({content: null}); + it('new Cell({content: null}) will have empty string content', function() { + var cell = new Cell({ content: null }); expect(cell.content).toEqual(''); }); - it('new Cell(0) will have "0" as content',function(){ + it('new Cell(0) will have "0" as content', function() { var cell = new Cell(0); expect(cell.content).toEqual('0'); }); - it('new Cell({content: 0}) will have "0" as content',function(){ - var cell = new Cell({content: 0}); + it('new Cell({content: 0}) will have "0" as content', function() { + var cell = new Cell({ content: 0 }); expect(cell.content).toEqual('0'); }); - it('new Cell(false) will have "false" as content',function(){ + it('new Cell(false) will have "false" as content', function() { var cell = new Cell(false); expect(cell.content).toEqual('false'); }); - it('new Cell({content: false}) will have "false" as content',function(){ - var cell = new Cell({content: false}); + it('new Cell({content: false}) will have "false" as content', function() { + var cell = new Cell({ content: false }); expect(cell.content).toEqual('false'); }); }); - describe('mergeTableOptions',function(){ - describe('chars',function(){ - it('unset chars take on value of table',function(){ + describe('mergeTableOptions', function() { + describe('chars', function() { + it('unset chars take on value of table', function() { var cell = new Cell(); var tableOptions = defaultOptions(); cell.mergeTableOptions(tableOptions); expect(cell.chars).toEqual(defaultChars()); }); - it('set chars override the value of table',function(){ - var cell = new Cell({chars:{bottomRight:'='}}); + it('set chars override the value of table', function() { + var cell = new Cell({ chars: { bottomRight: '=' } }); cell.mergeTableOptions(defaultOptions()); var chars = defaultChars(); chars.bottomRight = '='; expect(cell.chars).toEqual(chars); }); - it('hyphenated names will be converted to camel-case',function(){ - var cell = new Cell({chars:{'bottom-left':'='}}); + it('hyphenated names will be converted to camel-case', function() { + var cell = new Cell({ chars: { 'bottom-left': '=' } }); cell.mergeTableOptions(defaultOptions()); var chars = defaultChars(); chars.bottomLeft = '='; @@ -115,22 +115,22 @@ describe('Cell',function(){ }); }); - describe('truncate',function(){ - it('if unset takes on value of table',function(){ + describe('truncate', function() { + it('if unset takes on value of table', function() { var cell = new Cell(); cell.mergeTableOptions(defaultOptions()); expect(cell.truncate).toEqual('…'); }); - it('if set overrides value of table',function(){ - var cell = new Cell({truncate:'...'}); + it('if set overrides value of table', function() { + var cell = new Cell({ truncate: '...' }); cell.mergeTableOptions(defaultOptions()); expect(cell.truncate).toEqual('...'); }); }); - describe('style.padding-left', function () { - it('if unset will be copied from tableOptions.style', function () { + describe('style.padding-left', function() { + it('if unset will be copied from tableOptions.style', function() { var cell = new Cell(); cell.mergeTableOptions(defaultOptions()); expect(cell.paddingLeft).toEqual(1); @@ -148,19 +148,19 @@ describe('Cell',function(){ expect(cell.paddingLeft).toEqual(3); }); - it('if set will override tableOptions.style', function () { - var cell = new Cell({style:{'padding-left':2}}); + it('if set will override tableOptions.style', function() { + var cell = new Cell({ style: { 'padding-left': 2 } }); cell.mergeTableOptions(defaultOptions()); expect(cell.paddingLeft).toEqual(2); - cell = new Cell({style:{paddingLeft:3}}); + cell = new Cell({ style: { paddingLeft: 3 } }); cell.mergeTableOptions(defaultOptions()); expect(cell.paddingLeft).toEqual(3); }); }); - describe('style.padding-right', function () { - it('if unset will be copied from tableOptions.style', function () { + describe('style.padding-right', function() { + it('if unset will be copied from tableOptions.style', function() { var cell = new Cell(); cell.mergeTableOptions(defaultOptions()); expect(cell.paddingRight).toEqual(1); @@ -178,53 +178,53 @@ describe('Cell',function(){ expect(cell.paddingRight).toEqual(3); }); - it('if set will override tableOptions.style', function () { - var cell = new Cell({style:{'padding-right':2}}); + it('if set will override tableOptions.style', function() { + var cell = new Cell({ style: { 'padding-right': 2 } }); cell.mergeTableOptions(defaultOptions()); expect(cell.paddingRight).toEqual(2); - cell = new Cell({style:{paddingRight:3}}); + cell = new Cell({ style: { paddingRight: 3 } }); cell.mergeTableOptions(defaultOptions()); expect(cell.paddingRight).toEqual(3); }); }); - describe('desiredWidth',function(){ - it('content(hello) padding(1,1) == 7',function(){ + describe('desiredWidth', function() { + it('content(hello) padding(1,1) == 7', function() { var cell = new Cell('hello'); cell.mergeTableOptions(defaultOptions()); expect(cell.desiredWidth).toEqual(7); }); - it('content(hi) padding(1,2) == 5',function(){ - var cell = new Cell({content:'hi',style:{paddingRight:2}}); + it('content(hi) padding(1,2) == 5', function() { + var cell = new Cell({ content: 'hi', style: { paddingRight: 2 } }); var tableOptions = defaultOptions(); cell.mergeTableOptions(tableOptions); expect(cell.desiredWidth).toEqual(5); }); - it('content(hi) padding(3,2) == 7',function(){ - var cell = new Cell({content:'hi',style:{paddingLeft:3,paddingRight:2}}); + it('content(hi) padding(3,2) == 7', function() { + var cell = new Cell({ content: 'hi', style: { paddingLeft: 3, paddingRight: 2 } }); var tableOptions = defaultOptions(); cell.mergeTableOptions(tableOptions); expect(cell.desiredWidth).toEqual(7); }); }); - describe('desiredHeight',function(){ - it('1 lines of text',function(){ + describe('desiredHeight', function() { + it('1 lines of text', function() { var cell = new Cell('hi'); cell.mergeTableOptions(defaultOptions()); expect(cell.desiredHeight).toEqual(1); }); - it('2 lines of text',function(){ + it('2 lines of text', function() { var cell = new Cell('hi\nbye'); cell.mergeTableOptions(defaultOptions()); expect(cell.desiredHeight).toEqual(2); }); - it('2 lines of text',function(){ + it('2 lines of text', function() { var cell = new Cell('hi\nbye\nyo'); cell.mergeTableOptions(defaultOptions()); expect(cell.desiredHeight).toEqual(3); @@ -232,11 +232,11 @@ describe('Cell',function(){ }); }); - describe('init',function(){ - describe('hAlign',function(){ - it('if unset takes colAlign value from tableOptions',function(){ + describe('init', function() { + describe('hAlign', function() { + it('if unset takes colAlign value from tableOptions', function() { var tableOptions = defaultOptions(); - tableOptions.colAligns = ['left','right','both']; + tableOptions.colAligns = ['left', 'right', 'both']; var cell = new Cell(); cell.x = 0; cell.mergeTableOptions(tableOptions); @@ -249,25 +249,25 @@ describe('Cell',function(){ expect(cell.hAlign).toEqual('right'); cell = new Cell(); cell.mergeTableOptions(tableOptions); - cell.x=2; + cell.x = 2; cell.init(tableOptions); expect(cell.hAlign).toEqual('both'); }); - it('if set overrides tableOptions',function(){ + it('if set overrides tableOptions', function() { var tableOptions = defaultOptions(); - tableOptions.colAligns = ['left','right','both']; - var cell = new Cell({hAlign:'right'}); + tableOptions.colAligns = ['left', 'right', 'both']; + var cell = new Cell({ hAlign: 'right' }); cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.hAlign).toEqual('right'); - cell = new Cell({hAlign:'left'}); + cell = new Cell({ hAlign: 'left' }); cell.x = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.hAlign).toEqual('left'); - cell = new Cell({hAlign:'right'}); + cell = new Cell({ hAlign: 'right' }); cell.x = 2; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); @@ -275,12 +275,12 @@ describe('Cell',function(){ }); }); - describe('vAlign',function(){ - it('if unset takes rowAlign value from tableOptions',function(){ + describe('vAlign', function() { + it('if unset takes rowAlign value from tableOptions', function() { var tableOptions = defaultOptions(); - tableOptions.rowAligns = ['top','bottom','center']; + tableOptions.rowAligns = ['top', 'bottom', 'center']; var cell = new Cell(); - cell.y=0; + cell.y = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.vAlign).toEqual('top'); @@ -296,23 +296,23 @@ describe('Cell',function(){ expect(cell.vAlign).toEqual('center'); }); - it('if set overrides tableOptions',function(){ + it('if set overrides tableOptions', function() { var tableOptions = defaultOptions(); - tableOptions.rowAligns = ['top','bottom','center']; + tableOptions.rowAligns = ['top', 'bottom', 'center']; - var cell = new Cell({vAlign:'bottom'}); + var cell = new Cell({ vAlign: 'bottom' }); cell.y = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.vAlign).toEqual('bottom'); - cell = new Cell({vAlign:'top'}); + cell = new Cell({ vAlign: 'top' }); cell.y = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.vAlign).toEqual('top'); - cell = new Cell({vAlign:'center'}); + cell = new Cell({ vAlign: 'center' }); cell.y = 2; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); @@ -320,10 +320,10 @@ describe('Cell',function(){ }); }); - describe('width', function(){ - it('will match colWidth of x',function(){ + describe('width', function() { + it('will match colWidth of x', function() { var tableOptions = defaultOptions(); - tableOptions.colWidths = [5,10,15]; + tableOptions.colWidths = [5, 10, 15]; var cell = new Cell(); cell.x = 0; @@ -344,139 +344,137 @@ describe('Cell',function(){ expect(cell.width).toEqual(15); }); - it('will add colWidths if colSpan > 1 with wordWrap false',function(){ + it('will add colWidths if colSpan > 1 with wordWrap false', function() { var tableOptions = defaultOptions(); - tableOptions.colWidths = [5,10,15]; + tableOptions.colWidths = [5, 10, 15]; - var cell = new Cell({colSpan:2}); - cell.x=0; + var cell = new Cell({ colSpan: 2 }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.width).toEqual(16); - cell = new Cell({colSpan:2}); - cell.x=1; + cell = new Cell({ colSpan: 2 }); + cell.x = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.width).toEqual(26); - cell = new Cell({colSpan:3}); - cell.x=0; + cell = new Cell({ colSpan: 3 }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.width).toEqual(32); }); - it('will add colWidths if colSpan > 1 with wordWrap true',function(){ + it('will add colWidths if colSpan > 1 with wordWrap true', function() { var tableOptions = defaultOptions(); - tableOptions.colWidths = [5,10,15]; + tableOptions.colWidths = [5, 10, 15]; tableOptions.wordWrap = true; - var cell = new Cell({colSpan:2}); - cell.x=0; + var cell = new Cell({ colSpan: 2 }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.width).toEqual(16); - cell = new Cell({colSpan:2}); - cell.x=1; + cell = new Cell({ colSpan: 2 }); + cell.x = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.width).toEqual(26); - cell = new Cell({colSpan:3}); - cell.x=0; + cell = new Cell({ colSpan: 3 }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.width).toEqual(32); }); - it('will use multiple columns for wordWrap text when using colSpan and wordWrap together',function(){ + it('will use multiple columns for wordWrap text when using colSpan and wordWrap together', function() { var tableOptions = defaultOptions(); tableOptions.colWidths = [7, 7, 17]; tableOptions.wordWrap = true; - var cell = new Cell({content:"the quick brown fox", colSpan:2}); - cell.x=0; + var cell = new Cell({ content: 'the quick brown fox', colSpan: 2 }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.lines.length).toEqual(2); expect(cell.lines[0]).toContain('quick'); expect(cell.lines[1]).toContain('fox'); - cell = new Cell({content:"the quick brown fox", colSpan:2}); - cell.x=1; + cell = new Cell({ content: 'the quick brown fox', colSpan: 2 }); + cell.x = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.lines.length).toEqual(1); expect(cell.lines[0]).toContain('fox'); - cell = new Cell({content:"the quick brown fox", colSpan:3}); - cell.x=0; + cell = new Cell({ content: 'the quick brown fox', colSpan: 3 }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.lines.length).toEqual(1); expect(cell.lines[0]).toContain('fox'); }); - it('will only use one column for wordWrap text when not using colSpan',function(){ + it('will only use one column for wordWrap text when not using colSpan', function() { var tableOptions = defaultOptions(); tableOptions.colWidths = [7, 7, 7]; tableOptions.wordWrap = true; - var cell = new Cell({content:"the quick brown fox"}); - cell.x=0; + var cell = new Cell({ content: 'the quick brown fox' }); + cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.lines.length).toEqual(4); expect(cell.lines[1]).toContain('quick'); expect(cell.lines[3]).toContain('fox'); }); - - }); - describe('height', function(){ - it('will match rowHeight of x',function(){ + describe('height', function() { + it('will match rowHeight of x', function() { var tableOptions = defaultOptions(); - tableOptions.rowHeights = [5,10,15]; + tableOptions.rowHeights = [5, 10, 15]; var cell = new Cell(); - cell.y=0; + cell.y = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.height).toEqual(5); cell = new Cell(); - cell.y=1; + cell.y = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.height).toEqual(10); cell = new Cell(); - cell.y=2; + cell.y = 2; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.height).toEqual(15); }); - it('will add rowHeights if rowSpan > 1',function(){ + it('will add rowHeights if rowSpan > 1', function() { var tableOptions = defaultOptions(); - tableOptions.rowHeights = [5,10,15]; + tableOptions.rowHeights = [5, 10, 15]; - var cell = new Cell({rowSpan:2}); + var cell = new Cell({ rowSpan: 2 }); cell.y = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.height).toEqual(16); - cell = new Cell({rowSpan:2}); + cell = new Cell({ rowSpan: 2 }); cell.y = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.height).toEqual(26); - cell = new Cell({rowSpan:3}); + cell = new Cell({ rowSpan: 3 }); cell.y = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); @@ -484,15 +482,15 @@ describe('Cell',function(){ }); }); - describe('drawRight', function(){ + describe('drawRight', function() { var tableOptions; - beforeEach(function(){ + beforeEach(function() { tableOptions = defaultOptions(); - tableOptions.colWidths = [20,20,20]; + tableOptions.colWidths = [20, 20, 20]; }); - it('col 1 of 3, with default colspan',function(){ + it('col 1 of 3, with default colspan', function() { var cell = new Cell(); cell.x = 0; cell.mergeTableOptions(tableOptions); @@ -500,7 +498,7 @@ describe('Cell',function(){ expect(cell.drawRight).toEqual(false); }); - it('col 2 of 3, with default colspan',function(){ + it('col 2 of 3, with default colspan', function() { var cell = new Cell(); cell.x = 1; cell.mergeTableOptions(tableOptions); @@ -508,7 +506,7 @@ describe('Cell',function(){ expect(cell.drawRight).toEqual(false); }); - it('col 3 of 3, with default colspan',function(){ + it('col 3 of 3, with default colspan', function() { var cell = new Cell(); cell.x = 2; cell.mergeTableOptions(tableOptions); @@ -516,33 +514,33 @@ describe('Cell',function(){ expect(cell.drawRight).toEqual(true); }); - it('col 3 of 4, with default colspan',function(){ + it('col 3 of 4, with default colspan', function() { var cell = new Cell(); cell.x = 2; - tableOptions.colWidths = [20,20,20,20]; + tableOptions.colWidths = [20, 20, 20, 20]; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.drawRight).toEqual(false); }); - it('col 2 of 3, with colspan of 2',function(){ - var cell = new Cell({colSpan:2}); - cell.x=1; + it('col 2 of 3, with colspan of 2', function() { + var cell = new Cell({ colSpan: 2 }); + cell.x = 1; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.drawRight).toEqual(true); }); - it('col 1 of 3, with colspan of 3',function(){ - var cell = new Cell({colSpan:3}); + it('col 1 of 3, with colspan of 3', function() { + var cell = new Cell({ colSpan: 3 }); cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); expect(cell.drawRight).toEqual(true); }); - it('col 1 of 3, with colspan of 2',function(){ - var cell = new Cell({colSpan:2}); + it('col 1 of 3, with colspan of 2', function() { + var cell = new Cell({ colSpan: 2 }); cell.x = 0; cell.mergeTableOptions(tableOptions); cell.init(tableOptions); @@ -551,10 +549,10 @@ describe('Cell',function(){ }); }); - describe('drawLine', function(){ + describe('drawLine', function() { var cell; - beforeEach(function () { + beforeEach(function() { cell = new Cell(); //manually init @@ -572,15 +570,15 @@ describe('Cell',function(){ cell.x = cell.y = 0; }); - describe('top line',function(){ - it('will draw the top left corner when x=0,y=0',function(){ + describe('top line', function() { + it('will draw the top left corner when x=0,y=0', function() { cell.x = cell.y = 0; expect(cell.draw('top')).toEqual('┌───────'); cell.drawRight = true; expect(cell.draw('top')).toEqual('┌───────┐'); }); - it('will draw the top mid corner when x=1,y=0',function(){ + it('will draw the top mid corner when x=1,y=0', function() { cell.x = 1; cell.y = 0; expect(cell.draw('top')).toEqual('┬───────'); @@ -588,7 +586,7 @@ describe('Cell',function(){ expect(cell.draw('top')).toEqual('┬───────┐'); }); - it('will draw the left mid corner when x=0,y=1',function(){ + it('will draw the left mid corner when x=0,y=1', function() { cell.x = 0; cell.y = 1; expect(cell.draw('top')).toEqual('├───────'); @@ -596,7 +594,7 @@ describe('Cell',function(){ expect(cell.draw('top')).toEqual('├───────┤'); }); - it('will draw the mid mid corner when x=1,y=1',function(){ + it('will draw the mid mid corner when x=1,y=1', function() { cell.x = 1; cell.y = 1; expect(cell.draw('top')).toEqual('┼───────'); @@ -604,14 +602,14 @@ describe('Cell',function(){ expect(cell.draw('top')).toEqual('┼───────┤'); }); - it('will draw in the color specified by border style',function(){ + it('will draw in the color specified by border style', function() { cell.border = ['gray']; - expect(cell.draw('top')).toEqual(colors.gray('┌───────')) + expect(cell.draw('top')).toEqual(colors.gray('┌───────')); }); }); - describe('bottom line',function(){ - it('will draw the bottom left corner if x=0',function(){ + describe('bottom line', function() { + it('will draw the bottom left corner if x=0', function() { cell.x = 0; cell.y = 1; expect(cell.draw('bottom')).toEqual('└───────'); @@ -619,7 +617,7 @@ describe('Cell',function(){ expect(cell.draw('bottom')).toEqual('└───────┘'); }); - it('will draw the bottom left corner if x=1',function(){ + it('will draw the bottom left corner if x=1', function() { cell.x = 1; cell.y = 1; expect(cell.draw('bottom')).toEqual('┴───────'); @@ -627,19 +625,19 @@ describe('Cell',function(){ expect(cell.draw('bottom')).toEqual('┴───────┘'); }); - it('will draw in the color specified by border style',function(){ + it('will draw in the color specified by border style', function() { cell.border = ['gray']; - expect(cell.draw('bottom')).toEqual(colors.gray('└───────')) + expect(cell.draw('bottom')).toEqual(colors.gray('└───────')); }); }); - describe('drawBottom',function(){ - it('draws an empty line',function(){ + describe('drawBottom', function() { + it('draws an empty line', function() { expect(cell.drawEmpty()).toEqual('L '); expect(cell.drawEmpty(true)).toEqual('L R'); }); - it('draws an empty line',function(){ + it('draws an empty line', function() { cell.border = ['gray']; cell.head = ['red']; expect(cell.drawEmpty()).toEqual(colors.gray('L') + colors.red(' ')); @@ -647,26 +645,26 @@ describe('Cell',function(){ }); }); - describe('first line of text',function(){ - beforeEach(function () { + describe('first line of text', function() { + beforeEach(function() { cell.width = 9; }); - it('will draw left side if x=0',function(){ + it('will draw left side if x=0', function() { cell.x = 0; expect(cell.draw(0)).toEqual('L hello '); cell.drawRight = true; expect(cell.draw(0)).toEqual('L hello R'); }); - it('will draw mid side if x=1',function(){ + it('will draw mid side if x=1', function() { cell.x = 1; expect(cell.draw(0)).toEqual('M hello '); cell.drawRight = true; expect(cell.draw(0)).toEqual('M hello R'); }); - it('will align left',function(){ + it('will align left', function() { cell.x = 1; cell.hAlign = 'left'; expect(cell.draw(0)).toEqual('M hello '); @@ -674,7 +672,7 @@ describe('Cell',function(){ expect(cell.draw(0)).toEqual('M hello R'); }); - it('will align right',function(){ + it('will align right', function() { cell.x = 1; cell.hAlign = 'right'; expect(cell.draw(0)).toEqual('M hello '); @@ -682,7 +680,7 @@ describe('Cell',function(){ expect(cell.draw(0)).toEqual('M hello R'); }); - it('left and right will be drawn in color of border style',function(){ + it('left and right will be drawn in color of border style', function() { cell.border = ['gray']; cell.x = 0; expect(cell.draw(0)).toEqual(colors.gray('L') + ' hello '); @@ -690,7 +688,7 @@ describe('Cell',function(){ expect(cell.draw(0)).toEqual(colors.gray('L') + ' hello ' + colors.gray('R')); }); - it('text will be drawn in color of head style if y == 0',function(){ + it('text will be drawn in color of head style if y == 0', function() { cell.head = ['red']; cell.x = cell.y = 0; expect(cell.draw(0)).toEqual('L' + colors.red(' hello ')); @@ -698,7 +696,7 @@ describe('Cell',function(){ expect(cell.draw(0)).toEqual('L' + colors.red(' hello ') + 'R'); }); - it('text will NOT be drawn in color of head style if y == 1',function(){ + it('text will NOT be drawn in color of head style if y == 1', function() { cell.head = ['red']; cell.x = cell.y = 1; expect(cell.draw(0)).toEqual('M hello '); @@ -706,7 +704,7 @@ describe('Cell',function(){ expect(cell.draw(0)).toEqual('M hello R'); }); - it('head and border colors together',function(){ + it('head and border colors together', function() { cell.border = ['gray']; cell.head = ['red']; cell.x = cell.y = 0; @@ -716,26 +714,26 @@ describe('Cell',function(){ }); }); - describe('second line of text',function(){ - beforeEach(function () { + describe('second line of text', function() { + beforeEach(function() { cell.width = 9; }); - it('will draw left side if x=0',function(){ + it('will draw left side if x=0', function() { cell.x = 0; expect(cell.draw(1)).toEqual('L howdy '); cell.drawRight = true; expect(cell.draw(1)).toEqual('L howdy R'); }); - it('will draw mid side if x=1',function(){ + it('will draw mid side if x=1', function() { cell.x = 1; expect(cell.draw(1)).toEqual('M howdy '); cell.drawRight = true; expect(cell.draw(1)).toEqual('M howdy R'); }); - it('will align left',function(){ + it('will align left', function() { cell.x = 1; cell.hAlign = 'left'; expect(cell.draw(1)).toEqual('M howdy '); @@ -743,7 +741,7 @@ describe('Cell',function(){ expect(cell.draw(1)).toEqual('M howdy R'); }); - it('will align right',function(){ + it('will align right', function() { cell.x = 1; cell.hAlign = 'right'; expect(cell.draw(1)).toEqual('M howdy '); @@ -752,26 +750,26 @@ describe('Cell',function(){ }); }); - describe('truncated line of text',function(){ - beforeEach(function () { + describe('truncated line of text', function() { + beforeEach(function() { cell.width = 9; }); - it('will draw left side if x=0',function(){ + it('will draw left side if x=0', function() { cell.x = 0; expect(cell.draw(2)).toEqual('L goodni… '); cell.drawRight = true; expect(cell.draw(2)).toEqual('L goodni… R'); }); - it('will draw mid side if x=1',function(){ + it('will draw mid side if x=1', function() { cell.x = 1; expect(cell.draw(2)).toEqual('M goodni… '); cell.drawRight = true; expect(cell.draw(2)).toEqual('M goodni… R'); }); - it('will not change when aligned left',function(){ + it('will not change when aligned left', function() { cell.x = 1; cell.hAlign = 'left'; expect(cell.draw(2)).toEqual('M goodni… '); @@ -779,7 +777,7 @@ describe('Cell',function(){ expect(cell.draw(2)).toEqual('M goodni… R'); }); - it('will not change when aligned right',function(){ + it('will not change when aligned right', function() { cell.x = 1; cell.hAlign = 'right'; expect(cell.draw(2)).toEqual('M goodni… '); @@ -788,12 +786,12 @@ describe('Cell',function(){ }); }); - describe('vAlign',function(){ - beforeEach(function () { + describe('vAlign', function() { + beforeEach(function() { cell.height = '5'; }); - it('center',function(){ + it('center', function() { cell.vAlign = 'center'; expect(cell.draw(0)).toEqual('L '); expect(cell.draw(1)).toEqual('L hello '); @@ -817,7 +815,7 @@ describe('Cell',function(){ expect(cell.draw(4)).toEqual('M '); }); - it('top',function(){ + it('top', function() { cell.vAlign = 'top'; expect(cell.draw(0)).toEqual('L hello '); expect(cell.draw(1)).toEqual('L howdy '); @@ -842,7 +840,7 @@ describe('Cell',function(){ expect(cell.draw(4)).toEqual('M '); }); - it('center',function(){ + it('center', function() { cell.vAlign = 'bottom'; expect(cell.draw(0)).toEqual('L '); expect(cell.draw(1)).toEqual('L '); @@ -867,71 +865,71 @@ describe('Cell',function(){ }); }); - it('vertically truncated will show truncation on last visible line',function(){ + it('vertically truncated will show truncation on last visible line', function() { cell.height = 2; expect(cell.draw(0)).toEqual('L hello '); expect(cell.draw(1)).toEqual('L howd… '); }); - it("won't vertically truncate if the lines just fit",function(){ + it("won't vertically truncate if the lines just fit", function() { cell.height = 2; - cell.content = "hello\nhowdy"; - cell.lines = cell.content.split("\n"); + cell.content = 'hello\nhowdy'; + cell.lines = cell.content.split('\n'); expect(cell.draw(0)).toEqual('L hello '); expect(cell.draw(1)).toEqual('L howdy '); }); - it("will vertically truncate even if last line is short",function(){ + it('will vertically truncate even if last line is short', function() { cell.height = 2; - cell.content = "hello\nhi\nhowdy"; - cell.lines = cell.content.split("\n"); + cell.content = 'hello\nhi\nhowdy'; + cell.lines = cell.content.split('\n'); expect(cell.draw(0)).toEqual('L hello '); expect(cell.draw(1)).toEqual('L hi… '); }); - it("allows custom truncation",function(){ + it('allows custom truncation', function() { cell.height = 2; cell.truncate = '...'; - cell.content = "hello\nhi\nhowdy"; - cell.lines = cell.content.split("\n"); + cell.content = 'hello\nhi\nhowdy'; + cell.lines = cell.content.split('\n'); expect(cell.draw(0)).toEqual('L hello '); expect(cell.draw(1)).toEqual('L hi... '); - cell.content = "hello\nhowdy\nhi"; - cell.lines = cell.content.split("\n"); + cell.content = 'hello\nhowdy\nhi'; + cell.lines = cell.content.split('\n'); expect(cell.draw(0)).toEqual('L hello '); expect(cell.draw(1)).toEqual('L ho... '); }); }); - describe("ColSpanCell",function(){ - it('has an init function',function(){ + describe('ColSpanCell', function() { + it('has an init function', function() { expect(new ColSpanCell()).toHaveProperty('init'); new ColSpanCell().init(); // nothing happens. }); - it('draw returns an empty string',function(){ + it('draw returns an empty string', function() { expect(new ColSpanCell().draw('top')).toEqual(''); expect(new ColSpanCell().draw('bottom')).toEqual(''); expect(new ColSpanCell().draw(1)).toEqual(''); }); }); - describe("RowSpanCell",function(){ + describe('RowSpanCell', function() { var original, tableOptions; - beforeEach(function () { + beforeEach(function() { original = { - rowSpan:3, - y:0, - draw: jest.fn() + rowSpan: 3, + y: 0, + draw: jest.fn(), }; tableOptions = { - rowHeights:[2,3,4,5] - } + rowHeights: [2, 3, 4, 5], + }; }); - it('drawing top of the next row',function(){ + it('drawing top of the next row', function() { var spanner = new RowSpanCell(original); spanner.x = 0; spanner.y = 1; @@ -941,7 +939,7 @@ describe('Cell',function(){ expect(original.draw).toHaveBeenCalledWith(2, 1); }); - it('drawing line 0 of the next row',function(){ + it('drawing line 0 of the next row', function() { var spanner = new RowSpanCell(original); spanner.x = 0; spanner.y = 1; @@ -951,9 +949,9 @@ describe('Cell',function(){ expect(original.draw).toHaveBeenCalledWith(3); }); - it('drawing line 1 of the next row',function(){ + it('drawing line 1 of the next row', function() { var spanner = new RowSpanCell(original); - spanner.x = 0; + spanner.x = 0; spanner.y = 1; spanner.init(tableOptions); spanner.draw(1); @@ -961,7 +959,7 @@ describe('Cell',function(){ expect(original.draw).toHaveBeenCalledWith(4); }); - it('drawing top of two rows below',function(){ + it('drawing top of two rows below', function() { var spanner = new RowSpanCell(original); spanner.x = 0; spanner.y = 2; @@ -971,7 +969,7 @@ describe('Cell',function(){ expect(original.draw).toHaveBeenCalledWith(6, 2); }); - it('drawing line 0 of two rows below',function(){ + it('drawing line 0 of two rows below', function() { var spanner = new RowSpanCell(original); spanner.x = 0; spanner.y = 2; @@ -981,7 +979,7 @@ describe('Cell',function(){ expect(original.draw).toHaveBeenCalledWith(7); }); - it('drawing line 1 of two rows below',function(){ + it('drawing line 1 of two rows below', function() { var spanner = new RowSpanCell(original); spanner.x = 0; spanner.y = 2; @@ -991,7 +989,7 @@ describe('Cell',function(){ expect(original.draw).toHaveBeenCalledWith(8); }); - it('drawing bottom',function(){ + it('drawing bottom', function() { var spanner = new RowSpanCell(original); spanner.x = 0; spanner.y = 1; diff --git a/test/example-tests.js b/test/example-tests.js index e3ea2a7..d81cfa3 100644 --- a/test/example-tests.js +++ b/test/example-tests.js @@ -2,5 +2,5 @@ var printExamples = require('../lib/print-example'); var examples = require('../examples/col-and-row-span-examples'); var usage = require('../examples/basic-usage-examples'); -printExamples.runTest('@api Usage',usage); -printExamples.runTest('@api Table (examples)',examples); \ No newline at end of file +printExamples.runTest('@api Usage', usage); +printExamples.runTest('@api Table (examples)', examples); diff --git a/test/layout-manager-test.js b/test/layout-manager-test.js index 58ecdae..8dc028d 100644 --- a/test/layout-manager-test.js +++ b/test/layout-manager-test.js @@ -1,4 +1,4 @@ -describe('layout-manager',function(){ +describe('layout-manager', function() { var layoutManager = require('../src/layout-manager'); var layoutTable = layoutManager.layoutTable; var addRowSpanCells = layoutManager.addRowSpanCells; @@ -6,155 +6,133 @@ describe('layout-manager',function(){ var Cell = require('../src/cell'); var RowSpanCell = Cell.RowSpanCell; - describe('layoutTable',function(){ - it('sets x and y',function(){ - var table = [ - [{},{}], - [{},{}] - ]; + describe('layoutTable', function() { + it('sets x and y', function() { + var table = [[{}, {}], [{}, {}]]; layoutTable(table); - expect(table).toEqual([ - [{x:0,y:0},{x:1,y:0}], - [{x:0,y:1},{x:1,y:1}] - ]); + expect(table).toEqual([[{ x: 0, y: 0 }, { x: 1, y: 0 }], [{ x: 0, y: 1 }, { x: 1, y: 1 }]]); var w = maxWidth(table); expect(w).toEqual(2); }); - it('colSpan will push x values to the right',function(){ - var table = [ - [{colSpan:2},{}], - [{},{colSpan:2}] - ]; + it('colSpan will push x values to the right', function() { + var table = [[{ colSpan: 2 }, {}], [{}, { colSpan: 2 }]]; layoutTable(table); expect(table).toEqual([ - [{x:0,y:0,colSpan:2},{x:2,y:0}], - [{x:0,y:1},{x:1,y:1,colSpan:2}] + [{ x: 0, y: 0, colSpan: 2 }, { x: 2, y: 0 }], + [{ x: 0, y: 1 }, { x: 1, y: 1, colSpan: 2 }], ]); expect(maxWidth(table)).toEqual(3); }); - it('rowSpan will push x values on cells below',function(){ - var table = [ - [{rowSpan:2},{}], - [{}] - ]; + it('rowSpan will push x values on cells below', function() { + var table = [[{ rowSpan: 2 }, {}], [{}]]; layoutTable(table); - expect(table).toEqual([ - [{x:0,y:0,rowSpan:2},{x:1,y:0}], - [{x:1,y:1}] - ]); + expect(table).toEqual([[{ x: 0, y: 0, rowSpan: 2 }, { x: 1, y: 0 }], [{ x: 1, y: 1 }]]); expect(maxWidth(table)).toEqual(2); }); - it('colSpan and rowSpan together',function(){ - var table = [ - [{rowSpan:2,colSpan:2},{}], - [{}] - ]; + it('colSpan and rowSpan together', function() { + var table = [[{ rowSpan: 2, colSpan: 2 }, {}], [{}]]; layoutTable(table); - expect(table).toEqual([ - [{x:0,y:0,rowSpan:2,colSpan:2},{x:2,y:0}], - [{x:2,y:1}] - ]); + expect(table).toEqual([[{ x: 0, y: 0, rowSpan: 2, colSpan: 2 }, { x: 2, y: 0 }], [{ x: 2, y: 1 }]]); expect(maxWidth(table)).toEqual(3); }); - it('complex layout',function(){ - + it('complex layout', function() { var table = [ - [{c:'a'},{c:'b'}, {c:'c',rowSpan:3,colSpan:2}, {c:'d'}], - [{c:'e',rowSpan:2,colSpan:2}, {c:'f'}], - [ {c:'g'}] + [{ c: 'a' }, { c: 'b' }, { c: 'c', rowSpan: 3, colSpan: 2 }, { c: 'd' }], + [{ c: 'e', rowSpan: 2, colSpan: 2 }, { c: 'f' }], + [{ c: 'g' }], ]; layoutTable(table); expect(table).toEqual([ - [{c:'a',y:0,x:0}, {c:'b',y:0,x:1}, {c:'c',y:0,x:2,rowSpan:3,colSpan:2}, {c:'d',y:0,x:4}], - [{c:'e',rowSpan:2,colSpan:2,y:1,x:0}, {c:'f',y:1,x:4}], - [{c:'g',y:2,x:4}] + [ + { c: 'a', y: 0, x: 0 }, + { c: 'b', y: 0, x: 1 }, + { c: 'c', y: 0, x: 2, rowSpan: 3, colSpan: 2 }, + { c: 'd', y: 0, x: 4 }, + ], + [{ c: 'e', rowSpan: 2, colSpan: 2, y: 1, x: 0 }, { c: 'f', y: 1, x: 4 }], + [{ c: 'g', y: 2, x: 4 }], ]); - }); - it('maxWidth of single element',function(){ + it('maxWidth of single element', function() { var table = [[{}]]; - layoutTable(table) + layoutTable(table); expect(maxWidth(table)).toEqual(1); }); }); - describe('addRowSpanCells',function(){ - it('will insert a rowSpan cell - beginning of line',function(){ - var table = [ - [{x:0,y:0,rowSpan:2},{x:1,y:0}], - [{x:1,y:1}] - ]; + describe('addRowSpanCells', function() { + it('will insert a rowSpan cell - beginning of line', function() { + var table = [[{ x: 0, y: 0, rowSpan: 2 }, { x: 1, y: 0 }], [{ x: 1, y: 1 }]]; addRowSpanCells(table); - expect(table[0]).toEqual([{x:0,y:0,rowSpan:2},{x:1,y:0}]); + expect(table[0]).toEqual([{ x: 0, y: 0, rowSpan: 2 }, { x: 1, y: 0 }]); expect(table[1].length).toEqual(2); expect(table[1][0]).toBeInstanceOf(RowSpanCell); - expect(table[1][1]).toEqual({x:1,y:1}); + expect(table[1][1]).toEqual({ x: 1, y: 1 }); }); - it('will insert a rowSpan cell - end of line',function(){ - var table = [ - [{x:0,y:0},{x:1,y:0,rowSpan:2}], - [{x:0,y:1}] - ]; + it('will insert a rowSpan cell - end of line', function() { + var table = [[{ x: 0, y: 0 }, { x: 1, y: 0, rowSpan: 2 }], [{ x: 0, y: 1 }]]; addRowSpanCells(table); - expect(table[0]).toEqual([{x:0,y:0},{rowSpan:2,x:1,y:0}]); + expect(table[0]).toEqual([{ x: 0, y: 0 }, { rowSpan: 2, x: 1, y: 0 }]); expect(table[1].length).toEqual(2); - expect(table[1][0]).toEqual({x:0,y:1}); + expect(table[1][0]).toEqual({ x: 0, y: 1 }); expect(table[1][1]).toBeInstanceOf(RowSpanCell); }); - it('will insert a rowSpan cell - middle of line',function(){ - var table = [ - [{x:0,y:0},{x:1,y:0,rowSpan:2},{x:2,y:0}], - [{x:0,y:1},{x:2,y:1}] - ]; + it('will insert a rowSpan cell - middle of line', function() { + var table = [[{ x: 0, y: 0 }, { x: 1, y: 0, rowSpan: 2 }, { x: 2, y: 0 }], [{ x: 0, y: 1 }, { x: 2, y: 1 }]]; addRowSpanCells(table); - expect(table[0]).toEqual([{x:0,y:0},{rowSpan:2,x:1,y:0},{x:2,y:0}]); + expect(table[0]).toEqual([{ x: 0, y: 0 }, { rowSpan: 2, x: 1, y: 0 }, { x: 2, y: 0 }]); expect(table[1].length).toEqual(3); - expect(table[1][0]).toEqual({x:0,y:1}); + expect(table[1][0]).toEqual({ x: 0, y: 1 }); expect(table[1][1]).toBeInstanceOf(RowSpanCell); - expect(table[1][2]).toEqual({x:2,y:1}); + expect(table[1][2]).toEqual({ x: 2, y: 1 }); }); - it('will insert a rowSpan cell - multiple on the same line',function(){ + it('will insert a rowSpan cell - multiple on the same line', function() { var table = [ - [{x:0,y:0},{x:1,y:0,rowSpan:2},{x:2,y:0,rowSpan:2},{x:3,y:0}], - [{x:0,y:1},{x:3,y:1}] + [{ x: 0, y: 0 }, { x: 1, y: 0, rowSpan: 2 }, { x: 2, y: 0, rowSpan: 2 }, { x: 3, y: 0 }], + [{ x: 0, y: 1 }, { x: 3, y: 1 }], ]; addRowSpanCells(table); - expect(table[0]).toEqual([{x:0,y:0},{rowSpan:2,x:1,y:0},{rowSpan:2,x:2,y:0},{x:3,y:0}]); + expect(table[0]).toEqual([ + { x: 0, y: 0 }, + { rowSpan: 2, x: 1, y: 0 }, + { rowSpan: 2, x: 2, y: 0 }, + { x: 3, y: 0 }, + ]); expect(table[1].length).toEqual(4); - expect(table[1][0]).toEqual({x:0,y:1}); + expect(table[1][0]).toEqual({ x: 0, y: 1 }); expect(table[1][1]).toBeInstanceOf(RowSpanCell); expect(table[1][2]).toBeInstanceOf(RowSpanCell); - expect(table[1][3]).toEqual({x:3,y:1}); + expect(table[1][3]).toEqual({ x: 3, y: 1 }); }); }); -}); \ No newline at end of file +}); diff --git a/test/original-cli-table-index-tests.js b/test/original-cli-table-index-tests.js index 178401a..5c4ba95 100644 --- a/test/original-cli-table-index-tests.js +++ b/test/original-cli-table-index-tests.js @@ -1,115 +1,109 @@ -describe('@api original-cli-table index tests',function(){ +describe('@api original-cli-table index tests', function() { var Table = require('../src/table'); - it('test complete table', function (){ - var table = new Table({ - head: ['Rel', 'Change', 'By', 'When'] - , style: { - 'padding-left': 1 - , 'padding-right': 1 - , head: [] - , border: [] - } - , colWidths: [6, 21, 25, 17] - }); - - table.push( - ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '7 minutes ago'] - , ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '8 minutes ago'] - ); - - var expected = [ - '┌──────┬─────────────────────┬─────────────────────────┬─────────────────┐' - , '│ Rel │ Change │ By │ When │' - , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤' - , '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 7 minutes ago │' - , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤' - , '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 8 minutes ago │' - , '└──────┴─────────────────────┴─────────────────────────┴─────────────────┘' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); - //expect(table.render()).should.eql(expected.join("\n")); + it('test complete table', function() { + var table = new Table({ + head: ['Rel', 'Change', 'By', 'When'], + style: { + 'padding-left': 1, + 'padding-right': 1, + head: [], + border: [], + }, + colWidths: [6, 21, 25, 17], }); - it('test width property', function (){ - var table = new Table({ - head: ['Cool'], - style: { - head: [], - border: [] - } - }); - - expect(table.width).toEqual(8); - }); - - it('test vertical table output', function() { - var table = new Table({ style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output - - table.push( - {'v0.1': 'Testing something cool'} - , {'v0.1': 'Testing something cool'} - ); - - var expected = [ - '┌────┬──────────────────────┐' - , '│v0.1│Testing something cool│' - , '├────┼──────────────────────┤' - , '│v0.1│Testing something cool│' - , '└────┴──────────────────────┘' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); + table.push( + ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '7 minutes ago'], + ['v0.1', 'Testing something cool', 'rauchg@gmail.com', '8 minutes ago'] + ); + + var expected = [ + '┌──────┬─────────────────────┬─────────────────────────┬─────────────────┐', + '│ Rel │ Change │ By │ When │', + '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤', + '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 7 minutes ago │', + '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤', + '│ v0.1 │ Testing something … │ rauchg@gmail.com │ 8 minutes ago │', + '└──────┴─────────────────────┴─────────────────────────┴─────────────────┘', + ]; + + expect(table.toString()).toEqual(expected.join('\n')); + //expect(table.render()).should.eql(expected.join("\n")); + }); + + it('test width property', function() { + var table = new Table({ + head: ['Cool'], + style: { + head: [], + border: [], + }, }); - it('test cross table output', function() { - var table = new Table({ head: ["", "Header 1", "Header 2"], style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output - - table.push( - {"Header 3": ['v0.1', 'Testing something cool'] } - , {"Header 4": ['v0.1', 'Testing something cool'] } - ); - - var expected = [ - '┌────────┬────────┬──────────────────────┐' - , '│ │Header 1│Header 2 │' - , '├────────┼────────┼──────────────────────┤' - , '│Header 3│v0.1 │Testing something cool│' - , '├────────┼────────┼──────────────────────┤' - , '│Header 4│v0.1 │Testing something cool│' - , '└────────┴────────┴──────────────────────┘' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); + expect(table.width).toEqual(8); + }); + + it('test vertical table output', function() { + var table = new Table({ style: { 'padding-left': 0, 'padding-right': 0, head: [], border: [] } }); // clear styles to prevent color output + + table.push({ 'v0.1': 'Testing something cool' }, { 'v0.1': 'Testing something cool' }); + + var expected = [ + '┌────┬──────────────────────┐', + '│v0.1│Testing something cool│', + '├────┼──────────────────────┤', + '│v0.1│Testing something cool│', + '└────┴──────────────────────┘', + ]; + + expect(table.toString()).toEqual(expected.join('\n')); + }); + + it('test cross table output', function() { + var table = new Table({ + head: ['', 'Header 1', 'Header 2'], + style: { 'padding-left': 0, 'padding-right': 0, head: [], border: [] }, + }); // clear styles to prevent color output + + table.push({ 'Header 3': ['v0.1', 'Testing something cool'] }, { 'Header 4': ['v0.1', 'Testing something cool'] }); + + var expected = [ + '┌────────┬────────┬──────────────────────┐', + '│ │Header 1│Header 2 │', + '├────────┼────────┼──────────────────────┤', + '│Header 3│v0.1 │Testing something cool│', + '├────────┼────────┼──────────────────────┤', + '│Header 4│v0.1 │Testing something cool│', + '└────────┴────────┴──────────────────────┘', + ]; + + expect(table.toString()).toEqual(expected.join('\n')); + }); + + it('test table colors', function() { + var table = new Table({ + head: ['Rel', 'By'], + style: { head: ['red'], border: ['grey'] }, }); - it('test table colors', function(){ - var table = new Table({ - head: ['Rel', 'By'], - style: {head: ['red'], border: ['grey']} - }); - - /*var off = '' + /*var off = '' , red = '' , orange = '' , grey = ''*/ - var off = '\u001b[39m' - , red = '\u001b[31m' - , orange = '\u001b[38;5;221m' - , grey = '\u001b[90m' - - , c256s = orange + 'v0.1' + off; + var off = '\u001b[39m', + red = '\u001b[31m', + orange = '\u001b[38;5;221m', + grey = '\u001b[90m', + c256s = orange + 'v0.1' + off; - table.push( - [c256s, 'rauchg@gmail.com'] - ); + table.push([c256s, 'rauchg@gmail.com']); - // The expectation from the original cli-table is commented out below. - // The output from cli-table2 will still look the same, but the border color is - // toggled off and back on at the border of each cell. + // The expectation from the original cli-table is commented out below. + // The output from cli-table2 will still look the same, but the border color is + // toggled off and back on at the border of each cell. - /*var expected = [ + /*var expected = [ grey + '┌──────┬──────────────────┐' + off , grey + '│' + off + red + ' Rel ' + off + grey + '│' + off + red + ' By ' + off + grey + '│' + off , grey + '├──────┼──────────────────┤' + off @@ -117,176 +111,145 @@ describe('@api original-cli-table index tests',function(){ , grey + '└──────┴──────────────────┘' + off ];*/ - var expected = [ - grey + '┌──────'+off+grey+'┬──────────────────┐' + off - , grey + '│' + off + red + ' Rel ' + off + grey + '│' + off + red + ' By ' + off + grey + '│' + off - , grey + '├──────'+off+grey+'┼──────────────────┤' + off - , grey + '│' + off + ' ' + c256s + ' ' + grey + '│' + off + ' rauchg@gmail.com ' + grey + '│' + off - , grey + '└──────'+off+grey+'┴──────────────────┘' + off - ]; - - expect(table.toString()).toEqual(expected.join("\n")); + var expected = [ + grey + '┌──────' + off + grey + '┬──────────────────┐' + off, + grey + '│' + off + red + ' Rel ' + off + grey + '│' + off + red + ' By ' + off + grey + '│' + off, + grey + '├──────' + off + grey + '┼──────────────────┤' + off, + grey + '│' + off + ' ' + c256s + ' ' + grey + '│' + off + ' rauchg@gmail.com ' + grey + '│' + off, + grey + '└──────' + off + grey + '┴──────────────────┘' + off, + ]; + + expect(table.toString()).toEqual(expected.join('\n')); + }); + + it('test custom chars', function() { + var table = new Table({ + chars: { + top: '═', + 'top-mid': '╤', + 'top-left': '╔', + 'top-right': '╗', + bottom: '═', + 'bottom-mid': '╧', + 'bottom-left': '╚', + 'bottom-right': '╝', + left: '║', + 'left-mid': '╟', + right: '║', + 'right-mid': '╢', + }, + style: { + head: [], + border: [], + }, }); - it('test custom chars', function (){ - var table = new Table({ - chars: { - 'top': '═' - , 'top-mid': '╤' - , 'top-left': '╔' - , 'top-right': '╗' - , 'bottom': '═' - , 'bottom-mid': '╧' - , 'bottom-left': '╚' - , 'bottom-right': '╝' - , 'left': '║' - , 'left-mid': '╟' - , 'right': '║' - , 'right-mid': '╢' - }, - style: { - head: [] - , border: [] - } - }); - - table.push( - ['foo', 'bar', 'baz'] - , ['frob', 'bar', 'quuz'] - ); - - var expected = [ - '╔══════╤═════╤══════╗' - , '║ foo │ bar │ baz ║' - , '╟──────┼─────┼──────╢' - , '║ frob │ bar │ quuz ║' - , '╚══════╧═════╧══════╝' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); + table.push(['foo', 'bar', 'baz'], ['frob', 'bar', 'quuz']); + + var expected = [ + '╔══════╤═════╤══════╗', + '║ foo │ bar │ baz ║', + '╟──────┼─────┼──────╢', + '║ frob │ bar │ quuz ║', + '╚══════╧═════╧══════╝', + ]; + + expect(table.toString()).toEqual(expected.join('\n')); + }); + + it('test compact shortand', function() { + var table = new Table({ + style: { + head: [], + border: [], + compact: true, + }, }); - it('test compact shortand', function (){ - var table = new Table({ - style: { - head: [] - , border: [] - , compact : true - } - }); - - table.push( - ['foo', 'bar', 'baz'] - , ['frob', 'bar', 'quuz'] - ); - - var expected = [ - '┌──────┬─────┬──────┐' - , '│ foo │ bar │ baz │' - , '│ frob │ bar │ quuz │' - , '└──────┴─────┴──────┘' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); + table.push(['foo', 'bar', 'baz'], ['frob', 'bar', 'quuz']); + + var expected = ['┌──────┬─────┬──────┐', '│ foo │ bar │ baz │', '│ frob │ bar │ quuz │', '└──────┴─────┴──────┘']; + + expect(table.toString()).toEqual(expected.join('\n')); + }); + + it('test compact empty mid line', function() { + var table = new Table({ + chars: { + mid: '', + 'left-mid': '', + 'mid-mid': '', + 'right-mid': '', + }, + style: { + head: [], + border: [], + }, }); - it('test compact empty mid line', function (){ - var table = new Table({ - chars: { - 'mid': '' - , 'left-mid': '' - , 'mid-mid': '' - , 'right-mid': '' - }, - style: { - head: [] - , border: [] - } - }); - - table.push( - ['foo', 'bar', 'baz'] - , ['frob', 'bar', 'quuz'] - ); - - var expected = [ - '┌──────┬─────┬──────┐' - , '│ foo │ bar │ baz │' - , '│ frob │ bar │ quuz │' - , '└──────┴─────┴──────┘' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); + table.push(['foo', 'bar', 'baz'], ['frob', 'bar', 'quuz']); + + var expected = ['┌──────┬─────┬──────┐', '│ foo │ bar │ baz │', '│ frob │ bar │ quuz │', '└──────┴─────┴──────┘']; + + expect(table.toString()).toEqual(expected.join('\n')); + }); + + it('test decoration lines disabled', function() { + var table = new Table({ + chars: { + top: '', + 'top-mid': '', + 'top-left': '', + 'top-right': '', + bottom: '', + 'bottom-mid': '', + 'bottom-left': '', + 'bottom-right': '', + left: '', + 'left-mid': '', + mid: '', + 'mid-mid': '', + right: '', + 'right-mid': '', + middle: ' ', // a single space + }, + style: { + head: [], + border: [], + 'padding-left': 0, + 'padding-right': 0, + }, }); - it('test decoration lines disabled', function (){ - var table = new Table({ - chars: { - 'top': '' - , 'top-mid': '' - , 'top-left': '' - , 'top-right': '' - , 'bottom': '' - , 'bottom-mid': '' - , 'bottom-left': '' - , 'bottom-right': '' - , 'left': '' - , 'left-mid': '' - , 'mid': '' - , 'mid-mid': '' - , 'right': '' - , 'right-mid': '' - , 'middle': ' ' // a single space - }, - style: { - head: [] - , border: [] - , 'padding-left': 0 - , 'padding-right': 0 - } - }); - - table.push( - ['foo', 'bar', 'baz'] - , ['frobnicate', 'bar', 'quuz'] - ); - - var expected = [ - 'foo bar baz ' - , 'frobnicate bar quuz' - ]; - - expect(table.toString()).toEqual(expected.join("\n")); - }); + table.push(['foo', 'bar', 'baz'], ['frobnicate', 'bar', 'quuz']); - it('test with null/undefined as values or column names', function (){ - var table = new Table({ - style: { - head: [] - , border: [] - } - }); + var expected = ['foo bar baz ', 'frobnicate bar quuz']; - table.push( - [null, undefined, 0] - ); + expect(table.toString()).toEqual(expected.join('\n')); + }); - // This is the expectation from the original cli-table. - // The empty columns have widths based on the strings `null` and `undefined` - // That does not make sense to me, so I am deviating from the original behavior here. + it('test with null/undefined as values or column names', function() { + var table = new Table({ + style: { + head: [], + border: [], + }, + }); + + table.push([null, undefined, 0]); - /*var expected = [ + // This is the expectation from the original cli-table. + // The empty columns have widths based on the strings `null` and `undefined` + // That does not make sense to me, so I am deviating from the original behavior here. + + /*var expected = [ '┌──────┬───────────┬───┐' , '│ │ │ 0 │' , '└──────┴───────────┴───┘' ]; */ - var expected = [ - '┌──┬──┬───┐' - , '│ │ │ 0 │' - , '└──┴──┴───┘' - ]; + var expected = ['┌──┬──┬───┐', '│ │ │ 0 │', '└──┴──┴───┘']; - expect(table.toString()).toEqual(expected.join("\n")); - }); + expect(table.toString()).toEqual(expected.join('\n')); + }); }); diff --git a/test/original-cli-table-newlines-test.js b/test/original-cli-table-newlines-test.js index ee28f04..4eacb48 100644 --- a/test/original-cli-table-newlines-test.js +++ b/test/original-cli-table-newlines-test.js @@ -1,84 +1,66 @@ -describe('@api original-cli-table newline tests',function(){ +describe('@api original-cli-table newline tests', function() { var Table = require('../src/table'); it('test table with newlines in headers', function() { var table = new Table({ - head: ['Test', "1\n2\n3"] - , style: { - 'padding-left': 1 - , 'padding-right': 1 - , head: [] - , border: [] - } + head: ['Test', '1\n2\n3'], + style: { + 'padding-left': 1, + 'padding-right': 1, + head: [], + border: [], + }, }); - var expected = [ - '┌──────┬───┐' - , '│ Test │ 1 │' - , '│ │ 2 │' - , '│ │ 3 │' - , '└──────┴───┘' - ]; + var expected = ['┌──────┬───┐', '│ Test │ 1 │', '│ │ 2 │', '│ │ 3 │', '└──────┴───┘']; - expect(table.toString()).toEqual(expected.join("\n")); + expect(table.toString()).toEqual(expected.join('\n')); }); it('test column width is accurately reflected when newlines are present', function() { - var table = new Table({ head: ['Test\nWidth'], style: {head:[], border:[]} }); + var table = new Table({ head: ['Test\nWidth'], style: { head: [], border: [] } }); expect(table.width).toEqual(9); }); it('test newlines in body cells', function() { - var table = new Table({style: {head:[], border:[]}}); + var table = new Table({ style: { head: [], border: [] } }); - table.push(["something\nwith\nnewlines"]); + table.push(['something\nwith\nnewlines']); - var expected = [ - '┌───────────┐' - , '│ something │' - , '│ with │' - , '│ newlines │' - , '└───────────┘' - ]; + var expected = ['┌───────────┐', '│ something │', '│ with │', '│ newlines │', '└───────────┘']; - expect(table.toString()).toEqual(expected.join("\n")); + expect(table.toString()).toEqual(expected.join('\n')); }); it('test newlines in vertical cell header and body', function() { - var table = new Table({ style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); + var table = new Table({ style: { 'padding-left': 0, 'padding-right': 0, head: [], border: [] } }); - table.push( - {'v\n0.1': 'Testing\nsomething cool'} - ); + table.push({ 'v\n0.1': 'Testing\nsomething cool' }); - var expected = [ - '┌───┬──────────────┐' - , '│v │Testing │' - , '│0.1│something cool│' - , '└───┴──────────────┘' - ]; + var expected = ['┌───┬──────────────┐', '│v │Testing │', '│0.1│something cool│', '└───┴──────────────┘']; - expect(table.toString()).toEqual(expected.join("\n")); + expect(table.toString()).toEqual(expected.join('\n')); }); it('test newlines in cross table header and body', function() { - var table = new Table({ head: ["", "Header\n1"], style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); + var table = new Table({ + head: ['', 'Header\n1'], + style: { 'padding-left': 0, 'padding-right': 0, head: [], border: [] }, + }); - table.push({ "Header\n2": ['Testing\nsomething\ncool'] }); + table.push({ 'Header\n2': ['Testing\nsomething\ncool'] }); var expected = [ - '┌──────┬─────────┐' - , '│ │Header │' - , '│ │1 │' - , '├──────┼─────────┤' - , '│Header│Testing │' - , '│2 │something│' - , '│ │cool │' - , '└──────┴─────────┘' + '┌──────┬─────────┐', + '│ │Header │', + '│ │1 │', + '├──────┼─────────┤', + '│Header│Testing │', + '│2 │something│', + '│ │cool │', + '└──────┴─────────┘', ]; - expect(table.toString()).toEqual(expected.join("\n")); + expect(table.toString()).toEqual(expected.join('\n')); }); - }); - diff --git a/test/table-layout-test.js b/test/table-layout-test.js index 182a63c..3f61167 100644 --- a/test/table-layout-test.js +++ b/test/table-layout-test.js @@ -1,4 +1,4 @@ -describe('tableLayout', function () { +describe('tableLayout', function() { var Cell = require('../src/cell'); var layoutManager = require('../src/layout-manager'); var makeTableLayout = layoutManager.makeTableLayout; @@ -8,212 +8,150 @@ describe('tableLayout', function () { var computeHeights = layoutManager.computeHeights; var kindOf = require('kind-of'); - it('simple 2x2 layout',function(){ - var actual = makeTableLayout([ - ['hello','goodbye'], - ['hola','adios'] - ]); + it('simple 2x2 layout', function() { + var actual = makeTableLayout([['hello', 'goodbye'], ['hola', 'adios']]); - var expected = [ - ['hello','goodbye'], - ['hola','adios'] - ]; + var expected = [['hello', 'goodbye'], ['hola', 'adios']]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('cross table',function(){ - var actual = makeTableLayout([ - {'1.0':['yes','no']}, - {'2.0':['hello','goodbye']} - ]); + it('cross table', function() { + var actual = makeTableLayout([{ '1.0': ['yes', 'no'] }, { '2.0': ['hello', 'goodbye'] }]); - var expected = [ - ['1.0','yes','no'], - ['2.0','hello','goodbye'] - ]; + var expected = [['1.0', 'yes', 'no'], ['2.0', 'hello', 'goodbye']]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('vertical table',function(){ - var actual = makeTableLayout([ - {'1.0':'yes'}, - {'2.0':'hello'} - ]); + it('vertical table', function() { + var actual = makeTableLayout([{ '1.0': 'yes' }, { '2.0': 'hello' }]); - var expected = [ - ['1.0','yes'], - ['2.0','hello'] - ]; + var expected = [['1.0', 'yes'], ['2.0', 'hello']]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('colSpan adds RowSpanCells to the right',function(){ - var actual = makeTableLayout([ - [{content:'hello',colSpan:2}], - ['hola','adios'] - ]); + it('colSpan adds RowSpanCells to the right', function() { + var actual = makeTableLayout([[{ content: 'hello', colSpan: 2 }], ['hola', 'adios']]); - var expected = [ - [{content:'hello',colSpan:2},null], - ['hola','adios'] - ]; + var expected = [[{ content: 'hello', colSpan: 2 }, null], ['hola', 'adios']]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('rowSpan adds RowSpanCell below',function(){ - var actual = makeTableLayout([ - [{content:'hello',rowSpan:2},'goodbye'], - ['adios'] - ]); + it('rowSpan adds RowSpanCell below', function() { + var actual = makeTableLayout([[{ content: 'hello', rowSpan: 2 }, 'goodbye'], ['adios']]); - var expected = [ - ['hello' , 'goodbye'], - [{spannerFor:[0,0]} , 'adios'] - ]; + var expected = [['hello', 'goodbye'], [{ spannerFor: [0, 0] }, 'adios']]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('rowSpan and cellSpan together',function(){ - var actual = makeTableLayout([ - [{content:'hello',rowSpan:2,colSpan:2},'goodbye'], - ['adios'] - ]); + it('rowSpan and cellSpan together', function() { + var actual = makeTableLayout([[{ content: 'hello', rowSpan: 2, colSpan: 2 }, 'goodbye'], ['adios']]); - var expected = [ - ['hello' , null, 'goodbye'], - [{spannerFor:[0,0]} , null, 'adios'] - ]; + var expected = [['hello', null, 'goodbye'], [{ spannerFor: [0, 0] }, null, 'adios']]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('complex layout',function(){ + it('complex layout', function() { var actual = makeTableLayout([ - [{content:'hello',rowSpan:2,colSpan:2},{content:'yo',rowSpan:2,colSpan:2},'goodbye'], - ['adios'] + [{ content: 'hello', rowSpan: 2, colSpan: 2 }, { content: 'yo', rowSpan: 2, colSpan: 2 }, 'goodbye'], + ['adios'], ]); var expected = [ - ['hello' , null, 'yo' , null, 'goodbye'], - [{spannerFor:[0,0]} , null, {spannerFor:[0,2]} , null, 'adios'] + ['hello', null, 'yo', null, 'goodbye'], + [{ spannerFor: [0, 0] }, null, { spannerFor: [0, 2] }, null, 'adios'], ]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('complex layout2',function(){ + it('complex layout2', function() { var actual = makeTableLayout([ - ['a','b', {content:'c',rowSpan:3,colSpan:2},'d'], - [{content:'e',rowSpan:2,colSpan:2}, 'f'], - ['g'] + ['a', 'b', { content: 'c', rowSpan: 3, colSpan: 2 }, 'd'], + [{ content: 'e', rowSpan: 2, colSpan: 2 }, 'f'], + ['g'], ]); var expected = [ - ['a', 'b', 'c', null, 'd'], - ['e', null, {spannerFor:[0,2]}, null, 'f'], - [{spannerFor:[1,0]}, null, {spannerFor:[0,2]}, null, 'g'] + ['a', 'b', 'c', null, 'd'], + ['e', null, { spannerFor: [0, 2] }, null, 'f'], + [{ spannerFor: [1, 0] }, null, { spannerFor: [0, 2] }, null, 'g'], ]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - it('stairstep spans',function(){ - var actual = makeTableLayout([ - [{content:'',rowSpan:2},''], - [{content:'',rowSpan:2}], - [''] - ]); + it('stairstep spans', function() { + var actual = makeTableLayout([[{ content: '', rowSpan: 2 }, ''], [{ content: '', rowSpan: 2 }], ['']]); var expected = [ - [{content:'',rowSpan:2}, ''], - [{spannerFor:[0,0]},{content:'',rowSpan:2}], - ['',{spannerFor:[1,1]}] + [{ content: '', rowSpan: 2 }, ''], + [{ spannerFor: [0, 0] }, { content: '', rowSpan: 2 }], + ['', { spannerFor: [1, 1] }], ]; - checkLayout(actual,expected); + checkLayout(actual, expected); }); - describe('fillInTable',function(){ - function mc(opts,y,x){ + describe('fillInTable', function() { + function mc(opts, y, x) { var cell = new Cell(opts); cell.x = x; cell.y = y; return cell; } - it('will blank out individual cells',function(){ - var cells = [ - [mc('a',0,1)], - [mc('b',1,0)] - ]; + it('will blank out individual cells', function() { + var cells = [[mc('a', 0, 1)], [mc('b', 1, 0)]]; fillInTable(cells); - checkLayout(cells,[ - ['', 'a'], - ['b', ''] - ]); + checkLayout(cells, [['', 'a'], ['b', '']]); }); - it('will autospan to the right',function(){ - var cells = [ - [], - [mc('a',1,1)] - ]; + it('will autospan to the right', function() { + var cells = [[], [mc('a', 1, 1)]]; fillInTable(cells); - checkLayout(cells,[ - [{content:'',colSpan:2}, null], - ['', 'a'] - ]); + checkLayout(cells, [[{ content: '', colSpan: 2 }, null], ['', 'a']]); }); - it('will autospan down',function(){ - var cells = [ - [ mc('a',0,1)], - [] - ]; + it('will autospan down', function() { + var cells = [[mc('a', 0, 1)], []]; fillInTable(cells); addRowSpanCells(cells); - checkLayout(cells,[ - [{content:'',rowSpan:2}, 'a'], - [{spannerFor:[0,0]}, ''] - ]); + checkLayout(cells, [[{ content: '', rowSpan: 2 }, 'a'], [{ spannerFor: [0, 0] }, '']]); }); - it('will autospan right and down',function(){ - var cells = [ - [ mc('a',0,2)], - [], - [ mc('b',2,1)] - ]; + it('will autospan right and down', function() { + var cells = [[mc('a', 0, 2)], [], [mc('b', 2, 1)]]; fillInTable(cells); addRowSpanCells(cells); - checkLayout(cells,[ - [{content:'',colSpan:2, rowSpan:2}, null, 'a'], - [{spannerFor:[0,0]}, null, {content:'', colSpan:1, rowSpan:2}], - ['','b',{spannerFor:[1,2]}] + checkLayout(cells, [ + [{ content: '', colSpan: 2, rowSpan: 2 }, null, 'a'], + [{ spannerFor: [0, 0] }, null, { content: '', colSpan: 1, rowSpan: 2 }], + ['', 'b', { spannerFor: [1, 2] }], ]); }); }); - describe('computeWidths',function() { - function mc(y,x,desiredWidth, colSpan) { - return {x:x,y:y,desiredWidth:desiredWidth,colSpan:colSpan}; + describe('computeWidths', function() { + function mc(y, x, desiredWidth, colSpan) { + return { x: x, y: y, desiredWidth: desiredWidth, colSpan: colSpan }; } - it('finds the maximum desired width of each column', function () { + it('finds the maximum desired width of each column', function() { var widths = []; var cells = [ - [mc(0,0,7), mc(0,1,3), mc(0,2,5)], - [mc(1,0,8), mc(1,1,5), mc(1,2,2)], - [mc(2,0,6), mc(2,1,9), mc(2,2,1)] + [mc(0, 0, 7), mc(0, 1, 3), mc(0, 2, 5)], + [mc(1, 0, 8), mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 6), mc(2, 1, 9), mc(2, 2, 1)], ]; computeWidths(widths, cells); @@ -221,12 +159,12 @@ describe('tableLayout', function () { expect(widths).toEqual([8, 9, 5]); }); - it('won\'t touch hard coded values', function () { + it("won't touch hard coded values", function() { var widths = [null, 3]; var cells = [ - [mc(0,0,7), mc(0,1,3), mc(0,2,5)], - [mc(1,0,8), mc(1,1,5), mc(1,2,2)], - [mc(2,0,6), mc(2,1,9), mc(2,2,1)] + [mc(0, 0, 7), mc(0, 1, 3), mc(0, 2, 5)], + [mc(1, 0, 8), mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 6), mc(2, 1, 9), mc(2, 2, 1)], ]; computeWidths(widths, cells); @@ -234,158 +172,136 @@ describe('tableLayout', function () { expect(widths).toEqual([8, 3, 5]); }); - it('assumes undefined desiredWidth is 1', function () { + it('assumes undefined desiredWidth is 1', function() { var widths = []; - var cells = [[{x:0,y:0}], [{x:0,y:1}], [{x:0,y:2}]]; + var cells = [[{ x: 0, y: 0 }], [{ x: 0, y: 1 }], [{ x: 0, y: 2 }]]; computeWidths(widths, cells); - expect(widths).toEqual([1]) + expect(widths).toEqual([1]); }); - it('takes into account colSpan and wont over expand', function () { + it('takes into account colSpan and wont over expand', function() { var widths = []; var cells = [ - [mc(0,0,10, 2), mc(0,2,5)], - [mc(1,0,5), mc(1,1,5), mc(1,2,2)], - [mc(2,0,4), mc(2,1,2), mc(2,2,1)] + [mc(0, 0, 10, 2), mc(0, 2, 5)], + [mc(1, 0, 5), mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 4), mc(2, 1, 2), mc(2, 2, 1)], ]; computeWidths(widths, cells); expect(widths).toEqual([5, 5, 5]); }); - it('will expand rows involved in colSpan in a balanced way', function () { + it('will expand rows involved in colSpan in a balanced way', function() { var widths = []; var cells = [ - [mc(0,0,13,2), mc(0,2,5)], - [mc(1,0,5), mc(1,1,5), mc(1,2,2)], - [mc(2,0,4), mc(2,1,2), mc(2,2,1)] + [mc(0, 0, 13, 2), mc(0, 2, 5)], + [mc(1, 0, 5), mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 4), mc(2, 1, 2), mc(2, 2, 1)], ]; computeWidths(widths, cells); expect(widths).toEqual([6, 6, 5]); }); - it('expands across 3 cols', function () { + it('expands across 3 cols', function() { var widths = []; - var cells = [ - [mc(0,0,25,3) ], - [mc(1,0,5), mc(1,1,5), mc(1,2,2) ], - [mc(2,0,4), mc(2,1,2), mc(2,2,1) ] - ]; + var cells = [[mc(0, 0, 25, 3)], [mc(1, 0, 5), mc(1, 1, 5), mc(1, 2, 2)], [mc(2, 0, 4), mc(2, 1, 2), mc(2, 2, 1)]]; computeWidths(widths, cells); expect(widths).toEqual([9, 9, 5]); }); - it('multiple spans in same table', function () { + it('multiple spans in same table', function() { var widths = []; - var cells = [ - [mc(0,0,25,3) ], - [mc(1,0,30,3) ], - [mc(2,0,4), mc(2,1,2), mc(2,2,1) ] - ]; + var cells = [[mc(0, 0, 25, 3)], [mc(1, 0, 30, 3)], [mc(2, 0, 4), mc(2, 1, 2), mc(2, 2, 1)]]; computeWidths(widths, cells); expect(widths).toEqual([11, 9, 8]); }); - it('spans will only edit uneditable tables',function(){ + it('spans will only edit uneditable tables', function() { var widths = [null, 3]; - var cells = [ - [mc(0,0,20,3) ], - [mc(1,0,4), mc(1,1,20), mc(1,2,5) ] - ]; + var cells = [[mc(0, 0, 20, 3)], [mc(1, 0, 4), mc(1, 1, 20), mc(1, 2, 5)]]; computeWidths(widths, cells); - expect(widths).toEqual([7,3,8]) + expect(widths).toEqual([7, 3, 8]); }); - it('spans will only edit uneditable tables - first column uneditable',function(){ + it('spans will only edit uneditable tables - first column uneditable', function() { var widths = [3]; - var cells = [ - [mc(0,0,20,3) ], - [mc(1,0,4), mc(1,1,3), mc(1,2,5) ] - ]; + var cells = [[mc(0, 0, 20, 3)], [mc(1, 0, 4), mc(1, 1, 3), mc(1, 2, 5)]]; computeWidths(widths, cells); - expect(widths).toEqual([3,7,8]) + expect(widths).toEqual([3, 7, 8]); }); }); - - describe('computeHeights',function(){ - function mc(y,x,desiredHeight,colSpan){ - return {x:x,y:y,desiredHeight:desiredHeight,rowSpan:colSpan}; + + describe('computeHeights', function() { + function mc(y, x, desiredHeight, colSpan) { + return { x: x, y: y, desiredHeight: desiredHeight, rowSpan: colSpan }; } - it('finds the maximum desired height of each row',function(){ + it('finds the maximum desired height of each row', function() { var heights = []; var cells = [ - [mc(0,0,7), mc(0,1,3), mc(0,2,5) ], - [mc(1,0,8), mc(1,1,5), mc(1,2,2) ], - [mc(2,0,6), mc(2,1,9), mc(2,2,1) ] + [mc(0, 0, 7), mc(0, 1, 3), mc(0, 2, 5)], + [mc(1, 0, 8), mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 6), mc(2, 1, 9), mc(2, 2, 1)], ]; - computeHeights(heights,cells); + computeHeights(heights, cells); - expect(heights).toEqual([7,8,9]); + expect(heights).toEqual([7, 8, 9]); }); - it('won\'t touch hard coded values',function(){ - var heights = [null,3]; + it("won't touch hard coded values", function() { + var heights = [null, 3]; var cells = [ - [mc(0,0,7), mc(0,1,3), mc(0,2,5)], - [mc(1,0,8), mc(1,1,5), mc(1,2,2)], - [mc(2,0,6), mc(2,1,9), mc(2,2,1)] + [mc(0, 0, 7), mc(0, 1, 3), mc(0, 2, 5)], + [mc(1, 0, 8), mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 6), mc(2, 1, 9), mc(2, 2, 1)], ]; - computeHeights(heights,cells); + computeHeights(heights, cells); - expect(heights).toEqual([7,3,9]); + expect(heights).toEqual([7, 3, 9]); }); - it('assumes undefined desiredHeight is 1',function(){ + it('assumes undefined desiredHeight is 1', function() { var heights = []; - var cells = [[{x:0,y:0},{x:1,y:0},{x:2,y:0}]]; - computeHeights(heights,cells); - expect(heights).toEqual([1]) + var cells = [[{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }]]; + computeHeights(heights, cells); + expect(heights).toEqual([1]); }); - it('takes into account rowSpan and wont over expand',function(){ + it('takes into account rowSpan and wont over expand', function() { var heights = []; var cells = [ - [mc(0,0,10,2), mc(0,1,5), mc(0,2,2)], - [ mc(1,1,5), mc(1,2,2)], - [mc(2,0,4), mc(2,1,2), mc(2,2,1)] + [mc(0, 0, 10, 2), mc(0, 1, 5), mc(0, 2, 2)], + [mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 4), mc(2, 1, 2), mc(2, 2, 1)], ]; - computeHeights(heights,cells); - expect(heights).toEqual([5,5,4]); + computeHeights(heights, cells); + expect(heights).toEqual([5, 5, 4]); }); - it('will expand rows involved in rowSpan in a balanced way',function(){ + it('will expand rows involved in rowSpan in a balanced way', function() { var heights = []; var cells = [ - [mc(0,0,13,2), mc(0,1,5), mc(0,2,5)], - [ mc(1,1,5), mc(1,2,2)], - [mc(2,0,4), mc(2,1,2), mc(2,2,1)] + [mc(0, 0, 13, 2), mc(0, 1, 5), mc(0, 2, 5)], + [mc(1, 1, 5), mc(1, 2, 2)], + [mc(2, 0, 4), mc(2, 1, 2), mc(2, 2, 1)], ]; - computeHeights(heights,cells); - expect(heights).toEqual([6,6,4]); + computeHeights(heights, cells); + expect(heights).toEqual([6, 6, 4]); }); - it('expands across 3 rows',function(){ + it('expands across 3 rows', function() { var heights = []; - var cells = [ - [mc(0,0,25,3), mc(0,1,5), mc(0,2,4)], - [ mc(1,1,5), mc(1,2,2)], - [ mc(2,1,2), mc(2,2,1)] - ]; - computeHeights(heights,cells); - expect(heights).toEqual([9,9,5]); + var cells = [[mc(0, 0, 25, 3), mc(0, 1, 5), mc(0, 2, 4)], [mc(1, 1, 5), mc(1, 2, 2)], [mc(2, 1, 2), mc(2, 2, 1)]]; + computeHeights(heights, cells); + expect(heights).toEqual([9, 9, 5]); }); - it('multiple spans in same table',function(){ + it('multiple spans in same table', function() { var heights = []; - var cells = [ - [mc(0,0,25,3), mc(0,1,30,3), mc(0,2,4)], - [ mc(1,2,2)], - [ mc(2,2,1)] - ]; - computeHeights(heights,cells); - expect(heights).toEqual([11,9,8]); + var cells = [[mc(0, 0, 25, 3), mc(0, 1, 30, 3), mc(0, 2, 4)], [mc(1, 2, 2)], [mc(2, 2, 1)]]; + computeHeights(heights, cells); + expect(heights).toEqual([11, 9, 8]); }); }); @@ -409,52 +325,51 @@ describe('tableLayout', function () { * @param expectedRows - a table of shorthand assertions. */ - function checkLayout(actualTable,expectedTable){ - expectedTable.forEach(function(expectedRow,y){ - expectedRow.forEach(function(expectedCell,x){ - if(expectedCell !== null){ - var actualCell = findCell(actualTable,x,y); - checkExpectation(actualCell,expectedCell,x,y,actualTable); + function checkLayout(actualTable, expectedTable) { + expectedTable.forEach(function(expectedRow, y) { + expectedRow.forEach(function(expectedCell, x) { + if (expectedCell !== null) { + var actualCell = findCell(actualTable, x, y); + checkExpectation(actualCell, expectedCell, x, y, actualTable); } }); }); } - function findCell(table,x,y){ - for(var i = 0; i < table.length; i++){ + function findCell(table, x, y) { + for (var i = 0; i < table.length; i++) { var row = table[i]; - for(var j = 0; j < row.length; j++){ + for (var j = 0; j < row.length; j++) { var cell = row[j]; - if(cell.x === x && cell.y === y){ + if (cell.x === x && cell.y === y) { return cell; } } } } - function checkExpectation(actualCell,expectedCell,x,y,actualTable){ - if(kindOf(expectedCell) === 'string'){ - expectedCell = {content:expectedCell}; + function checkExpectation(actualCell, expectedCell, x, y, actualTable) { + if (kindOf(expectedCell) === 'string') { + expectedCell = { content: expectedCell }; } - if(expectedCell.hasOwnProperty('content')){ + if (expectedCell.hasOwnProperty('content')) { expect(actualCell).toBeInstanceOf(Cell); expect(actualCell.content).toEqual(expectedCell.content); } - if(expectedCell.hasOwnProperty('rowSpan')){ + if (expectedCell.hasOwnProperty('rowSpan')) { expect(actualCell).toBeInstanceOf(Cell); expect(actualCell.rowSpan).toEqual(expectedCell.rowSpan); } - if(expectedCell.hasOwnProperty('colSpan')){ + if (expectedCell.hasOwnProperty('colSpan')) { expect(actualCell).toBeInstanceOf(Cell); expect(actualCell.colSpan).toEqual(expectedCell.colSpan); } - if(expectedCell.hasOwnProperty('spannerFor')){ + if (expectedCell.hasOwnProperty('spannerFor')) { expect(actualCell).toBeInstanceOf(Cell.RowSpanCell); expect(actualCell.originalCell).toBeInstanceOf(Cell); - expect(actualCell.originalCell).toEqual(findCell(actualTable, - expectedCell.spannerFor[1], - expectedCell.spannerFor[0] - )); + expect(actualCell.originalCell).toEqual( + findCell(actualTable, expectedCell.spannerFor[1], expectedCell.spannerFor[0]) + ); //TODO: retest here x,y coords } } diff --git a/test/table-test.js b/test/table-test.js index 77472dd..1705d81 100644 --- a/test/table-test.js +++ b/test/table-test.js @@ -1,75 +1,69 @@ -describe('@api Table ',function(){ +describe('@api Table ', function() { var Table = require('..'); var colors = require('colors/safe'); - it('wordWrap with colored text',function(){ - var table = new Table({style:{border:[],head:[]},wordWrap:true,colWidths:[7,9]}); + it('wordWrap with colored text', function() { + var table = new Table({ style: { border: [], head: [] }, wordWrap: true, colWidths: [7, 9] }); - table.push([colors.red('Hello how are you?'),colors.blue('I am fine thanks!')]); + table.push([colors.red('Hello how are you?'), colors.blue('I am fine thanks!')]); var expected = [ - '┌───────┬─────────┐' - , '│ ' + colors.red('Hello') + ' │ ' + colors.blue('I am') + ' │' - , '│ ' + colors.red('how') + ' │ ' + colors.blue('fine') + ' │' - , '│ ' + colors.red('are') + ' │ ' + colors.blue('thanks!') + ' │' - , '│ ' + colors.red('you?') + ' │ │' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│ ' + colors.red('Hello') + ' │ ' + colors.blue('I am') + ' │', + '│ ' + colors.red('how') + ' │ ' + colors.blue('fine') + ' │', + '│ ' + colors.red('are') + ' │ ' + colors.blue('thanks!') + ' │', + '│ ' + colors.red('you?') + ' │ │', + '└───────┴─────────┘', ]; expect(table.toString()).toEqual(expected.join('\n')); }); it('allows numbers as `content` property of cells defined using object notation', function() { - var table = new Table({style:{border:[],head:[]}}); + var table = new Table({ style: { border: [], head: [] } }); - table.push([{content: 12}]); + table.push([{ content: 12 }]); - var expected = [ - '┌────┐' - , '│ 12 │' - , '└────┘' - ]; + var expected = ['┌────┐', '│ 12 │', '└────┘']; expect(table.toString()).toEqual(expected.join('\n')); }); it('throws if content is not a string or number', function() { - var table = new Table({style:{border:[],head:[]}}); + var table = new Table({ style: { border: [], head: [] } }); expect(function() { - table.push([{content: {a:'b'}}]); + table.push([{ content: { a: 'b' } }]); table.toString(); }).toThrow(); - }); - it('works with CJK values', function () { - var table = new Table({style: {border:[],head:[]}, colWidths: [5, 10, 5]}); + it('works with CJK values', function() { + var table = new Table({ style: { border: [], head: [] }, colWidths: [5, 10, 5] }); table.push( - ['foobar', 'English test', 'baz'] - , ['foobar', '中文测试', 'baz'] - , ['foobar', '日本語テスト', 'baz'] - , ['foobar', '한국어테스트', 'baz'] + ['foobar', 'English test', 'baz'], + ['foobar', '中文测试', 'baz'], + ['foobar', '日本語テスト', 'baz'], + ['foobar', '한국어테스트', 'baz'] ); var expected = [ - '┌─────┬──────────┬─────┐' - , '│ fo… │ English… │ baz │' - , '├─────┼──────────┼─────┤' - , '│ fo… │ 中文测试 │ baz │' - , '├─────┼──────────┼─────┤' - , '│ fo… │ 日本語… │ baz │' - , '├─────┼──────────┼─────┤' - , '│ fo… │ 한국어… │ baz │' - , '└─────┴──────────┴─────┘' + '┌─────┬──────────┬─────┐', + '│ fo… │ English… │ baz │', + '├─────┼──────────┼─────┤', + '│ fo… │ 中文测试 │ baz │', + '├─────┼──────────┼─────┤', + '│ fo… │ 日本語… │ baz │', + '├─────┼──────────┼─────┤', + '│ fo… │ 한국어… │ baz │', + '└─────┴──────────┴─────┘', ]; - expect(table.toString()).toEqual(expected.join("\n")); + expect(table.toString()).toEqual(expected.join('\n')); }); }); - /* var expected = [ diff --git a/test/utils-test.js b/test/utils-test.js index 4a02690..2333830 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -1,4 +1,4 @@ -describe('utils',function(){ +describe('utils', function() { var colors = require('colors/safe'); var utils = require('../src/utils'); @@ -9,404 +9,375 @@ describe('utils',function(){ var mergeOptions = utils.mergeOptions; var wordWrap = utils.wordWrap; - - describe('strlen',function(){ - it('length of "hello" is 5',function(){ + describe('strlen', function() { + it('length of "hello" is 5', function() { expect(strlen('hello')).toEqual(5); }); - it('length of "hi" is 2',function(){ + it('length of "hi" is 2', function() { expect(strlen('hi')).toEqual(2); }); - it('length of "hello" in red is 5',function(){ + it('length of "hello" in red is 5', function() { expect(strlen(colors.red('hello'))).toEqual(5); }); - it('length of "hello" in zebra is 5',function(){ + it('length of "hello" in zebra is 5', function() { expect(strlen(colors.zebra('hello'))).toEqual(5); }); - it('length of "hello\\nhi\\nheynow" is 6',function(){ + it('length of "hello\\nhi\\nheynow" is 6', function() { expect(strlen('hello\nhi\nheynow')).toEqual(6); }); - it('length of "中文字符" is 8',function(){ + it('length of "中文字符" is 8', function() { expect(strlen('中文字符')).toEqual(8); }); - it('length of "日本語の文字" is 12',function(){ + it('length of "日本語の文字" is 12', function() { expect(strlen('日本語の文字')).toEqual(12); }); - it('length of "한글" is 4',function(){ + it('length of "한글" is 4', function() { expect(strlen('한글')).toEqual(4); }); }); - describe('repeat',function(){ - it('"-" x 3',function(){ - expect(repeat('-',3)).toEqual('---'); + describe('repeat', function() { + it('"-" x 3', function() { + expect(repeat('-', 3)).toEqual('---'); }); - it('"-" x 4',function(){ - expect(repeat('-',4)).toEqual('----'); + it('"-" x 4', function() { + expect(repeat('-', 4)).toEqual('----'); }); - it('"=" x 4',function(){ - expect(repeat('=',4)).toEqual('===='); + it('"=" x 4', function() { + expect(repeat('=', 4)).toEqual('===='); }); }); - describe('pad',function(){ - it("pad('hello',6,' ', right) == ' hello'", function () { - expect(pad('hello',6,' ','right')).toEqual(' hello'); + describe('pad', function() { + it("pad('hello',6,' ', right) == ' hello'", function() { + expect(pad('hello', 6, ' ', 'right')).toEqual(' hello'); }); - it("pad('hello',7,' ', left) == 'hello '", function () { - expect(pad('hello',7,' ','left')).toEqual('hello '); + it("pad('hello',7,' ', left) == 'hello '", function() { + expect(pad('hello', 7, ' ', 'left')).toEqual('hello '); }); - it("pad('hello',8,' ', center) == ' hello '", function () { - expect(pad('hello',8,' ','center')).toEqual(' hello '); + it("pad('hello',8,' ', center) == ' hello '", function() { + expect(pad('hello', 8, ' ', 'center')).toEqual(' hello '); }); - it("pad('hello',9,' ', center) == ' hello '", function () { - expect(pad('hello',9,' ','center')).toEqual(' hello '); + it("pad('hello',9,' ', center) == ' hello '", function() { + expect(pad('hello', 9, ' ', 'center')).toEqual(' hello '); }); - it("pad('yo',4,' ', center) == ' yo '", function () { - expect(pad('yo',4,' ','center')).toEqual(' yo '); + it("pad('yo',4,' ', center) == ' yo '", function() { + expect(pad('yo', 4, ' ', 'center')).toEqual(' yo '); }); - it('pad red(hello)', function(){ - expect(pad(colors.red('hello'),7,' ','right')).toEqual(' ' + colors.red('hello')); + it('pad red(hello)', function() { + expect(pad(colors.red('hello'), 7, ' ', 'right')).toEqual(' ' + colors.red('hello')); }); - it("pad('hello', 2, ' ', right) == 'hello'", function(){ + it("pad('hello', 2, ' ', right) == 'hello'", function() { expect(pad('hello', 2, ' ', 'right')).toEqual('hello'); }); }); - describe('truncate',function(){ - it('truncate("hello", 5) === "hello"',function(){ - expect(truncate('hello',5)).toEqual('hello'); + describe('truncate', function() { + it('truncate("hello", 5) === "hello"', function() { + expect(truncate('hello', 5)).toEqual('hello'); }); - it('truncate("hello sir", 7, "…") == "hello …"',function(){ + it('truncate("hello sir", 7, "…") == "hello …"', function() { expect(truncate('hello sir', 7, '…')).toEqual('hello …'); }); - it('truncate("hello sir", 6, "…") == "hello…"',function(){ + it('truncate("hello sir", 6, "…") == "hello…"', function() { expect(truncate('hello sir', 6, '…')).toEqual('hello…'); }); - it('truncate("goodnight moon", 8, "…") == "goodnig…"',function(){ + it('truncate("goodnight moon", 8, "…") == "goodnig…"', function() { expect(truncate('goodnight moon', 8, '…')).toEqual('goodnig…'); }); - it('truncate(colors.zebra("goodnight moon"), 15, "…") == colors.zebra("goodnight moon")',function(){ + it('truncate(colors.zebra("goodnight moon"), 15, "…") == colors.zebra("goodnight moon")', function() { var original = colors.zebra('goodnight moon'); expect(truncate(original, 15, '…')).toEqual(original); }); - it('truncate(colors.zebra("goodnight moon"), 8, "…") == colors.zebra("goodnig") + "…"',function(){ + it('truncate(colors.zebra("goodnight moon"), 8, "…") == colors.zebra("goodnig") + "…"', function() { var original = colors.zebra('goodnight moon'); var expected = colors.zebra('goodnig') + '…'; expect(truncate(original, 8, '…')).toEqual(expected); }); - it('truncate(colors.zebra("goodnight moon"), 9, "…") == colors.zebra("goodnig") + "…"',function(){ + it('truncate(colors.zebra("goodnight moon"), 9, "…") == colors.zebra("goodnig") + "…"', function() { var original = colors.zebra('goodnight moon'); var expected = colors.zebra('goodnigh') + '…'; expect(truncate(original, 9, '…')).toEqual(expected); }); - it('red(hello) + green(world) truncated to 9 chars',function(){ + it('red(hello) + green(world) truncated to 9 chars', function() { var original = colors.red('hello') + colors.green(' world'); var expected = colors.red('hello') + colors.green(' wo') + '…'; expect(truncate(original, 9)).toEqual(expected); }); - it('red-on-green(hello) + green-on-red(world) truncated to 9 chars',function(){ + it('red-on-green(hello) + green-on-red(world) truncated to 9 chars', function() { var original = colors.red.bgGreen('hello') + colors.green.bgRed(' world'); var expected = colors.red.bgGreen('hello') + colors.green.bgRed(' wo') + '…'; - expect(truncate(original,9)).toEqual(expected); + expect(truncate(original, 9)).toEqual(expected); }); - it('red-on-green(hello) + green-on-red(world) truncated to 10 chars - using inverse',function(){ + it('red-on-green(hello) + green-on-red(world) truncated to 10 chars - using inverse', function() { var original = colors.red.bgGreen('hello' + colors.inverse(' world')); var expected = colors.red.bgGreen('hello' + colors.inverse(' wor')) + '…'; - expect(truncate(original,10)).toEqual(expected); + expect(truncate(original, 10)).toEqual(expected); }); - it('red-on-green( zebra (hello world) ) truncated to 11 chars',function(){ + it('red-on-green( zebra (hello world) ) truncated to 11 chars', function() { var original = colors.red.bgGreen(colors.zebra('hello world')); var expected = colors.red.bgGreen(colors.zebra('hello world')); - expect(truncate(original,11)).toEqual(expected); + expect(truncate(original, 11)).toEqual(expected); }); - it('red-on-green( zebra (hello world) ) truncated to 10 chars',function(){ + it('red-on-green( zebra (hello world) ) truncated to 10 chars', function() { var original = colors.red.bgGreen(colors.zebra('hello world')); var expected = colors.red.bgGreen(colors.zebra('hello wor')) + '…'; - expect(truncate(original,10)).toEqual(expected); + expect(truncate(original, 10)).toEqual(expected); }); it('handles reset code', function() { var original = '\x1b[31mhello\x1b[0m world'; var expected = '\x1b[31mhello\x1b[0m wor…'; - expect(truncate(original,10)).toEqual(expected); + expect(truncate(original, 10)).toEqual(expected); }); it('handles reset code (EMPTY VERSION)', function() { var original = '\x1b[31mhello\x1b[0m world'; var expected = '\x1b[31mhello\x1b[0m wor…'; - expect(truncate(original,10)).toEqual(expected); + expect(truncate(original, 10)).toEqual(expected); }); - it('truncateWidth("漢字テスト", 15) === "漢字テスト"',function(){ - expect(truncate('漢字テスト',15)).toEqual('漢字テスト'); + it('truncateWidth("漢字テスト", 15) === "漢字テスト"', function() { + expect(truncate('漢字テスト', 15)).toEqual('漢字テスト'); }); - it('truncateWidth("漢字テスト", 6) === "漢字…"',function(){ - expect(truncate('漢字テスト',6)).toEqual('漢字…'); + it('truncateWidth("漢字テスト", 6) === "漢字…"', function() { + expect(truncate('漢字テスト', 6)).toEqual('漢字…'); }); - it('truncateWidth("漢字テスト", 5) === "漢字…"',function(){ - expect(truncate('漢字テスト',5)).toEqual('漢字…'); + it('truncateWidth("漢字テスト", 5) === "漢字…"', function() { + expect(truncate('漢字テスト', 5)).toEqual('漢字…'); }); - it('truncateWidth("漢字testてすと", 12) === "漢字testて…"',function(){ - expect(truncate('漢字testてすと',12)).toEqual('漢字testて…'); + it('truncateWidth("漢字testてすと", 12) === "漢字testて…"', function() { + expect(truncate('漢字testてすと', 12)).toEqual('漢字testて…'); }); - it('handles color code with CJK chars',function(){ + it('handles color code with CJK chars', function() { var original = '漢字\x1b[31m漢字\x1b[0m漢字'; var expected = '漢字\x1b[31m漢字\x1b[0m漢…'; - expect(truncate(original,11)).toEqual(expected); + expect(truncate(original, 11)).toEqual(expected); }); }); - function defaultOptions(){ + function defaultOptions() { return { chars: { - 'top': '─' - , 'top-mid': '┬' - , 'top-left': '┌' - , 'top-right': '┐' - , 'bottom': '─' - , 'bottom-mid': '┴' - , 'bottom-left': '└' - , 'bottom-right': '┘' - , 'left': '│' - , 'left-mid': '├' - , 'mid': '─' - , 'mid-mid': '┼' - , 'right': '│' - , 'right-mid': '┤' - , 'middle': '│' - } - , truncate: '…' - , colWidths: [] - , rowHeights: [] - , colAligns: [] - , rowAligns: [] - , style: { - 'padding-left': 1 - , 'padding-right': 1 - , head: ['red'] - , border: ['grey'] - , compact : false - } - , head: [] + top: '─', + 'top-mid': '┬', + 'top-left': '┌', + 'top-right': '┐', + bottom: '─', + 'bottom-mid': '┴', + 'bottom-left': '└', + 'bottom-right': '┘', + left: '│', + 'left-mid': '├', + mid: '─', + 'mid-mid': '┼', + right: '│', + 'right-mid': '┤', + middle: '│', + }, + truncate: '…', + colWidths: [], + rowHeights: [], + colAligns: [], + rowAligns: [], + style: { + 'padding-left': 1, + 'padding-right': 1, + head: ['red'], + border: ['grey'], + compact: false, + }, + head: [], }; } - describe('mergeOptions',function(){ - it('allows you to override chars',function(){ + describe('mergeOptions', function() { + it('allows you to override chars', function() { expect(mergeOptions()).toEqual(defaultOptions()); }); - it('chars will be merged deeply',function(){ + it('chars will be merged deeply', function() { var expected = defaultOptions(); expected.chars.left = 'L'; - expect(mergeOptions({chars:{left:'L'}})).toEqual(expected); + expect(mergeOptions({ chars: { left: 'L' } })).toEqual(expected); }); - it('style will be merged deeply',function(){ + it('style will be merged deeply', function() { var expected = defaultOptions(); expected.style['padding-left'] = 2; - expect(mergeOptions({style:{'padding-left':2}})).toEqual(expected); + expect(mergeOptions({ style: { 'padding-left': 2 } })).toEqual(expected); }); - it('head will be overwritten',function(){ + it('head will be overwritten', function() { var expected = defaultOptions(); expected.style.head = []; //we can't use lodash's `merge()` in implementation because it would deeply copy array. - expect(mergeOptions({style:{'head':[]}})).toEqual(expected); + expect(mergeOptions({ style: { head: [] } })).toEqual(expected); }); - it('border will be overwritten',function(){ + it('border will be overwritten', function() { var expected = defaultOptions(); expected.style.border = []; //we can't use lodash's `merge()` in implementation because it would deeply copy array. - expect(mergeOptions({style:{'border':[]}})).toEqual(expected); + expect(mergeOptions({ style: { border: [] } })).toEqual(expected); }); }); - describe('wordWrap',function(){ - it('length',function(){ + describe('wordWrap', function() { + it('length', function() { var input = 'Hello, how are you today? I am fine, thank you!'; var expected = 'Hello, how\nare you\ntoday? I\nam fine,\nthank you!'; - expect(wordWrap(10,input).join('\n')).toEqual(expected); + expect(wordWrap(10, input).join('\n')).toEqual(expected); }); - it.skip('length with colors',function(){ + it.skip('length with colors', function() { var input = colors.red('Hello, how are') + colors.blue(' you today? I') + colors.green(' am fine, thank you!'); - var expected = colors.red('Hello, how\nare') + colors.blue(' you\ntoday? I') + colors.green('\nam fine,\nthank you!'); + var expected = + colors.red('Hello, how\nare') + colors.blue(' you\ntoday? I') + colors.green('\nam fine,\nthank you!'); - expect(wordWrap(10,input).join('\n')).toEqual(expected); + expect(wordWrap(10, input).join('\n')).toEqual(expected); }); - it('will not create an empty last line',function(){ + it('will not create an empty last line', function() { var input = 'Hello Hello '; var expected = 'Hello\nHello'; - expect(wordWrap(5,input).join('\n')).toEqual(expected); + expect(wordWrap(5, input).join('\n')).toEqual(expected); }); - it('will handle color reset code',function(){ + it('will handle color reset code', function() { var input = '\x1b[31mHello\x1b[0m Hello '; var expected = '\x1b[31mHello\x1b[0m\nHello'; - expect(wordWrap(5,input).join('\n')).toEqual(expected); + expect(wordWrap(5, input).join('\n')).toEqual(expected); }); - it('will handle color reset code (EMPTY version)',function(){ + it('will handle color reset code (EMPTY version)', function() { var input = '\x1b[31mHello\x1b[m Hello '; var expected = '\x1b[31mHello\x1b[m\nHello'; - expect(wordWrap(5,input).join('\n')).toEqual(expected); + expect(wordWrap(5, input).join('\n')).toEqual(expected); }); - it('words longer than limit will not create extra newlines',function(){ + it('words longer than limit will not create extra newlines', function() { var input = 'disestablishment is a multiplicity someotherlongword'; var expected = 'disestablishment\nis a\nmultiplicity\nsomeotherlongword'; - expect(wordWrap(7,input).join('\n')).toEqual(expected); + expect(wordWrap(7, input).join('\n')).toEqual(expected); }); - it('multiple line input',function(){ + it('multiple line input', function() { var input = 'a\nb\nc d e d b duck\nm\nn\nr'; var expected = ['a', 'b', 'c d', 'e d', 'b', 'duck', 'm', 'n', 'r']; - expect(wordWrap(4,input)).toEqual(expected); + expect(wordWrap(4, input)).toEqual(expected); }); - it('will not start a line with whitespace', function(){ + it('will not start a line with whitespace', function() { var input = 'ab cd ef gh ij kl'; - var expected = ['ab cd','ef gh', 'ij kl']; + var expected = ['ab cd', 'ef gh', 'ij kl']; expect(wordWrap(7, input)).toEqual(expected); }); - it('wraps CJK chars', function(){ + it('wraps CJK chars', function() { var input = '漢字 漢\n字 漢字'; - var expected = ['漢字 漢','字 漢字']; + var expected = ['漢字 漢', '字 漢字']; expect(wordWrap(7, input)).toEqual(expected); }); - it('wraps CJK chars with colors', function(){ + it('wraps CJK chars with colors', function() { var input = '\x1b[31m漢字\x1b[0m\n 漢字'; var expected = ['\x1b[31m漢字\x1b[0m', ' 漢字']; expect(wordWrap(5, input)).toEqual(expected); }); }); - describe('colorizeLines',function(){ - it('foreground colors continue on each line',function(){ + describe('colorizeLines', function() { + it('foreground colors continue on each line', function() { var input = colors.red('Hello\nHi').split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - colors.red('Hello'), - colors.red('Hi') - ]); + expect(utils.colorizeLines(input)).toEqual([colors.red('Hello'), colors.red('Hi')]); }); - it('foreground colors continue on each line',function(){ + it('foreground colors continue on each line', function() { var input = colors.bgRed('Hello\nHi').split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - colors.bgRed('Hello'), - colors.bgRed('Hi') - ]); + expect(utils.colorizeLines(input)).toEqual([colors.bgRed('Hello'), colors.bgRed('Hi')]); }); - it('styles will continue on each line',function(){ + it('styles will continue on each line', function() { var input = colors.underline('Hello\nHi').split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - colors.underline('Hello'), - colors.underline('Hi') - ]); + expect(utils.colorizeLines(input)).toEqual([colors.underline('Hello'), colors.underline('Hi')]); }); - it('styles that end before the break will not be applied to the next line',function(){ - var input = (colors.underline('Hello') +'\nHi').split('\n'); + it('styles that end before the break will not be applied to the next line', function() { + var input = (colors.underline('Hello') + '\nHi').split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - colors.underline('Hello'), - 'Hi' - ]); + expect(utils.colorizeLines(input)).toEqual([colors.underline('Hello'), 'Hi']); }); it('the reset code can be used to drop styles', function() { var input = '\x1b[31mHello\x1b[0m\nHi'.split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - "\x1b[31mHello\x1b[0m", - "Hi" - ]); + expect(utils.colorizeLines(input)).toEqual(['\x1b[31mHello\x1b[0m', 'Hi']); }); it('handles aixterm 16-color foreground', function() { var input = '\x1b[90mHello\nHi\x1b[0m'.split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - '\x1b[90mHello\x1b[39m', - '\x1b[90mHi\x1b[0m' - ]); + expect(utils.colorizeLines(input)).toEqual(['\x1b[90mHello\x1b[39m', '\x1b[90mHi\x1b[0m']); }); it('handles aixterm 16-color background', function() { var input = '\x1b[100mHello\nHi\x1b[m\nHowdy'.split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - '\x1b[100mHello\x1b[49m', - '\x1b[100mHi\x1b[m', - 'Howdy' - ]); + expect(utils.colorizeLines(input)).toEqual(['\x1b[100mHello\x1b[49m', '\x1b[100mHi\x1b[m', 'Howdy']); }); it('handles aixterm 256-color foreground', function() { - var input ='\x1b[48;5;8mHello\nHi\x1b[0m\nHowdy'.split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - '\x1b[48;5;8mHello\x1b[49m', - '\x1b[48;5;8mHi\x1b[0m', - 'Howdy' - ]); + var input = '\x1b[48;5;8mHello\nHi\x1b[0m\nHowdy'.split('\n'); + expect(utils.colorizeLines(input)).toEqual(['\x1b[48;5;8mHello\x1b[49m', '\x1b[48;5;8mHi\x1b[0m', 'Howdy']); }); - it('handles CJK chars',function(){ + it('handles CJK chars', function() { var input = colors.red('漢字\nテスト').split('\n'); - expect(utils.colorizeLines(input)).toEqual([ - colors.red('漢字'), - colors.red('テスト') - ]); + expect(utils.colorizeLines(input)).toEqual([colors.red('漢字'), colors.red('テスト')]); }); }); -}); \ No newline at end of file +}); diff --git a/test/verify-legacy-compatibility-test.js b/test/verify-legacy-compatibility-test.js index 2b93066..49dc3bb 100644 --- a/test/verify-legacy-compatibility-test.js +++ b/test/verify-legacy-compatibility-test.js @@ -1,156 +1,138 @@ -(function(){ - describe('verify original cli-table behavior',function(){ - commonTests(require('cli-table')); +(function() { + describe('verify original cli-table behavior', function() { + commonTests(require('cli-table')); }); - describe('@api cli-table2 matches verified behavior',function(){ - commonTests(require('../src/table')); + describe('@api cli-table2 matches verified behavior', function() { + commonTests(require('../src/table')); }); - function commonTests(Table){ + function commonTests(Table) { var colors = require('colors/safe'); - it('empty table has a width of 0',function(){ + it('empty table has a width of 0', function() { var table = new Table(); expect(table.width).toEqual(0); expect(table.toString()).toEqual(''); }); - it('header text will be colored according to style',function(){ - var table = new Table({head:['hello','goodbye'],style:{border:[],head:['red','bgWhite']}}); + it('header text will be colored according to style', function() { + var table = new Table({ head: ['hello', 'goodbye'], style: { border: [], head: ['red', 'bgWhite'] } }); var expected = [ - '┌───────┬─────────┐' - , '│' + colors.bgWhite.red(' hello ') +'│' + colors.bgWhite.red(' goodbye ') + '│' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│' + colors.bgWhite.red(' hello ') + '│' + colors.bgWhite.red(' goodbye ') + '│', + '└───────┴─────────┘', ]; expect(table.toString()).toEqual(expected.join('\n')); }); - it('tables with one row of data will not be treated as headers',function(){ - var table = new Table({style:{border:[],head:['red']}}); + it('tables with one row of data will not be treated as headers', function() { + var table = new Table({ style: { border: [], head: ['red'] } }); - table.push(['hello','goodbye']); + table.push(['hello', 'goodbye']); - var expected = [ - '┌───────┬─────────┐' - , '│ hello │ goodbye │' - , '└───────┴─────────┘' - ]; + var expected = ['┌───────┬─────────┐', '│ hello │ goodbye │', '└───────┴─────────┘']; expect(table.toString()).toEqual(expected.join('\n')); }); - it('table with headers and data headers',function(){ - var table = new Table({head:['hello','goodbye'],style:{border:[],head:['red']}}); + it('table with headers and data headers', function() { + var table = new Table({ head: ['hello', 'goodbye'], style: { border: [], head: ['red'] } }); - table.push(['hola','adios']); + table.push(['hola', 'adios']); var expected = [ - '┌───────┬─────────┐' - , '│' + colors.red(' hello ') +'│' + colors.red(' goodbye ') + '│' - , '├───────┼─────────┤' - , '│ hola │ adios │' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│' + colors.red(' hello ') + '│' + colors.red(' goodbye ') + '│', + '├───────┼─────────┤', + '│ hola │ adios │', + '└───────┴─────────┘', ]; expect(table.toString()).toEqual(expected.join('\n')); }); - it('compact shorthand',function(){ - var table = new Table({style:{compact:true,border:[],head:['red']}}); + it('compact shorthand', function() { + var table = new Table({ style: { compact: true, border: [], head: ['red'] } }); - table.push(['hello','goodbye'],['hola','adios']); + table.push(['hello', 'goodbye'], ['hola', 'adios']); - var expected = [ - '┌───────┬─────────┐' - , '│ hello │ goodbye │' - , '│ hola │ adios │' - , '└───────┴─────────┘' - ]; + var expected = ['┌───────┬─────────┐', '│ hello │ goodbye │', '│ hola │ adios │', '└───────┴─────────┘']; expect(table.toString()).toEqual(expected.join('\n')); }); - it('compact shorthand - headers are still rendered with separator',function(){ - var table = new Table({head:['hello','goodbye'],style:{compact:true,border:[],head:[]}}); + it('compact shorthand - headers are still rendered with separator', function() { + var table = new Table({ head: ['hello', 'goodbye'], style: { compact: true, border: [], head: [] } }); - table.push(['hola','adios'],['hi','bye']); + table.push(['hola', 'adios'], ['hi', 'bye']); var expected = [ - '┌───────┬─────────┐' - , '│ hello │ goodbye │' - , '├───────┼─────────┤' - , '│ hola │ adios │' - , '│ hi │ bye │' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│ hello │ goodbye │', + '├───────┼─────────┤', + '│ hola │ adios │', + '│ hi │ bye │', + '└───────┴─────────┘', ]; expect(table.toString()).toEqual(expected.join('\n')); }); - it('compact longhand - headers are not rendered with separator',function(){ + it('compact longhand - headers are not rendered with separator', function() { var table = new Table({ chars: { - 'mid': '' - , 'left-mid': '' - , 'mid-mid': '' - , 'right-mid': '' + mid: '', + 'left-mid': '', + 'mid-mid': '', + 'right-mid': '', }, - head:['hello','goodbye'], - style:{border:[],head:[]}} - ); + head: ['hello', 'goodbye'], + style: { border: [], head: [] }, + }); - table.push(['hola','adios'],['hi','bye']); + table.push(['hola', 'adios'], ['hi', 'bye']); var expected = [ - '┌───────┬─────────┐' - , '│ hello │ goodbye │' - , '│ hola │ adios │' - , '│ hi │ bye │' - , '└───────┴─────────┘' + '┌───────┬─────────┐', + '│ hello │ goodbye │', + '│ hola │ adios │', + '│ hi │ bye │', + '└───────┴─────────┘', ]; expect(table.toString()).toEqual(expected.join('\n')); }); - it('compact longhand',function(){ + it('compact longhand', function() { var table = new Table({ chars: { - 'mid': '' - , 'left-mid': '' - , 'mid-mid': '' - , 'right-mid': '' + mid: '', + 'left-mid': '', + 'mid-mid': '', + 'right-mid': '', }, - style:{border:[],head:['red']} + style: { border: [], head: ['red'] }, }); - table.push(['hello','goodbye'],['hola','adios']); + table.push(['hello', 'goodbye'], ['hola', 'adios']); - var expected = [ - '┌───────┬─────────┐' - , '│ hello │ goodbye │' - , '│ hola │ adios │' - , '└───────┴─────────┘' - ]; + var expected = ['┌───────┬─────────┐', '│ hello │ goodbye │', '│ hola │ adios │', '└───────┴─────────┘']; expect(table.toString()).toEqual(expected.join('\n')); }); - it('objects with multiple properties in a cross-table',function(){ - var table = new Table({style:{border:[],head:[]}}); + it('objects with multiple properties in a cross-table', function() { + var table = new Table({ style: { border: [], head: [] } }); table.push( - {'a':['b'], c:['d']} // value of property 'c' will be discarded + { a: ['b'], c: ['d'] } // value of property 'c' will be discarded ); - var expected = [ - '┌───┬───┐' - , '│ a │ b │' - , '└───┴───┘' - ]; + var expected = ['┌───┬───┐', '│ a │ b │', '└───┴───┘']; expect(table.toString()).toEqual(expected.join('\n')); }); } -})(); \ No newline at end of file +})(); diff --git a/yarn.lock b/yarn.lock index f39a1c5..fb3a82e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -923,6 +923,19 @@ escodegen@^1.9.0: optionalDependencies: source-map "~0.6.1" +eslint-config-prettier@^2.9.0: + version "2.9.0" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-2.9.0.tgz#5ecd65174d486c22dff389fe036febf502d468a3" + dependencies: + get-stdin "^5.0.1" + +eslint-plugin-prettier@^2.6.0: + version "2.6.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-2.6.0.tgz#33e4e228bdb06142d03c560ce04ec23f6c767dd7" + dependencies: + fast-diff "^1.1.1" + jest-docblock "^21.0.0" + eslint-scope@^3.7.1: version "3.7.1" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-3.7.1.tgz#3d63c3edfda02e06e01a452ad88caacc7cdcb6e8" @@ -1139,6 +1152,10 @@ fast-deep-equal@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614" +fast-diff@^1.1.1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.1.2.tgz#4b62c42b8e03de3f848460b639079920695d0154" + fast-json-stable-stringify@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" @@ -1335,6 +1352,10 @@ get-caller-file@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5" +get-stdin@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-5.0.1.tgz#122e161591e21ff4c52530305693f20e6393a398" + get-stream@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-3.0.0.tgz#8e943d1358dc37555054ecbe2edb05aa174ede14" @@ -2125,6 +2146,10 @@ jest-diff@^23.0.1: jest-get-type "^22.1.0" pretty-format "^23.0.1" +jest-docblock@^21.0.0: + version "21.2.0" + resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-21.2.0.tgz#51529c3b30d5fd159da60c27ceedc195faf8d414" + jest-docblock@^23.0.1: version "23.0.1" resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-23.0.1.tgz#deddd18333be5dc2415260a04ef3fce9276b5725" @@ -3189,6 +3214,10 @@ preserve@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" +prettier@1.13.5: + version "1.13.5" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.13.5.tgz#7ae2076998c8edce79d63834e9b7b09fead6bfd0" + pretty-format@^23.0.1: version "23.0.1" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-23.0.1.tgz#d61d065268e4c759083bccbca27a01ad7c7601f4"