display.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { cli, Table } from 'cli-ux';
  2. import chalk from 'chalk';
  3. import { NameValueObj } from '../Types';
  4. export function displayHeader(caption: string, placeholderSign: string = '_', size: number = 50) {
  5. let singsPerSide: number = Math.floor((size - (caption.length + 2)) / 2);
  6. let finalStr: string = '';
  7. for (let i = 0; i < singsPerSide; ++i) finalStr += placeholderSign;
  8. finalStr += ` ${ caption} `;
  9. while (finalStr.length < size) finalStr += placeholderSign;
  10. process.stdout.write("\n" + chalk.bold.blueBright(finalStr) + "\n\n");
  11. }
  12. export function displayNameValueTable(rows: NameValueObj[]) {
  13. cli.table(
  14. rows,
  15. {
  16. name: { minWidth: 30, get: row => chalk.bold.white(row.name) },
  17. value: { get: row => chalk.white(row.value) }
  18. },
  19. { 'no-header': true }
  20. );
  21. }
  22. export function displayCollapsedRow(row: { [k: string]: string | number }) {
  23. const collapsedRow: NameValueObj[] = Object.keys(row).map(name => ({
  24. name,
  25. value: typeof row[name] === 'string' ? row[name] as string : row[name].toString()
  26. }));
  27. displayNameValueTable(collapsedRow);
  28. }
  29. export function displayCollapsedTable(rows: { [k: string]: string | number }[]) {
  30. for (const row of rows) displayCollapsedRow(row);
  31. }
  32. export function displayTable(rows: { [k: string]: string | number }[], cellHorizontalPadding = 0) {
  33. if (!rows.length) {
  34. return;
  35. }
  36. const maxLength = (columnName: string) => rows.reduce(
  37. (maxLength, row) => {
  38. const val = row[columnName];
  39. const valLength = typeof val === 'string' ? val.length : val.toString().length;
  40. return Math.max(maxLength, valLength);
  41. },
  42. columnName.length
  43. )
  44. const columnDef = (columnName: string) => ({
  45. get: (row: typeof rows[number]) => chalk.white(`${row[columnName]}`),
  46. minWidth: maxLength(columnName) + cellHorizontalPadding
  47. });
  48. let columns: Table.table.Columns<{ [k: string]: string }> = {};
  49. Object.keys(rows[0]).forEach(columnName => columns[columnName] = columnDef(columnName))
  50. cli.table(rows, columns);
  51. }
  52. export function toFixedLength(text: string, length: number, spacesOnLeft = false): string {
  53. if (text.length > length && length > 3) {
  54. return text.slice(0, length-3) + '...';
  55. }
  56. while(text.length < length) { spacesOnLeft ? text = ' '+text : text += ' ' };
  57. return text;
  58. }