* Inserts newlines in a string to wrap it at the specified width. * Uses ANSI-aware slicing to avoid splitting escape sequences. * @param text The text to wrap. * @param wrapWidth The width at which to wrap lines (in visible characters). * @returns The wrapped text.
( text: string, wrapWidth: number, )
| 17 | * @returns The wrapped text. |
| 18 | */ |
| 19 | function wrapText( |
| 20 | text: string, |
| 21 | wrapWidth: number, |
| 22 | ): { aboveTheFold: string; remainingLines: number } { |
| 23 | const lines = text.split('\n') |
| 24 | const wrappedLines: string[] = [] |
| 25 | |
| 26 | for (const line of lines) { |
| 27 | const visibleWidth = stringWidth(line) |
| 28 | if (visibleWidth <= wrapWidth) { |
| 29 | wrappedLines.push(line.trimEnd()) |
| 30 | } else { |
| 31 | // Break long lines into chunks of wrapWidth visible characters |
| 32 | // using ANSI-aware slicing to preserve escape sequences |
| 33 | let position = 0 |
| 34 | while (position < visibleWidth) { |
| 35 | const chunk = sliceAnsi(line, position, position + wrapWidth) |
| 36 | wrappedLines.push(chunk.trimEnd()) |
| 37 | position += wrapWidth |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | const remainingLines = wrappedLines.length - MAX_LINES_TO_SHOW |
| 43 | |
| 44 | // If there's only 1 line after the fold, show it directly |
| 45 | // instead of showing "... +1 line (ctrl+o to expand)" |
| 46 | if (remainingLines === 1) { |
| 47 | return { |
| 48 | aboveTheFold: wrappedLines |
| 49 | .slice(0, MAX_LINES_TO_SHOW + 1) |
| 50 | .join('\n') |
| 51 | .trimEnd(), |
| 52 | remainingLines: 0, // All lines are shown, nothing remaining |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Otherwise show the standard MAX_LINES_TO_SHOW |
| 57 | return { |
| 58 | aboveTheFold: wrappedLines.slice(0, MAX_LINES_TO_SHOW).join('\n').trimEnd(), |
| 59 | remainingLines: Math.max(0, remainingLines), |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Renders the content with line-based truncation for terminal display. |
no test coverage detected