(path: string, maxLength: number)
| 14 | * @returns The truncated path, or original if it fits within maxLength |
| 15 | */ |
| 16 | export function truncatePathMiddle(path: string, maxLength: number): string { |
| 17 | // No truncation needed |
| 18 | if (stringWidth(path) <= maxLength) { |
| 19 | return path |
| 20 | } |
| 21 | |
| 22 | // Handle edge case of very small or non-positive maxLength |
| 23 | if (maxLength <= 0) { |
| 24 | return '…' |
| 25 | } |
| 26 | |
| 27 | // Need at least room for "…" + something meaningful |
| 28 | if (maxLength < 5) { |
| 29 | return truncateToWidth(path, maxLength) |
| 30 | } |
| 31 | |
| 32 | // Find the filename (last path segment) |
| 33 | const lastSlash = path.lastIndexOf('/') |
| 34 | // Include the leading slash in filename for display |
| 35 | const filename = lastSlash >= 0 ? path.slice(lastSlash) : path |
| 36 | const directory = lastSlash >= 0 ? path.slice(0, lastSlash) : '' |
| 37 | const filenameWidth = stringWidth(filename) |
| 38 | |
| 39 | // If filename alone is too long, truncate from start |
| 40 | if (filenameWidth >= maxLength - 1) { |
| 41 | return truncateStartToWidth(path, maxLength) |
| 42 | } |
| 43 | |
| 44 | // Calculate space available for directory prefix |
| 45 | // Result format: directory + "…" + filename |
| 46 | const availableForDir = maxLength - 1 - filenameWidth // -1 for ellipsis |
| 47 | |
| 48 | if (availableForDir <= 0) { |
| 49 | // No room for directory, just show filename (truncated if needed) |
| 50 | return truncateStartToWidth(filename, maxLength) |
| 51 | } |
| 52 | |
| 53 | // Truncate directory and combine |
| 54 | const truncatedDir = truncateToWidthNoEllipsis(directory, availableForDir) |
| 55 | return truncatedDir + '…' + filename |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Truncates a string to fit within a maximum display width, measured in terminal columns. |
no test coverage detected