Cut a path from the middle, and keep a label's number when it's cut

This commit is contained in:
Callum Alpass committed 2026-11-03 20:53:31 +11:00
1 parent 9e532f5d6f
commit 39e96681f6
2 files changed
+40 -1

No files matched your search

+19
View File
@@ -11,3 +11,22 @@ export function firstLine(text: string): string {
if (line.length <= 100) return line; if (line.length <= 100) return line;
return `${line.slice(0, 99)}…`; 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}`;
}
+21 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; 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", () => { describe("truncate", () => {
test("collapses whitespace and clips with an ellipsis", () => { test("collapses whitespace and clips with an ellipsis", () => {
@@ -26,3 +26,23 @@ describe("firstLine", () => {
expect(firstLine(long)).toBe(`${"x".repeat(99)}…`); 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…");
});
});