/** * Tests for title-row.ts — `Edit` / `Write` 标题行的纯排版(预算分配、按宽度截断、状态圆点、行数缩略)。 * * Run with: node --test clients/pi/extensions/tool-diff/title-row.test.ts * * 被测模块不 import pi / pi-tui(宽度与截断函数都是注入的),所以这里喂假实现: * ASCII = 1 列、CJK = 2 列;`•`(U+2022)、`⋮`、`…` 都是 1 列 —— 与 pi-tui 的 `visibleWidth` * 已核对一致。主题的 `fg` 换成恒等函数,断言里直接看纯文本。 */ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { BLINK_MARKER, DOT_MARKER, ELLIPSIS, MIN_PATH_COLS_WITH_BAR, PLACEHOLDER_PATH, RATIO_BAR_CELL, RATIO_BAR_WIDTH, TitleRow, formatCount, loadingSuffix, pathPlaceholder, ratioBar, shortenPath, statsSuffix, statusDot, truncateStartToWidth, type TitleRowDeps, type TitleTheme, } from "./title-row.ts"; /** 恒等主题:不着色,断言直接比对纯文本。 */ const plainTheme: TitleTheme = { fg: (_color, text) => text }; /** 假宽度函数:CJK 常见全角区间按 2 列,其余按 1 列。 */ function widthOf(text: string): number { let width = 0; for (const ch of text) { const code = ch.codePointAt(0) ?? 0; const wide = (code >= 0x1100 && code <= 0x115f) || (code >= 0x2e80 && code <= 0xa4cf) || (code >= 0xac00 && code <= 0xd7a3) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xfe30 && code <= 0xfe6f) || (code >= 0xff00 && code <= 0xff60) || (code >= 0xffe0 && code <= 0xffe6); width += wide ? 2 : 1; } return width; } /** 假截断函数(生产环境传 pi-tui 的 truncateToWidth):从尾部硬切,够用。 */ function truncateToWidth(text: string, width: number, ellipsis = ELLIPSIS): string { if (widthOf(text) <= width) return text; let out = ""; let used = 0; for (const ch of text) { const w = widthOf(ch); if (used + w > width - widthOf(ellipsis)) break; out += ch; used += w; } return out + ellipsis; } function deps(home = "/Users/me"): TitleRowDeps { return { widthOf, truncateToWidth, home, indent: " " }; } /** 一条必须从头部截断才能放进 90 列的深层路径。 */ const LONG_PATH = "/Users/me/work/project/packages/renderer/src/components/inner/deep/deeper/deepest/final/renderer-impl.ts"; function titleLine(path: string, suffix: string, width: number, rowDeps: TitleRowDeps = deps()): string { return new TitleRow(rowDeps, plainTheme, DOT_MARKER, "Write", path, suffix).render(width)[0] ?? ""; } describe("statusDot: 行首结局灯的色槽", () => { /** 记录 fg 调用的主题 */ function recorder(): { theme: TitleTheme; calls: Array<[string, string]> } { const calls: Array<[string, string]> = []; return { calls, theme: { fg: (color, text) => { calls.push([color, text]); return text; }, }, }; } it("paints pending dim and success / error with the diff green / red", () => { for (const [state, slot] of [ ["pending", "dim"], ["success", "toolDiffAdded"], ["error", "toolDiffRemoved"], ] as const) { const { theme, calls } = recorder(); assert.equal(statusDot(theme, state), DOT_MARKER); assert.deepEqual(calls, [[slot, DOT_MARKER]]); } }); it("is one column wide and carries no trailing blank (the gap belongs to TitleRow)", () => { assert.equal(widthOf(statusDot(plainTheme, "pending")), 1); assert.equal(statusDot(plainTheme, "pending"), DOT_MARKER); }); }); describe("pathPlaceholder: 路径未到时的占位符(用户 2026-10-28 定)", () => { it("substitutes `files` only when the path is still empty", () => { assert.equal(pathPlaceholder(""), PLACEHOLDER_PATH); assert.equal(PLACEHOLDER_PATH, "files"); }); it("passes a real path through untouched", () => { assert.equal(pathPlaceholder("src/index.ts"), "src/index.ts"); }); it("keeps the title line shaped `• Write files ●` while loading", () => { const line = new TitleRow(deps(), plainTheme, DOT_MARKER, "Write", pathPlaceholder(""), loadingSuffix(plainTheme, true)).render(60)[0] ?? ""; assert.equal(line, ` ${DOT_MARKER} Write ${PLACEHOLDER_PATH} ${BLINK_MARKER}`); }); }); describe("loadingSuffix: 载入中的闪烁标记", () => { /** 记录 fg 调用的主题 */ function recorder(): { theme: TitleTheme; calls: Array<[string, string]> } { const calls: Array<[string, string]> = []; return { calls, theme: { fg: (color, text) => { calls.push([color, text]); return text; }, }, }; } it("is `●` in the dim slot when lit, a single blank when dark", () => { const on = recorder(); assert.equal(loadingSuffix(on.theme, true), BLINK_MARKER); assert.deepEqual(on.calls, [["dim", BLINK_MARKER]]); const off = recorder(); assert.equal(loadingSuffix(off.theme, false), " "); assert.deepEqual(off.calls, [["dim", " "]]); }); it("**keeps both phases one column** (otherwise the path window jitters every 500ms)", () => { assert.equal(widthOf(loadingSuffix(plainTheme, true)), 1); assert.equal(widthOf(loadingSuffix(plainTheme, false)), 1); assert.notEqual(loadingSuffix(plainTheme, false), "", "灭态不能是空串(那样尾部宽度会掉 2 列)"); }); }); describe("TitleRow: 行首圆点", () => { it("puts the dot in column 1 and the tool name from column 3", () => { const line = titleLine("/Users/me/x.ts", "", 60); assert.equal(line, ` ${DOT_MARKER} Write ~/x.ts`); assert.equal(line.indexOf(DOT_MARKER), 1); assert.equal(line.indexOf("Write"), 3); }); it("omits the dot (and its gap) when handed an empty dot string", () => { const line = new TitleRow(deps(), plainTheme, "", "Write", "/Users/me/x.ts", "").render(60)[0] ?? ""; assert.equal(line, " Write ~/x.ts"); }); }); describe("TitleRow: 长路径截断时行首不被挤得抖动(回归)", () => { it("keeps the dot and the suffix intact while truncating the head of the path", () => { const line = titleLine(LONG_PATH, statsSuffix(plainTheme, { added: 3, removed: 5 }), 90); assert.ok(line.startsWith(` ${DOT_MARKER} Write `), line); assert.ok(line.endsWith("(+3 -5)"), line); assert.ok(line.includes(ELLIPSIS), line); assert.equal(widthOf(line) <= 90, true, line); }); it("keeps the line within the given width across a sweep of terminal widths", () => { for (let width = 24; width <= 100; width += 1) { const line = titleLine(LONG_PATH, statsSuffix(plainTheme, { added: 123456, removed: 9999 }), width); assert.ok(widthOf(line) <= width, `line wider than ${width}: ${JSON.stringify(line)}`); } }); it("keeps the tail (file name) visible while dropping the head of a long path", () => { const line = titleLine(LONG_PATH, "", 90); assert.ok(line.includes(ELLIPSIS), line); assert.ok(line.includes("/final/renderer-impl.ts"), line); assert.ok(!line.includes("/Users/me/work"), line); }); }); describe("TitleRow: 工具名与尾部永远完整", () => { it("keeps a wide stats suffix intact and truncates the path instead", () => { const line = titleLine(LONG_PATH, statsSuffix(plainTheme, { added: 123456, removed: 9999 }), 90); assert.ok(line.endsWith("(+123k -9999)"), line); assert.ok(line.includes(ELLIPSIS), line); assert.ok(widthOf(line) <= 90, line); }); it("falls back to whole-line truncation when the path budget runs out", () => { const line = titleLine(LONG_PATH, statsSuffix(plainTheme, { added: 3, removed: 0 }), 10); assert.equal(widthOf(line) <= 10, true, line); assert.ok(line.startsWith(` ${DOT_MARKER} `), line); assert.ok(line.includes("Write"), line); }); it("renders the streaming-start form (no path yet) without a dangling separator", () => { assert.equal(titleLine("", "", 60), ` ${DOT_MARKER} Write`); }); }); describe("TitleRow: 路径与缩进", () => { it("shortens the home prefix and honours a custom indent", () => { const line = titleLine("/Users/me/work/project/src/index.ts", "", 60, { ...deps(), indent: " ", }); assert.equal(line, ` ${DOT_MARKER} Write ~/work/project/src/index.ts`); }); it("colors the path with the text token, after truncation (ANSI never reaches the measurer)", () => { const calls: Array<[string, string]> = []; const recordingTheme: TitleTheme = { fg: (color, text) => { calls.push([color, text]); return text; }, }; new TitleRow(deps(), recordingTheme, "", "Write", LONG_PATH, "").render(90); assert.equal(calls.length, 1); assert.equal(calls[0]?.[0], "text"); assert.ok(calls[0]?.[1].startsWith(ELLIPSIS), calls[0]?.[1]); }); }); describe("formatCount", () => { it("keeps counts below 10k exact", () => { assert.equal(formatCount(0), "0"); assert.equal(formatCount(1), "1"); assert.equal(formatCount(9999), "9999"); }); it("abbreviates counts at or above 10k with a k suffix", () => { assert.equal(formatCount(10_000), "10k"); assert.equal(formatCount(10_043), "10k"); assert.equal(formatCount(11_133), "11.1k"); assert.equal(formatCount(10_450), "10.5k"); assert.equal(formatCount(99_999), "100k"); assert.equal(formatCount(123_456), "123k"); assert.equal(formatCount(1_234_567), "1235k"); }); }); describe("statsSuffix", () => { /** 记录 fg 调用的主题,用来断言着色 token。 */ function recorder(): { theme: TitleTheme; calls: Array<[string, string]> } { const calls: Array<[string, string]> = []; return { calls, theme: { fg: (color, text) => { calls.push([color, text]); return text; }, }, }; } it("returns an empty string when there is nothing to report", () => { assert.equal(statsSuffix(plainTheme, undefined), ""); assert.equal(statsSuffix(plainTheme, { added: 0, removed: 0 }), ""); }); it("omits the side that is zero", () => { assert.equal(statsSuffix(plainTheme, { added: 3, removed: 0 }), "(+3)"); assert.equal(statsSuffix(plainTheme, { added: 0, removed: 5 }), "(-5)"); }); it("shows both sides with the diff color tokens", () => { const { theme, calls } = recorder(); assert.equal(statsSuffix(theme, { added: 3, removed: 5 }), "(+3 -5)"); assert.deepEqual(calls, [ ["toolDiffAdded", "+3"], ["toolDiffRemoved", "-5"], ["dim", "("], ["dim", ")"], ]); }); it("abbreviates huge counts (the tail must stay narrow)", () => { assert.equal(statsSuffix(plainTheme, { added: 10_043, removed: 11_133 }), "(+10k -11.1k)"); }); }); describe("ratioBar: 行尾红绿条(用户 2026-10-30 定)", () => { /** 记录 fg 调用的主题,用来断言着色 token。 */ function recorder(): { theme: TitleTheme; calls: Array<[string, string]> } { const calls: Array<[string, string]> = []; return { calls, theme: { fg: (color, text) => { calls.push([color, text]); return text; }, }, }; } /** 按颜色拆格:两侧共用 `━`,所以只能靠 fg 槽区分。 */ function splitByColor(stats: { added: number; removed: number }): { green: number; red: number } { const calls: Array<[string, string]> = []; const theme: TitleTheme = { fg: (color, text) => { calls.push([color, text]); return text; }, }; const bar = ratioBar(theme, stats); assert.ok(bar.startsWith("[") && bar.endsWith("]"), `条必须带括号:${JSON.stringify(bar)}`); const count = (slot: string): number => calls.filter(([name]) => name === slot).reduce((sum, [, text]) => sum + text.length, 0); return { green: count("success"), red: count("error") }; } it("is always RATIO_BAR_WIDTH columns wide, brackets included", () => { assert.equal(RATIO_BAR_WIDTH, 12); for (const stats of [ { added: 1, removed: 1 }, { added: 54, removed: 7 }, { added: 0, removed: 5 }, { added: 999, removed: 0 }, { added: 100_000, removed: 12 }, ]) { const bar = ratioBar(plainTheme, stats); assert.equal(widthOf(bar), RATIO_BAR_WIDTH, `${JSON.stringify(stats)} 的条宽度:${JSON.stringify(bar)}`); assert.equal(bar.length, RATIO_BAR_WIDTH, "括号与格子都是 1 列,字符数应等宽"); } }); it("splits evenly for a 1:1 change", () => { assert.deepEqual(splitByColor({ added: 5, removed: 5 }), { green: 5, red: 5 }); }); it("follows the added share, rounded", () => { // 54 / 61 ≈ 0.885 → 9 格绿,1 格红 assert.deepEqual(splitByColor({ added: 54, removed: 7 }), { green: 9, red: 1 }); // 9 / 10 = 0.9 → 9 格绿 assert.deepEqual(splitByColor({ added: 9, removed: 1 }), { green: 9, red: 1 }); }); it("gives a non-zero side at least one cell (1:99 must not look like a pure delete)", () => { const tiny = splitByColor({ added: 1, removed: 99 }); assert.equal(tiny.green, 1, "新增再少也要占一格"); assert.equal(tiny.red, 9); const mostlyGreen = splitByColor({ added: 99, removed: 1 }); assert.equal(mostlyGreen.red, 1, "删除再少也要占一格"); assert.equal(mostlyGreen.green, 9); }); it("gives the whole bar to the only non-zero side", () => { assert.deepEqual(splitByColor({ added: 12, removed: 0 }), { green: 10, red: 0 }); assert.deepEqual(splitByColor({ added: 0, removed: 12 }), { green: 0, red: 10 }); }); it("keeps the ratio when the counts are abbreviated in the numbers beside it", () => { // 数字缩成 `+10k -11.1k`,条按真实比例(不是缩略后的值)算 assert.deepEqual(splitByColor({ added: 10_043, removed: 11_133 }), { green: 5, red: 5 }); }); it("paints green / red with the statusline tokens and the brackets dim", () => { const { theme, calls } = recorder(); assert.equal(ratioBar(theme, { added: 6, removed: 4 }), `[${RATIO_BAR_CELL.repeat(6)}${RATIO_BAR_CELL.repeat(4)}]`); assert.deepEqual(calls, [ ["success", RATIO_BAR_CELL.repeat(6)], ["error", RATIO_BAR_CELL.repeat(4)], ["dim", "["], ["dim", "]"], ]); }); it("skips the empty side instead of emitting an empty colour run", () => { const { theme, calls } = recorder(); ratioBar(theme, { added: 3, removed: 0 }); assert.deepEqual(calls.map(([slot]) => slot), ["success", "dim", "dim"]); }); it("returns nothing when there is nothing to report", () => { assert.equal(ratioBar(plainTheme, undefined), ""); assert.equal(ratioBar(plainTheme, { added: 0, removed: 0 }), ""); // 防御:非有限值 / 负数被当成 0 assert.equal(ratioBar(plainTheme, { added: Number.NaN, removed: 0 }), ""); assert.equal(ratioBar(plainTheme, { added: -5, removed: 0 }), ""); assert.deepEqual(splitByColor({ added: Number.POSITIVE_INFINITY, removed: 4 }), { green: 0, red: 10 }); }); }); describe("shortenPath", () => { it("shortens the home prefix at a path boundary only", () => { assert.equal(shortenPath("/Users/me/work/index.ts", "/Users/me"), "~/work/index.ts"); assert.equal(shortenPath("/Users/me", "/Users/me"), "~"); // `/Users/melo` 不该被缩成 `~lo` assert.equal(shortenPath("/Users/melo/index.ts", "/Users/me"), "/Users/melo/index.ts"); }); it("leaves the path alone without a home directory or outside of it", () => { assert.equal(shortenPath("/tmp/renderer.ts", ""), "/tmp/renderer.ts"); assert.equal(shortenPath("/tmp/renderer.ts", "/Users/me"), "/tmp/renderer.ts"); }); }); describe("truncateStartToWidth", () => { it("returns the text unchanged when it fits", () => { assert.equal(truncateStartToWidth("abcdef", 6, widthOf), "abcdef"); }); it("keeps the tail and marks the dropped head with an ellipsis", () => { assert.equal(truncateStartToWidth("abcdef", 4, widthOf), "…def"); assert.equal(truncateStartToWidth("abcdef", 1, widthOf), ELLIPSIS); }); it("returns nothing when there is no room at all", () => { assert.equal(truncateStartToWidth("abcdef", 0, widthOf), ""); assert.equal(truncateStartToWidth("abcdef", -3, widthOf), ""); }); it("measures CJK characters as two columns", () => { assert.equal(truncateStartToWidth("路径文件名", 5, widthOf), "…件名"); }); }); describe("TitleRow: 红绿条的位置与取舍", () => { const stats = { added: 54, removed: 7 }; /** 带完整尾部与条的一条标题行。 */ function barTitle(path: string, width: number, rowDeps: TitleRowDeps = deps()): string { return ( new TitleRow( rowDeps, plainTheme, DOT_MARKER, "Edit", path, statsSuffix(plainTheme, stats), ratioBar(plainTheme, stats), ).render(width)[0] ?? "" ); } it("sits after the counts, separated by one space", () => { const line = barTitle("src/core/game.js", 80); assert.equal(line, ` ${DOT_MARKER} Edit src/core/game.js (+54 -7) [${RATIO_BAR_CELL.repeat(9)}${RATIO_BAR_CELL}]`); assert.ok(line.endsWith("]"), line); }); it("takes its 13 columns out of the path budget (not out of the line width)", () => { const line = barTitle(LONG_PATH, 90); assert.ok(widthOf(line) <= 90, `不得超宽:${widthOf(line)}`); assert.ok(line.endsWith("]"), `宽终端里条应被完整画出:${JSON.stringify(line)}`); // 同时带条的版本路径更短 —— 预算真的从路径里扣了,不是靠溢出终端 const withoutBar = new TitleRow(deps(), plainTheme, DOT_MARKER, "Edit", LONG_PATH, statsSuffix(plainTheme, stats)).render(90)[0] ?? ""; assert.ok(widthOf(withoutBar) <= 90); // 两条行都顶满 90 列,所以比「除首尾之外剩下的路径区」而不是整行长度 const pathColsOf = (out: string, hasBar: boolean): number => widthOf(out) - widthOf(` ${DOT_MARKER} Edit `) - widthOf(statsSuffix(plainTheme, stats)) - (hasBar ? 1 + RATIO_BAR_WIDTH : 0); assert.equal( pathColsOf(line, true) + 1 + RATIO_BAR_WIDTH, pathColsOf(withoutBar, false), `条的 13 列应原封不动地从路径预算里扣:${pathColsOf(line, true)} + 13 !== ${pathColsOf(withoutBar, false)}`, ); }); it("is dropped before the path gets squeezed (numbers are the precise reading)", () => { // 刚好装不下「条 + 足够长的路径」的宽度 for (let width = 24; width <= 60; width += 1) { const line = barTitle(LONG_PATH, width); assert.ok(widthOf(line) <= width, `${width}: ${JSON.stringify(line)}`); const hasBar = line.endsWith("]"); const pathCols = widthOf(line) - widthOf(` ${DOT_MARKER} Edit `) - widthOf(statsSuffix(plainTheme, stats)) - (hasBar ? 1 + RATIO_BAR_WIDTH : 0); if (hasBar) assert.ok(pathCols >= MIN_PATH_COLS_WITH_BAR, `${width}: 画条时路径应留够 ${MIN_PATH_COLS_WITH_BAR} 列,实得 ${pathCols}`); } }); it("never widens the line across terminal widths", () => { for (let width = 20; width <= 120; width += 1) { const line = barTitle(LONG_PATH, width); assert.ok(widthOf(line) <= width, `${width}: ${JSON.stringify(line)}`); } }); it("is omitted while loading (no stats yet) and when nothing changed", () => { const loading = new TitleRow(deps(), plainTheme, DOT_MARKER, "Edit", PLACEHOLDER_PATH, loadingSuffix(plainTheme, true)).render(80)[0] ?? ""; assert.equal(loading, ` ${DOT_MARKER} Edit files ${BLINK_MARKER}`); const unchanged = new TitleRow( deps(), plainTheme, DOT_MARKER, "Edit", "src/a.ts", statsSuffix(plainTheme, { added: 0, removed: 0 }), ratioBar(plainTheme, { added: 0, removed: 0 }), ).render(80)[0] ?? ""; assert.equal(unchanged, ` ${DOT_MARKER} Edit src/a.ts`); }); it("is skipped in the whole-line fallback (a half-drawn bar would lie)", () => { const line = barTitle(LONG_PATH, 12); assert.equal(line.includes("["), false, `极窄宽度下不应画半条:${JSON.stringify(line)}`); assert.ok(widthOf(line) <= 12, line); }); });