display.ts 2.4 KB

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