feat(cli): add @shumai/tableprinter package to handle terminal-friendly table layouts

This commit is contained in:
yiling
2026-06-21 19:28:31 +08:00
parent 1c994adce9
commit 7d91d70a14
11 changed files with 488 additions and 52 deletions
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest'
import { newTablePrinter, withTruncate, withColor } from './index'
class StringWriter {
content = ''
write(s: string) {
this.content += s
}
}
describe('tableprinter', () => {
it('tsv mode', () => {
const writer = new StringWriter()
const tp = newTablePrinter(writer, false, 80)
tp.addHeader(['ID', 'Name', 'Size'])
tp.addField('1')
tp.addField('apple')
tp.addField('10')
tp.endRow()
tp.addField('2')
tp.addField('banana')
tp.addField('20')
tp.endRow()
tp.render()
expect(writer.content).toBe('1\tapple\t10\n2\tbanana\t20\n')
})
it('tty mode - no truncation', () => {
const writer = new StringWriter()
const tp = newTablePrinter(writer, true, 80)
tp.addHeader(['ID', 'Name', 'Size'])
tp.addField('1')
tp.addField('apple')
tp.addField('10')
tp.endRow()
tp.addField('2')
tp.addField('banana')
tp.addField('20')
tp.endRow()
tp.render()
const lines = writer.content.split('\n')
expect(lines[0]).toBe('ID Name Size')
expect(lines[1]).toBe('1 apple 10')
expect(lines[2]).toBe('2 banana 20')
})
it('tty mode - dynamic truncation to fit viewport', () => {
const writer = new StringWriter()
// Very narrow viewport
const tp = newTablePrinter(writer, true, 20)
tp.addHeader(['ID', 'LongName'])
tp.addField('01KV')
tp.addField('YTDown_YouTube_Ed-Sheeran-Pokemon-Celestial')
tp.endRow()
tp.render()
const lines = writer.content.split('\n').filter(Boolean)
// Avail width for columns: 20 - 2 (delimiter size) = 18.
// ID column is 4 chars, leaving 14 chars for LongName.
// LongName has truncate by default.
expect(lines[0]).toBe('ID LongName')
expect(lines[1]).toBe('01KV YTDown_YouT...')
})
it('tty mode - disabled truncation option', () => {
const writer = new StringWriter()
// Narrow viewport
const tp = newTablePrinter(writer, true, 25)
// Disable truncation on the first column, keep default on the second
tp.addHeader(['ID', 'LongName'], withTruncate(null))
tp.addField('01KVFW2HD6CK9D9H77A341HQP1', withTruncate(null))
tp.addField('YTDown_YouTube_Ed-Sheeran-Pokemon')
tp.endRow()
tp.render()
const lines = writer.content.split('\n').filter(Boolean)
// First column is 26 characters and must not be truncated since truncation is disabled.
expect(lines[1].startsWith('01KVFW2HD6CK9D9H77A341HQP1')).toBe(true)
})
it('tty mode - color preservation and display width measurement', () => {
const writer = new StringWriter()
const tp = newTablePrinter(writer, true, 80)
// Red colored title
const coloredName = '\u001b[31mapple\u001b[0m'
tp.addHeader(['ID', 'Name'])
tp.addField('1')
tp.addField(
coloredName,
withColor((s) => `\u001b[31m${s}\u001b[0m`),
)
tp.endRow()
tp.render()
const lines = writer.content.split('\n')
// Display width of coloredName should be 5 despite escape sequences.
expect(lines[0]).toBe('ID Name')
})
})
+239
View File
@@ -0,0 +1,239 @@
import { displayWidth, padRight, truncate } from './text'
export interface TableField {
text: string
truncateFunc?: (width: number, val: string) => string
paddingFunc?: (width: number, val: string) => string
colorFunc?: (val: string) => string
}
export type FieldOption = (field: TableField) => void
export interface TablePrinter {
addHeader(columns: string[], ...opts: FieldOption[]): void
addField(s: string, ...opts: FieldOption[]): void
endRow(): void
render(): void
}
export function withTruncate(fn: ((width: number, val: string) => string) | null): FieldOption {
return (f: TableField) => {
f.truncateFunc = fn ?? undefined
}
}
export function withPadding(fn: ((width: number, val: string) => string) | null): FieldOption {
return (f: TableField) => {
f.paddingFunc = fn ?? undefined
}
}
export function withColor(fn: (val: string) => string): FieldOption {
return (f: TableField) => {
f.colorFunc = fn
}
}
export interface Writer {
write(s: string): void
}
export function newTablePrinter(w: Writer, isTty: boolean, maxWidth: number): TablePrinter {
if (isTty) {
return new TtyTablePrinter(w, maxWidth)
}
return new TsvTablePrinter(w)
}
class TtyTablePrinter implements TablePrinter {
private hasHeaders = false
private rows: TableField[][] = []
constructor(
private out: Writer,
private maxWidth: number,
) {}
addHeader(columns: string[], ...opts: FieldOption[]): void {
if (this.hasHeaders) return
this.hasHeaders = true
for (const column of columns) {
this.addField(column, ...opts)
}
this.endRow()
}
addField(s: string, ...opts: FieldOption[]): void {
if (this.rows.length === 0) {
this.rows.push([])
}
const rowI = this.rows.length - 1
const field: TableField = {
text: s,
truncateFunc: truncate,
}
for (const opt of opts) {
opt(field)
}
this.rows[rowI].push(field)
}
endRow(): void {
this.rows.push([])
}
render(): void {
// Filter out trailing empty rows if any
const activeRows = this.rows.filter((row) => row.length > 0)
if (activeRows.length === 0) return
const delim = ' '
const numCols = activeRows[0].length
const colWidths = this.calculateColumnWidths(activeRows, delim.length)
for (const row of activeRows) {
for (let col = 0; col < row.length; col++) {
if (col >= numCols) break
const field = row[col]
if (col > 0) {
this.out.write(delim)
}
let truncVal = field.text
if (field.truncateFunc) {
truncVal = field.truncateFunc(colWidths[col], field.text)
}
if (field.paddingFunc) {
truncVal = field.paddingFunc(colWidths[col], truncVal)
} else if (col < numCols - 1) {
truncVal = padRight(colWidths[col], truncVal)
}
if (field.colorFunc) {
truncVal = field.colorFunc(truncVal)
}
this.out.write(truncVal)
}
if (row.length > 0) {
this.out.write('\n')
}
}
}
private calculateColumnWidths(activeRows: TableField[][], delimSize: number): number[] {
const numCols = activeRows[0].length
const maxColWidths = new Array(numCols).fill(0)
const colWidths = new Array(numCols).fill(0)
for (const row of activeRows) {
for (let col = 0; col < row.length; col++) {
if (col >= numCols) break
const field = row[col]
const w = displayWidth(field.text)
if (w > maxColWidths[col]) {
maxColWidths[col] = w
}
// if this field has disabled truncating, ensure that the column is wide enough
if (field.truncateFunc === undefined && w > colWidths[col]) {
colWidths[col] = w
}
}
}
const getAvailWidth = (): number => {
let setWidths = 0
for (let col = 0; col < numCols; col++) {
setWidths += colWidths[col]
}
return this.maxWidth - delimSize * (numCols - 1) - setWidths
}
const getNumFixedCols = (): number => {
let fixedCols = 0
for (let col = 0; col < numCols; col++) {
if (colWidths[col] > 0) {
fixedCols++
}
}
return fixedCols
}
// set the widths of short columns
let w = getAvailWidth()
if (w > 0) {
const numFlexColumns = numCols - getNumFixedCols()
if (numFlexColumns > 0) {
const perColumn = Math.floor(w / numFlexColumns)
for (let col = 0; col < numCols; col++) {
if (colWidths[col] === 0) {
const max = maxColWidths[col]
if (max < perColumn) {
colWidths[col] = max
}
}
}
}
}
// truncate long columns to the remaining available width
w = getAvailWidth()
const numFlexColsCount = numCols - getNumFixedCols()
if (numFlexColsCount > 0) {
const perColumn = Math.floor(w / numFlexColsCount)
for (let col = 0; col < numCols; col++) {
if (colWidths[col] === 0) {
const max = maxColWidths[col]
if (max < perColumn) {
colWidths[col] = max
} else if (perColumn > 0) {
colWidths[col] = perColumn
}
}
}
}
// add the remainder to truncated columns
w = getAvailWidth()
if (w > 0) {
for (let col = 0; col < numCols; col++) {
const d = maxColWidths[col] - colWidths[col]
let toAdd = w
if (d < toAdd) {
toAdd = d
}
colWidths[col] += toAdd
w -= toAdd
if (w <= 0) {
break
}
}
}
return colWidths
}
}
class TsvTablePrinter implements TablePrinter {
private currentCol = 0
constructor(private out: Writer) {}
addHeader(): void {}
addField(s: string): void {
if (this.currentCol > 0) {
this.out.write('\t')
}
this.out.write(s)
this.currentCol++
}
endRow(): void {
this.out.write('\n')
this.currentCol = 0
}
render(): void {}
}
+85
View File
@@ -0,0 +1,85 @@
/* eslint-disable no-control-regex */
export function stripAnsi(str: string): string {
return str.replace(
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
'',
)
}
export function displayWidth(str: string): number {
const stripped = stripAnsi(str)
let width = 0
for (let i = 0; i < stripped.length; i++) {
const code = stripped.charCodeAt(i)
// Basic detection for CJK Unified Ideographs, Hangul, Hiragana, Katakana, Fullwidth
if (
(code >= 0x3000 && code <= 0x9fff) || // CJK symbols, Hiragana, Katakana, Unified Ideographs
(code >= 0xff00 && code <= 0xffef) || // Fullwidth forms
(code >= 0x1100 && code <= 0x11ff) || // Hangul Jamo
(code >= 0xac00 && code <= 0xd7af) // Hangul Syllables
) {
width += 2
} else {
width += 1
}
}
return width
}
export function truncate(width: number, s: string): string {
const stripped = stripAnsi(s)
const visualWidth = displayWidth(stripped)
if (visualWidth <= width) {
return s
}
// If width is too small, return part of ellipses
if (width <= 3) {
return '.'.repeat(width)
}
const targetWidth = width - 3 // save space for "..."
let currentWidth = 0
let cutIndex = 0
for (let i = 0; i < s.length; i++) {
// If we hit an ANSI escape sequence, skip it in width calculation but keep it in output
if (s[i] === '\u001b') {
// Find end of ANSI sequence
const match = s
.slice(i)
.match(/^[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/)
if (match) {
i += match[0].length - 1
continue
}
}
const code = s.charCodeAt(i)
const charWidth =
(code >= 0x3000 && code <= 0x9fff) ||
(code >= 0xff00 && code <= 0xffef) ||
(code >= 0x1100 && code <= 0x11ff) ||
(code >= 0xac00 && code <= 0xd7af)
? 2
: 1
if (currentWidth + charWidth > targetWidth) {
cutIndex = i
break
}
currentWidth += charWidth
}
const sliced = s.slice(0, cutIndex)
const resetCode = s.includes('\u001b') ? '\u001b[0m' : ''
return sliced + '...' + resetCode
}
export function padRight(width: number, s: string): string {
const currentWidth = displayWidth(s)
if (currentWidth >= width) {
return s
}
return s + ' '.repeat(width - currentWidth)
}