fix(tui): prevent truncateMiddle overflow at small widths (#60287)

This commit is contained in:
Filip
2026-10-29 18:07:23 +01:00
committed by GitHub
Unverified
parent 6b9f21471f
commit ccd406b00f
4 changed files with 27 additions and 0 deletions
+2
View File
@@ -67,11 +67,13 @@ export function truncateLeft(str: string, len: number): string {
}
export function truncateMiddle(str: string, maxLength: number = 35): string {
if (maxLength <= 0) return ""
if (str.length <= maxLength) return str
const ellipsis = "…"
const keepStart = Math.ceil((maxLength - ellipsis.length) / 2)
const keepEnd = Math.floor((maxLength - ellipsis.length) / 2)
if (keepEnd <= 0) return str.slice(0, keepStart) + ellipsis
return str.slice(0, keepStart) + ellipsis + str.slice(-keepEnd)
}
+12
View File
@@ -18,3 +18,15 @@ test("rolls the compact form over at the rounding boundary", () => {
expect(Locale.number(999950)).toBe("1.0M")
expect(Locale.number(1000000)).toBe("1.0M")
})
test("truncates text in the middle without overflowing small widths", () => {
expect(Locale.truncateMiddle("abcdefghij", 0)).toBe("")
expect(Locale.truncateMiddle("abcdefghij", 1)).toBe("…")
expect(Locale.truncateMiddle("abcdefghij", 2)).toBe("a…")
expect(Locale.truncateMiddle("abcdefghij", 3)).toBe("a…j")
expect(Locale.truncateMiddle("abcdefghij", 4)).toBe("ab…j")
expect(Locale.truncateMiddle("abcdefghij", 9)).toBe("abcd…ghij")
expect(Locale.truncateMiddle("abcd", 4)).toBe("abcd")
expect(Locale.truncateMiddle("abcd", 10)).toBe("abcd")
expect(Locale.truncateMiddle("a", 1)).toBe("a")
})
+11
View File
@@ -37,6 +37,17 @@ describe("client paths", () => {
expect(getFilenameTruncated("/repo/long-component-name.tsx", 16)).toBe("long-compon….tsx")
expect(truncateMiddle("abcdefghijklmnop", 9)).toBe("abcd…mnop")
})
test("truncates in the middle without overflowing small widths", () => {
expect(truncateMiddle("abcdefghij", 0)).toBe("")
expect(truncateMiddle("abcdefghij", 1)).toBe("…")
expect(truncateMiddle("abcdefghij", 2)).toBe("a…")
expect(truncateMiddle("abcdefghij", 3)).toBe("a…j")
expect(truncateMiddle("abcdefghij", 4)).toBe("ab…j")
expect(truncateMiddle("abcd", 4)).toBe("abcd")
expect(truncateMiddle("abcd", 10)).toBe("abcd")
expect(truncateMiddle("a", 1)).toBe("a")
})
})
describe("encodeFilePath", () => {
+2
View File
@@ -23,10 +23,12 @@ export function getFilenameTruncated(path: string | undefined, maxLength = 20) {
}
export function truncateMiddle(text: string, maxLength = 20) {
if (maxLength <= 0) return ""
if (text.length <= maxLength) return text
const available = maxLength - 1
const start = Math.ceil(available / 2)
const end = Math.floor(available / 2)
if (end <= 0) return text.slice(0, start) + "…"
return text.slice(0, start) + "…" + text.slice(-end)
}