UNPKG

easy-cli-framework

Version:

A framework for building CLI applications that are robust and easy to maintain. Supports theming, configuration files, interactive prompts, and more.

87 lines (83 loc) 2.7 kB
'use strict'; var Table = require('cli-table'); /** * A themed table that extends a cli-table * @template TItem * @class ThemedTable * * @param {ThemedTableOptions<TItem>} options The options for the themed table * * @example * ```typescript * const theme = new EasyCLITheme(); * const table = new ThemedTable({ * theme, * columns: [ * { name: 'Name', data: item => item.name }, * { name: 'Age', data: item => item.age }, * ], * }); * * table.render([ * { name: 'Alice', age: 25 }, * { name: 'Bob', age: 30 }, * ]); *``` */ class ThemedTable { constructor({ theme, columns, totalWidth = 120 }) { this.theme = theme; this.columns = columns; this.totalWidth = totalWidth; } /** * Calculate the remaining default column width * @private * @returns {number} The remaining default column width */ calculateRemaingingDefaultColumnWidth() { const { width, columns } = this.columns.reduce((acc, column) => { if (column.width) { acc.width -= column.width; } else { acc.columns += 1; } return acc; }, { width: this.totalWidth, columns: 0 }); return Math.floor(width / columns); } /** * Render the table to the console * * @param {TItem[]} items The items to render * * @example * ```typescript * table.render([ * { name: 'Alice', age: 25 }, * { name: 'Bob', age: 30 }, * ]); * ``` */ render(items) { const defaultWidth = this.calculateRemaingingDefaultColumnWidth(); const table = new Table({ head: this.columns.map(column => { var _a; return this.theme.formattedString(column.name, (_a = column.headerStyle) !== null && _a !== undefined ? _a : 'default'); }), colWidths: this.columns.map(column => { var _a; return (_a = column.width) !== null && _a !== undefined ? _a : defaultWidth; }), colAligns: this.columns.map(column => { var _a; return (_a = column.align) !== null && _a !== undefined ? _a : 'middle'; }), colors: false, }); items.forEach(item => { table.push(this.columns.map(column => { const data = column.data(item); const style = typeof column.style === 'function' ? column.style(item) : column.style; return this.theme.formattedString(`${data}`, style !== null && style !== undefined ? style : 'default'); })); }); console.log(table.toString()); } } exports.ThemedTable = ThemedTable;