|
| 1 | +import process from 'node:process'; |
| 2 | +import Table from 'cli-table3'; |
| 3 | + |
| 4 | +type TableRow = (string | number)[]; |
| 5 | +type TableOptions = { |
| 6 | + head: string[]; |
| 7 | + colAligns?: ('left' | 'right' | 'center')[]; |
| 8 | + style?: { |
| 9 | + head?: string[]; |
| 10 | + }; |
| 11 | +}; |
| 12 | + |
| 13 | +export class ResponsiveTable { |
| 14 | + private head: string[]; |
| 15 | + private rows: TableRow[] = []; |
| 16 | + private colAligns: ('left' | 'right' | 'center')[]; |
| 17 | + private style?: { head?: string[] }; |
| 18 | + |
| 19 | + constructor(options: TableOptions) { |
| 20 | + this.head = options.head; |
| 21 | + this.colAligns = options.colAligns ?? Array.from({ length: this.head.length }, () => 'left'); |
| 22 | + this.style = options.style; |
| 23 | + } |
| 24 | + |
| 25 | + push(row: TableRow): void { |
| 26 | + this.rows.push(row); |
| 27 | + } |
| 28 | + |
| 29 | + toString(): string { |
| 30 | + const terminalWidth = process.stdout.columns || 120; |
| 31 | + |
| 32 | + // Calculate reasonable column widths for responsive layout |
| 33 | + const numColumns = this.head.length; |
| 34 | + const tableOverhead = 3 * numColumns + 1; // borders and separators |
| 35 | + const availableWidth = terminalWidth - tableOverhead; |
| 36 | + |
| 37 | + // Create proportional column widths, with minimums |
| 38 | + const baseWidth = Math.floor(availableWidth / numColumns); |
| 39 | + const columnWidths = this.head.map((_, index) => { |
| 40 | + const align = this.colAligns[index]; |
| 41 | + // Give wider columns to text content, narrower to numbers |
| 42 | + if (align === 'right') { |
| 43 | + // Numeric columns - smaller width |
| 44 | + return Math.max(Math.floor(baseWidth * 0.7), 8); |
| 45 | + } |
| 46 | + else if (index === 0) { |
| 47 | + // First column (Date/Session) - medium width |
| 48 | + return Math.max(Math.floor(baseWidth * 0.8), 10); |
| 49 | + } |
| 50 | + else if (index === 1) { |
| 51 | + // Models column - can be longer, needs more space |
| 52 | + return Math.max(Math.floor(baseWidth * 1.2), 12); |
| 53 | + } |
| 54 | + else { |
| 55 | + // Other columns - standard width |
| 56 | + return Math.max(baseWidth, 8); |
| 57 | + } |
| 58 | + }); |
| 59 | + |
| 60 | + // Create table with responsive column widths and word wrapping |
| 61 | + const table = new Table({ |
| 62 | + head: this.head, |
| 63 | + style: this.style, |
| 64 | + colAligns: this.colAligns, |
| 65 | + colWidths: columnWidths, |
| 66 | + wordWrap: true, |
| 67 | + wrapOnWordBoundary: true, |
| 68 | + }); |
| 69 | + |
| 70 | + // Add all rows to the table |
| 71 | + for (const row of this.rows) { |
| 72 | + table.push(row); |
| 73 | + } |
| 74 | + |
| 75 | + return table.toString(); |
| 76 | + } |
| 77 | +} |
0 commit comments