xonecas.io
70160
Ce

cel-tui / commit 48a7711

refactor(core): cache text line counts and add real-world benchmarks

xonecas2026-04-25 48a7711cc4d5e13edc0012b153aae7888e0a04d0 parent 96f6ba3

9 files changed

benchmarks/RESULTS.md+57−2
@@ -148,6 +148,60 @@ Differential rendering has near-constant cost regardless of change amount — do
148148 | Re-render +1 message diff | 248 µs | 4,030 |
149149 | 1,000 re-renders batch | 67 ms | 14,800 |
150150
151+## Real-World Synthetic App Shapes
152+
153+Focused run for the new `benchmarks/real-world.bench.ts` cases.
154+These numbers use fixtures shaped after `mini-coder` and `mini-coder-next`:
155+long unvirtualized conversations, syntax-highlight-like wrapping HStack token
156+rows, and mini-coder-style virtualized scrollback slices.
157+
158+**Runtime:** Bun 1.3.13 (x64-linux)
159+**Date:** 2026-04-25
160+
161+### mini-coder-next-style unvirtualized conversation
162+
163+| Scenario | Time |
164+| -------------------------------------- | ------ |
165+| Layout 100 messages (120×40) | 71 ms |
166+| Layout 500 messages (120×40) | 348 ms |
167+| Layout 1,000 messages (120×40) | 740 ms |
168+| Paint pre-laid 500 messages (120×40) | 4.0 ms |
169+| Paint pre-laid 1,000 messages (120×40) | 6.5 ms |
170+| Full render 250 messages (120×40) | 172 ms |
171+| Diff render 250 → 251 messages | 179 ms |
172+
173+The new benchmark exposes the real bottleneck that the older app-tree cases
174+missed: long unvirtualized conversation layout dominates render time. Paint is
175+much smaller but still grows for token-heavy visible content.
176+
177+### Long wrapping HStack token lists
178+
179+| Scenario | Time |
180+| ---------------------------- | ------ |
181+| Layout 100 tokens (120×40) | 314 µs |
182+| Layout 500 tokens (120×40) | 1.6 ms |
183+| Layout 1,000 tokens (120×40) | 3.2 ms |
184+| Paint 100 tokens (120×40) | 771 µs |
185+| Paint 500 tokens (120×40) | 3.5 ms |
186+| Paint 1,000 tokens (120×40) | 6.0 ms |
187+
188+These rows mimic `SyntaxHighlight` output: each logical line becomes an
189+`HStack({ flexWrap: "wrap" })` with many styled `Text` spans.
190+
191+### mini-coder-style virtualized conversation
192+
193+| Scenario | Time |
194+| ----------------------------------------------- | ------ |
195+| Layout total 1,000 / visible 40 (120×40) | 31 ms |
196+| Layout total 5,000 / visible 40 (120×40) | 26 ms |
197+| Paint total 1,000 / visible 40 (120×40) | 1.6 ms |
198+| Paint total 5,000 / visible 40 (120×40) | 1.6 ms |
199+| Measure content height, 250 messages, width 118 | 56 ms |
200+
201+The virtualized shape is mostly insensitive to total message count because the
202+rendered node count is bounded by the visible slice plus spacers. The remaining
203+cost is from the visible token-heavy message nodes and cold height measurement.
204+
151205 ## Ink Raw Numbers
152206
153207 Ink v6.8.0, visually similar tree to cel-tui's "ink-comparable"
@@ -177,8 +231,9 @@ Run 3: 1,000 re-renders: 1450.79 ms — 1,451 µs/render
177231 # cel-tui benchmarks
178232 cd cel-tui
179233 bun install
180-bun run benchmarks/run-all.ts # full suite
181-bun run benchmarks/e2e.bench.ts # just the headline numbers
234+bun run benchmarks/run-all.ts # full suite
235+bun run benchmarks/e2e.bench.ts # just the headline numbers
236+bun run benchmarks/real-world.bench.ts # real app-shaped stress cases
182237
183238 # Ink benchmarks
184239 git clone https://github.com/vadimdemedes/ink.git /tmp/ink-bench
benchmarks/helpers.ts+208−2
@@ -2,8 +2,8 @@
22 * Shared helpers for benchmark tree construction.
33 */
44
5-import type { Node, ContainerNode } from "@cel-tui/types";
6-import { VStack, HStack, Text, TextInput } from "@cel-tui/core";
5+import type { ContainerNode, Node, StyleProps } from "@cel-tui/types";
6+import { HStack, Text, TextInput, VStack } from "@cel-tui/core";
77
88 /** Build a flat VStack with N Text children. */
99 export function flatTree(n: number): ContainerNode {
@@ -129,6 +129,212 @@ export function appTree(messageCount: number): ContainerNode {
129129 ]);
130130 }
131131
132+const TOKEN_TEXT = [
133+ "const",
134+ " ",
135+ "result",
136+ " ",
137+ "=",
138+ " ",
139+ "await",
140+ " ",
141+ "agent",
142+ ".",
143+ "run",
144+ "(",
145+ "{",
146+ " cwd",
147+ ": ",
148+ "projectRoot",
149+ ", ",
150+ "prompt",
151+ ": ",
152+ "message",
153+ " }",
154+ ")",
155+ ";",
156+ " // stream tool output",
157+];
158+
159+const TOKEN_STYLES: StyleProps[] = [
160+ { fgColor: "color05", bold: true },
161+ { fgColor: "color07" },
162+ { fgColor: "color06" },
163+ { fgColor: "color07" },
164+ { fgColor: "color08" },
165+ { fgColor: "color07" },
166+ { fgColor: "color05", bold: true },
167+ { fgColor: "color07" },
168+ { fgColor: "color02" },
169+ { fgColor: "color08" },
170+ { fgColor: "color04" },
171+ { fgColor: "color08" },
172+ { fgColor: "color03" },
173+ { fgColor: "color06" },
174+ { fgColor: "color08" },
175+ { fgColor: "color02" },
176+ { fgColor: "color08" },
177+ { fgColor: "color06" },
178+ { fgColor: "color08" },
179+ { fgColor: "color02" },
180+ { fgColor: "color03" },
181+ { fgColor: "color08" },
182+ { fgColor: "color08" },
183+ { fgColor: "color08", italic: true },
184+];
185+
186+const MESSAGE_BODIES = [
187+ "I'll inspect the rendering pipeline and then patch the benchmark helpers.",
188+ "Please add a regression case for wide token rows and scrollback-heavy conversations.",
189+ "tool: grep completed with 14 matches across packages/core/src/layout.ts and paint.ts",
190+ "The fix preserves controlled scroll offsets while keeping the cursor visible.",
191+];
192+
193+const MESSAGE_KINDS = ["user", "assistant", "tool"] as const;
194+
195+/** Build one wrapping HStack row with many styled Text token children. */
196+export function hstackTokenRow(tokenCount: number): ContainerNode {
197+ const children: Node[] = [];
198+ for (let i = 0; i < tokenCount; i++) {
199+ const index = i % TOKEN_TEXT.length;
200+ children.push(Text(TOKEN_TEXT[index], TOKEN_STYLES[index]));
201+ }
202+ return HStack({ flexWrap: "wrap" }, children);
203+}
204+
205+/** Build a syntax-highlight-like block without depending on clew. */
206+export function syntaxLikeBlock(
207+ lines: number,
208+ tokensPerLine: number,
209+): ContainerNode {
210+ const children: Node[] = [];
211+ for (let i = 0; i < lines; i++) {
212+ children.push(
213+ HStack({ flexWrap: "wrap" }, [
214+ Text(`${String(i + 1).padStart(3, " ")} │ `, { fgColor: "color08" }),
215+ ...hstackTokenRow(tokensPerLine).children,
216+ ]),
217+ );
218+ }
219+ return VStack({ gap: 0 }, children);
220+}
221+
222+function miniCoderMessage(index: number): ContainerNode {
223+ const kind = MESSAGE_KINDS[index % MESSAGE_KINDS.length];
224+ const isUser = kind === "user";
225+ const isTool = kind === "tool";
226+ const title = isUser ? "user" : isTool ? "tool" : "assistant";
227+ const color = isUser ? "color04" : isTool ? "color03" : "color02";
228+ const children: Node[] = [
229+ HStack({ gap: 1 }, [
230+ Text(title, { bold: true, fgColor: color }),
231+ Text(`#${index}`, { fgColor: "color08" }),
232+ Text(isTool ? "shell" : "chat", { fgColor: "color08" }),
233+ ]),
234+ Text(MESSAGE_BODIES[index % MESSAGE_BODIES.length], { wrap: "word" }),
235+ ];
236+
237+ if (!isUser) {
238+ children.push(syntaxLikeBlock(isTool ? 3 : 5, isTool ? 10 : 16));
239+ }
240+
241+ children.push(
242+ HStack({ gap: 1, flexWrap: "wrap" }, [
243+ HStack({ padding: { x: 1 }, bgColor: "color08" }, [
244+ Text(isTool ? "tool-call" : "tokens", { fgColor: "color00" }),
245+ ]),
246+ HStack({ padding: { x: 1 }, bgColor: "color00" }, [
247+ Text(isTool ? "exit 0" : `${800 + (index % 400)} tok`, {
248+ fgColor: "color07",
249+ }),
250+ ]),
251+ Text("cached", { fgColor: "color08" }),
252+ ]),
253+ );
254+
255+ return VStack(
256+ {
257+ gap: 1,
258+ padding: { x: 1, y: 1 },
259+ bgColor: isUser ? "color00" : undefined,
260+ fgColor: "color07",
261+ },
262+ children,
263+ );
264+}
265+
266+function miniCoderRoot(messages: Node[], totalMessages: number): ContainerNode {
267+ return VStack({ height: "100%", gap: 1, padding: { x: 1, y: 1 } }, [
268+ VStack(
269+ { flex: 1, gap: 1, overflow: "scroll", scrollOffset: Infinity },
270+ messages,
271+ ),
272+ HStack({ height: 1, gap: 1 }, [
273+ Text("mini-coder", { bold: true, fgColor: "color02" }),
274+ Text(`${totalMessages} messages`, { fgColor: "color08" }),
275+ Text("model: sonnet", { fgColor: "color08" }),
276+ ]),
277+ TextInput({
278+ height: 3,
279+ value: "Summarize the benchmark bottleneck and propose the next patch.",
280+ onChange: () => {},
281+ placeholder: Text("message mini-coder", { fgColor: "color08" }),
282+ bgColor: "color00",
283+ fgColor: "color07",
284+ }),
285+ ]);
286+}
287+
288+/** Build a mini-coder-next-like unvirtualized conversation tree. */
289+export function miniCoderNextConversationTree(
290+ messageCount: number,
291+): ContainerNode {
292+ const messages: Node[] = [];
293+ for (let i = 0; i < messageCount; i++) {
294+ messages.push(miniCoderMessage(i));
295+ }
296+ return miniCoderRoot(messages, messageCount);
297+}
298+
299+/**
300+ * Build a mini-coder-like virtualized conversation tree.
301+ * Only a visible slice is rendered; fixed-height spacers represent the rest.
302+ */
303+export function miniCoderVirtualizedConversationTree(
304+ totalMessages: number,
305+ visibleMessages: number,
306+): ContainerNode {
307+ const start = Math.max(0, totalMessages - visibleMessages);
308+ const hiddenBefore = start;
309+ const hiddenAfter = Math.max(0, totalMessages - start - visibleMessages);
310+ const messages: Node[] = [];
311+
312+ if (hiddenBefore > 0) {
313+ messages.push(VStack({ height: hiddenBefore * 8 }, []));
314+ }
315+ for (
316+ let i = start;
317+ i < Math.min(totalMessages, start + visibleMessages);
318+ i++
319+ ) {
320+ messages.push(miniCoderMessage(i));
321+ }
322+ if (hiddenAfter > 0) {
323+ messages.push(VStack({ height: hiddenAfter * 8 }, []));
324+ }
325+
326+ return miniCoderRoot(messages, totalMessages);
327+}
328+
329+/** Representative mini-coder-next message nodes for content-height measurement. */
330+export function miniCoderNextMeasureNodes(count: number): Node[] {
331+ const nodes: Node[] = [];
332+ for (let i = 0; i < count; i++) {
333+ nodes.push(miniCoderMessage(i));
334+ }
335+ return nodes;
336+}
337+
132338 /** Pure ASCII string for width benchmarking. */
133339 export const ASCII_STRING =
134340 "The quick brown fox jumps over the lazy dog. 0123456789!@#$%^&*()";
benchmarks/real-world.bench.ts+214−0
@@ -0,0 +1,214 @@
1+/**
2+ * Benchmark: real-world synthetic app shapes.
3+ *
4+ * These fixtures mimic mini-coder / mini-coder-next node tree shapes without
5+ * importing those apps: long unvirtualized conversations, virtualized message
6+ * windows, syntax-highlight-like blocks, and wide wrapping token rows.
7+ */
8+
9+import { bench, group, run } from "mitata";
10+import { CellBuffer, emitBuffer, measureContentHeight } from "@cel-tui/core";
11+import { emitDiff } from "../packages/core/src/emitter.js";
12+import { layout } from "../packages/core/src/layout.js";
13+import { paint } from "../packages/core/src/paint.js";
14+import { clearTextMeasurementCaches } from "../packages/core/src/text-layout.js";
15+import { clearVisibleWidthCache } from "../packages/core/src/width.js";
16+import {
17+ hstackTokenRow,
18+ miniCoderNextConversationTree,
19+ miniCoderNextMeasureNodes,
20+ miniCoderVirtualizedConversationTree,
21+} from "./helpers.js";
22+
23+const W = 120;
24+const H = 40;
25+
26+function clearMeasurementCaches(): void {
27+ clearTextMeasurementCaches();
28+ clearVisibleWidthCache();
29+}
30+
31+// --- mini-coder-next: unvirtualized long conversation layout ---
32+
33+group("real-world: mini-coder-next long conversation layout", () => {
34+ const t100 = miniCoderNextConversationTree(100);
35+ const t500 = miniCoderNextConversationTree(500);
36+ const t1000 = miniCoderNextConversationTree(1000);
37+
38+ bench("100 messages (120×40)", () => {
39+ layout(t100, W, H);
40+ });
41+
42+ bench("500 messages (120×40)", () => {
43+ layout(t500, W, H);
44+ });
45+
46+ bench("1000 messages (120×40)", () => {
47+ layout(t1000, W, H);
48+ });
49+});
50+
51+// --- mini-coder-next: cold-cache first render/layout ---
52+
53+group("real-world: mini-coder-next cold first render", () => {
54+ const t100 = miniCoderNextConversationTree(100);
55+ const t500 = miniCoderNextConversationTree(500);
56+ const t1000 = miniCoderNextConversationTree(1000);
57+ const measureNodes = miniCoderNextMeasureNodes(250);
58+
59+ bench("cold layout 100 messages (120×40)", () => {
60+ clearMeasurementCaches();
61+ layout(t100, W, H);
62+ });
63+
64+ bench("cold layout 500 messages (120×40)", () => {
65+ clearMeasurementCaches();
66+ layout(t500, W, H);
67+ });
68+
69+ bench("cold layout 1000 messages (120×40)", () => {
70+ clearMeasurementCaches();
71+ layout(t1000, W, H);
72+ });
73+
74+ bench("cold full render 250 messages (120×40)", () => {
75+ clearMeasurementCaches();
76+ const tree = miniCoderNextConversationTree(250);
77+ const l = layout(tree, W, H);
78+ const buf = new CellBuffer(W, H);
79+ paint(l, buf);
80+ emitBuffer(buf);
81+ });
82+
83+ bench("cold measure content height 250 nodes at width 118", () => {
84+ clearMeasurementCaches();
85+ let total = 0;
86+ for (const node of measureNodes) {
87+ total += measureContentHeight(node, { width: 118 });
88+ }
89+ return total;
90+ });
91+});
92+
93+// --- mini-coder-next: paint pre-laid unvirtualized conversations ---
94+
95+group("real-world: mini-coder-next long conversation paint", () => {
96+ const l500 = layout(miniCoderNextConversationTree(500), W, H);
97+ const l1000 = layout(miniCoderNextConversationTree(1000), W, H);
98+
99+ bench("500 messages (120×40)", () => {
100+ const buf = new CellBuffer(W, H);
101+ paint(l500, buf);
102+ });
103+
104+ bench("1000 messages (120×40)", () => {
105+ const buf = new CellBuffer(W, H);
106+ paint(l1000, buf);
107+ });
108+});
109+
110+// --- mini-coder-next: full render and diff render including tree construction ---
111+
112+group("real-world: mini-coder-next e2e", () => {
113+ const prevTree = miniCoderNextConversationTree(250);
114+ const prevLayout = layout(prevTree, W, H);
115+ const prevBuf = new CellBuffer(W, H);
116+ paint(prevLayout, prevBuf);
117+
118+ bench("full render 250 messages (120×40)", () => {
119+ const tree = miniCoderNextConversationTree(250);
120+ const l = layout(tree, W, H);
121+ const buf = new CellBuffer(W, H);
122+ paint(l, buf);
123+ emitBuffer(buf);
124+ });
125+
126+ bench("diff render 250 → 251 messages (120×40)", () => {
127+ const tree = miniCoderNextConversationTree(251);
128+ const l = layout(tree, W, H);
129+ const buf = new CellBuffer(W, H);
130+ paint(l, buf);
131+ emitDiff(prevBuf, buf);
132+ });
133+});
134+
135+// --- HStack token-list stress tests ---
136+
137+group("real-world: hstack token lists", () => {
138+ const r100 = hstackTokenRow(100);
139+ const r500 = hstackTokenRow(500);
140+ const r1000 = hstackTokenRow(1000);
141+ const l100 = layout(r100, W, H);
142+ const l500 = layout(r500, W, H);
143+ const l1000 = layout(r1000, W, H);
144+
145+ bench("layout 100 tokens (120×40)", () => {
146+ layout(r100, W, H);
147+ });
148+
149+ bench("layout 500 tokens (120×40)", () => {
150+ layout(r500, W, H);
151+ });
152+
153+ bench("layout 1000 tokens (120×40)", () => {
154+ layout(r1000, W, H);
155+ });
156+
157+ bench("paint 100 tokens (120×40)", () => {
158+ const buf = new CellBuffer(W, H);
159+ paint(l100, buf);
160+ });
161+
162+ bench("paint 500 tokens (120×40)", () => {
163+ const buf = new CellBuffer(W, H);
164+ paint(l500, buf);
165+ });
166+
167+ bench("paint 1000 tokens (120×40)", () => {
168+ const buf = new CellBuffer(W, H);
169+ paint(l1000, buf);
170+ });
171+});
172+
173+// --- mini-coder: virtualized conversation layout/paint ---
174+
175+group("real-world: mini-coder virtualized conversation", () => {
176+ const v1000 = miniCoderVirtualizedConversationTree(1000, 40);
177+ const v5000 = miniCoderVirtualizedConversationTree(5000, 40);
178+ const l1000 = layout(v1000, W, H);
179+ const l5000 = layout(v5000, W, H);
180+
181+ bench("layout total 1000 / visible 40 (120×40)", () => {
182+ layout(v1000, W, H);
183+ });
184+
185+ bench("layout total 5000 / visible 40 (120×40)", () => {
186+ layout(v5000, W, H);
187+ });
188+
189+ bench("paint total 1000 / visible 40 (120×40)", () => {
190+ const buf = new CellBuffer(W, H);
191+ paint(l1000, buf);
192+ });
193+
194+ bench("paint total 5000 / visible 40 (120×40)", () => {
195+ const buf = new CellBuffer(W, H);
196+ paint(l5000, buf);
197+ });
198+});
199+
200+// --- Content height measurement for prebuilt message nodes ---
201+
202+group("real-world: content height measurement", () => {
203+ const nodes = miniCoderNextMeasureNodes(250);
204+
205+ bench("250 representative message nodes at width 118", () => {
206+ let total = 0;
207+ for (const node of nodes) {
208+ total += measureContentHeight(node, { width: 118 });
209+ }
210+ return total;
211+ });
212+});
213+
214+await run();
benchmarks/run-all.ts+2−0
@@ -11,6 +11,7 @@
1111 * bun run benchmarks/hit-test.bench.ts
1212 * bun run benchmarks/keys.bench.ts
1313 * bun run benchmarks/e2e.bench.ts
14+ * bun run benchmarks/real-world.bench.ts
1415 */
1516
1617 import { $ } from "bun";
@@ -23,6 +24,7 @@ const benchmarks = [
2324 "hit-test",
2425 "keys",
2526 "e2e",
27+ "real-world",
2628 ];
2729
2830 console.log("cel-tui benchmark suite");
packages/core/src/layout.ts+4−4
@@ -1,5 +1,5 @@
11 import type { ContainerProps, Node, SizeValue } from "@cel-tui/types";
2-import { layoutText } from "./text-layout.js";
2+import { measureTextLineCount } from "./text-layout.js";
33 import { visibleWidth } from "./width.js";
44
55 /**
@@ -100,11 +100,11 @@ function intrinsicMainSize(
100100 ): number {
101101 if (node.type === "text") {
102102 if (isVertical) {
103- return layoutText(
103+ return measureTextLineCount(
104104 node.content,
105105 Math.max(1, crossSize),
106106 node.props.wrap ?? "none",
107- ).lineCount;
107+ );
108108 }
109109 // Width (intrinsic)
110110 if (node.props.repeat === "fill") return 0;
@@ -124,7 +124,7 @@ function intrinsicMainSize(
124124 if (isVertical) {
125125 const val = node.props.value || "";
126126 const innerCrossForTI = Math.max(1, crossSize - tiPadX);
127- return layoutText(val, innerCrossForTI, "word").lineCount + tiPadY;
127+ return measureTextLineCount(val, innerCrossForTI, "word") + tiPadY;
128128 }
129129 return 0 + tiPadX;
130130 }
packages/core/src/scroll.ts+3−3
@@ -1,6 +1,6 @@
11 import type { ContainerProps } from "@cel-tui/types";
22 import type { LayoutNode } from "./layout.js";
3-import { layoutText } from "./text-layout.js";
3+import { measureTextLineCount } from "./text-layout.js";
44
55 function isVerticalScrollTarget(target: LayoutNode): boolean {
66 return target.node.type === "vstack" || target.node.type === "textinput";
@@ -50,11 +50,11 @@ export function getMaxScrollOffset(target: LayoutNode): number {
5050 const padY = (target.node.props.padding?.y ?? 0) * 2;
5151 const contentWidth = Math.max(1, rect.width - padX);
5252 const contentHeight = Math.max(0, rect.height - padY);
53- const lineCount = layoutText(
53+ const lineCount = measureTextLineCount(
5454 target.node.props.value,
5555 contentWidth,
5656 "word",
57- ).lineCount;
57+ );
5858 return Math.max(0, lineCount - contentHeight);
5959 }
6060
packages/core/src/text-layout.test.ts+23−1
@@ -1,5 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2-import { layoutText } from "./text-layout.js";
2+import { layoutText, measureTextLineCount } from "./text-layout.js";
33
44 describe("text-layout", () => {
55 test("preserves whitespace at soft wraps and maps offsets using visual lines", () => {
@@ -62,4 +62,26 @@ describe("text-layout", () => {
6262 expect(result.offsetToPosition(2)).toEqual({ line: 1, col: 0 });
6363 expect(result.positionToOffset(1, 1)).toBe(3);
6464 });
65+
66+ test("measureTextLineCount fast path counts hard lines for wrap none", () => {
67+ expect(measureTextLineCount("", 10, "none")).toBe(1);
68+ expect(measureTextLineCount("hello", 1, "none")).toBe(1);
69+ expect(measureTextLineCount("a\nb\n", 1, "none")).toBe(3);
70+ });
71+
72+ test("measureTextLineCount matches layoutText lineCount for wrapped cases", () => {
73+ const cases = [
74+ ["foo bar baz", 6],
75+ ["a b ", 3],
76+ ["a\n", 10],
77+ ["\tfoo", 6],
78+ ["世界世界", 5],
79+ ] as const;
80+
81+ for (const [value, width] of cases) {
82+ expect(measureTextLineCount(value, width, "word")).toBe(
83+ layoutText(value, width, "word").lineCount,
84+ );
85+ }
86+ });
6587 });
packages/core/src/text-layout.ts+169−2
@@ -1,6 +1,10 @@
11 import { visibleWidthFromColumn } from "./width.js";
22
33 const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
4+const whitespaceRegex = /^\s+$/u;
5+const TEXT_LINE_COUNT_CACHE_SIZE = 2048;
6+
7+type WrapMode = "none" | "word";
48
59 export interface VisualLine {
610 text: string;
@@ -39,6 +43,18 @@ interface Range {
3943 end: number;
4044 }
4145
46+interface LineCountCacheEntry {
47+ none?: number;
48+ wordByWidth?: Map<number, number>;
49+}
50+
51+const lineCountCache = new Map<string, LineCountCacheEntry>();
52+
53+/** Clear text measurement caches. Useful for cold-cache benchmarks. */
54+export function clearTextMeasurementCaches(): void {
55+ lineCountCache.clear();
56+}
57+
4258 function requiredAt<T>(
4359 items: readonly T[],
4460 index: number,
@@ -51,10 +67,33 @@ function requiredAt<T>(
5167 return item;
5268 }
5369
70+/**
71+ * Measure the number of visual lines a string occupies for the given width and
72+ * wrap mode. This avoids constructing the full `TextLayoutResult` when callers
73+ * only need line count.
74+ */
75+export function measureTextLineCount(
76+ value: string,
77+ width: number,
78+ wrap: WrapMode,
79+): number {
80+ const normalizedWidth = Math.max(1, width);
81+ const cached = getCachedLineCount(value, normalizedWidth, wrap);
82+ if (cached !== undefined) return cached;
83+
84+ const lineCount =
85+ wrap === "word"
86+ ? measureWrappedLineCount(value, normalizedWidth)
87+ : countHardLines(value);
88+
89+ cacheLineCount(value, normalizedWidth, wrap, lineCount);
90+ return lineCount;
91+}
92+
5493 export function layoutText(
5594 value: string,
5695 width: number,
57- wrap: "none" | "word",
96+ wrap: WrapMode,
5897 ): TextLayoutResult {
5998 const hardLines = splitHardLines(value);
6099 const lines: VisualLineData[] = [];
@@ -97,6 +136,134 @@ export function layoutText(
97136 };
98137 }
99138
139+function countHardLines(value: string): number {
140+ let lineCount = 1;
141+ for (let i = 0; i < value.length; i++) {
142+ if (value[i] === "\n") {
143+ lineCount++;
144+ }
145+ }
146+ return lineCount;
147+}
148+
149+function getCachedLineCount(
150+ value: string,
151+ width: number,
152+ wrap: WrapMode,
153+): number | undefined {
154+ const entry = lineCountCache.get(value);
155+ if (entry === undefined) return undefined;
156+ if (wrap === "none") return entry.none;
157+ return entry.wordByWidth?.get(width);
158+}
159+
160+function cacheLineCount(
161+ value: string,
162+ width: number,
163+ wrap: WrapMode,
164+ lineCount: number,
165+): void {
166+ let entry = lineCountCache.get(value);
167+ if (entry === undefined) {
168+ if (lineCountCache.size >= TEXT_LINE_COUNT_CACHE_SIZE) {
169+ const firstKey = lineCountCache.keys().next().value;
170+ if (firstKey !== undefined) {
171+ lineCountCache.delete(firstKey);
172+ }
173+ }
174+ entry = {};
175+ lineCountCache.set(value, entry);
176+ }
177+
178+ if (wrap === "none") {
179+ entry.none = lineCount;
180+ return;
181+ }
182+
183+ if (entry.wordByWidth === undefined) {
184+ entry.wordByWidth = new Map();
185+ }
186+ entry.wordByWidth.set(width, lineCount);
187+}
188+
189+function measureWrappedLineCount(value: string, width: number): number {
190+ let lineCount = 0;
191+ for (const hardLine of splitHardLines(value)) {
192+ lineCount += measureWrappedHardLine(
193+ value,
194+ hardLine.start,
195+ hardLine.end,
196+ width,
197+ );
198+ }
199+ return lineCount;
200+}
201+
202+function measureWrappedHardLine(
203+ value: string,
204+ start: number,
205+ end: number,
206+ width: number,
207+): number {
208+ if (start === end) {
209+ return 1;
210+ }
211+
212+ const widths: number[] = [];
213+ const whitespace: boolean[] = [];
214+ const text = value.slice(start, end);
215+ let col = 0;
216+
217+ for (const { segment } of segmenter.segment(text)) {
218+ const segmentWidth = visibleWidthFromColumn(segment, col);
219+ widths.push(segmentWidth);
220+ whitespace.push(whitespaceRegex.test(segment));
221+ col += segmentWidth;
222+ }
223+
224+ if (col <= width) {
225+ return 1;
226+ }
227+
228+ let lineCount = 0;
229+ let lineStart = 0;
230+
231+ while (lineStart < widths.length) {
232+ let lineEnd = lineStart;
233+ let lineWidth = 0;
234+ let lastBreak = -1;
235+
236+ while (lineEnd < widths.length) {
237+ const segmentWidth = widths[lineEnd];
238+ if (segmentWidth === undefined) {
239+ break;
240+ }
241+ const nextWidth = lineWidth + segmentWidth;
242+ if (nextWidth > width) break;
243+ lineWidth = nextWidth;
244+ lineEnd++;
245+ if (whitespace[lineEnd - 1]) {
246+ lastBreak = lineEnd;
247+ }
248+ }
249+
250+ lineCount++;
251+
252+ if (lineEnd >= widths.length) {
253+ break;
254+ }
255+
256+ if (lineEnd === lineStart) {
257+ lineStart++;
258+ continue;
259+ }
260+
261+ lineStart = lastBreak > lineStart ? lastBreak : lineEnd;
262+ }
263+
264+ return lineCount;
265+}
266+
100267 function splitHardLines(value: string): Range[] {
101268 const lines: Range[] = [];
102269 let start = 0;
@@ -127,7 +294,7 @@ function segmentLine(
127294 startOffset: offset,
128295 endOffset: offset + segment.length,
129296 width,
130- isWhitespace: /^\s+$/u.test(segment),
297+ isWhitespace: whitespaceRegex.test(segment),
131298 });
132299 offset += segment.length;
133300 col += width;
packages/core/src/width.ts+5−0
@@ -125,6 +125,11 @@ const TAB_STOP = 4;
125125 const WIDTH_CACHE_SIZE = 512;
126126 const widthCache = new Map<string, number>();
127127
128+/** Clear the visible-width cache. Useful for cold-cache benchmarks. */
129+export function clearVisibleWidthCache(): void {
130+ widthCache.clear();
131+}
132+
128133 function tabWidthAtColumn(column: number): number {
129134 return TAB_STOP - (column % TAB_STOP);
130135 }