From 39e96681f60c2f6d8274967ede74dac8e992c466 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Tue, 3 Nov 2026 20:53:31 +1100 Subject: [PATCH] Cut a path from the middle, and keep a label's number when it's cut --- src/ui/text.ts | 19 +++++++++++++++++++ test/text.test.ts | 22 +++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/ui/text.ts b/src/ui/text.ts index efcb66c..ef79846 100644 --- a/src/ui/text.ts +++ b/src/ui/text.ts @@ -11,3 +11,22 @@ export function firstLine(text: string): string { if (line.length <= 100) return line; return `${line.slice(0, 99)}…`; } + +/** + * Shortens a path to `width` from the middle, keeping its first folder and its file name: + * `src/…/TerminalPane.tsx`. A name too long even for that keeps its end. + */ +export function truncatePath(path: string, width: number): string { + if (path.length <= width) return path; + const parts = path.split("/"); + const name = parts.pop() ?? path; + const head = parts[0] ? `${parts[0]}/…/` : "…/"; + if (parts.length > 1 && head.length + name.length <= width) return `${head}${name}`; + return `…${name.slice(Math.max(0, name.length - width + 1))}`; +} + +/** Clips text to `width`, keeping a number at its end: `Term… 2`. */ +export function truncateNumbered(text: string, width: number): string { + const number = /\s\d+$/.exec(text)?.[0] ?? ""; + return text.length <= width ? text : `${truncate(text.slice(0, text.length - number.length), Math.max(1, width - number.length))}${number}`; +} diff --git a/test/text.test.ts b/test/text.test.ts index 1ee69da..020b927 100644 --- a/test/text.test.ts +++ b/test/text.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { firstLine, truncate } from "../src/ui/text.ts"; +import { firstLine, truncate, truncateNumbered, truncatePath } from "../src/ui/text.ts"; describe("truncate", () => { test("collapses whitespace and clips with an ellipsis", () => { @@ -26,3 +26,23 @@ describe("firstLine", () => { expect(firstLine(long)).toBe(`${"x".repeat(99)}…`); }); }); + +describe("truncatePath", () => { + test("keeps the first folder and the file name, dropping the middle", () => { + expect(truncatePath("src/ui/TerminalPane.tsx", 40)).toBe("src/ui/TerminalPane.tsx"); + expect(truncatePath("src/ui/deep/er/TerminalPane.tsx", 22)).toBe("src/…/TerminalPane.tsx"); + }); + + test("keeps the end of a name too long for that", () => { + expect(truncatePath("src/ui/TerminalPane.tsx", 8)).toBe("…ane.tsx"); + expect(truncatePath("averyveryverylongname.ts", 10)).toBe("…ngname.ts"); + }); +}); + +describe("truncateNumbered", () => { + test("keeps the number at the end", () => { + expect(truncateNumbered("Terminal 12", 20)).toBe("Terminal 12"); + expect(truncateNumbered("Terminal 2", 7)).toBe("Term… 2"); + expect(truncateNumbered("Scratch", 4)).toBe("Scr…"); + }); +});