xonecas.io
70160
Ce

cel-tui / commit ede7e68

refactor(core): unify text layout and scroll calculations

xonecas2026-04-07 ede7e682e027710e11628ba2f2ae3dfed8224b6c parent ed5430e

10 files changed

TODO.md+10βˆ’0
@@ -12,6 +12,14 @@ Remaining work, known bugs, and planned improvements.
1212
1313 ## Bugs / Spec Violations
1414
15+- πŸ”§ **TextInput cursor position diverges from rendered word-wrap** β€” high priority. `TextInput` paints wrapped lines with `wrapLine()` in `paint.ts`, but cursor placement uses `offsetToWrappedPos()`, which assumes hard width-based wrapping (`Math.floor(vw / width)`) instead of the same word-wrap semantics. This causes the cursor to drift by one or more columns after line wrapping, especially around spaces/word boundaries. Fix: make cursor mapping use the exact same wrapping logic as rendere …
16+
17+- πŸ”§ **Mouse wheel scrolling is too slow for scrollable containers** β€” high priority. Scroll handling in `cel.ts` applies a hardcoded `delta` of `Β±1` cell per wheel event for both controlled and uncontrolled scrollables. That makes long logs and transcripts tedious to navigate, and apps using the documented sticky-bottom chat pattern inherit the sluggish behavior unchanged. Fix: introduce a larger default wheel step and/or a configurable scroll-step API, then add tests covering multi-line m …
18+
19+- πŸ”§ **Native cursor flickers and blink cadence resets during animated re-renders** β€” high priority. When a focused `TextInput` is present, `cel.ts` emits diff output for each frame and then repositions/shows the native terminal cursor afterward. During frequent animations or streaming updates this can produce a cursor-shaped artifact near changing cells and cause terminal-specific blink instability because the cursor is repeatedly moved and shown every frame. Fix: audit cursor visibility/po …
20+
21+- πŸ”§ **Streaming wrapped Markdown with inline formatting can corrupt until rendering settles** β€” high priority. The risky behavior is in `packages/components/src/markdown.ts`: plain paragraphs render as a single `Text(..., { wrap: "word" })`, but formatted paragraphs/list items/blockquote content render as `HStack({ flexWrap: "wrap" })` trees built from split inline spans. During streaming, partial markdown can change shape across renders (for example plain text becoming a formatted span onc …
22+
1523 - πŸ”§ **Scrollbar thumb position ignores padding** β€” `paintScrollbar` in `paint.ts` computes `maxOffset = contentHeight - rect.height` without accounting for container padding, while the scroll clamping logic uses `contentHeight + padY - rect.height`. For padded scrollable containers the thumb position is slightly off.
1624
1725 - πŸ”§ **Duplicate max scroll offset calculation** β€” `getMaxScrollOffset` in `cel.ts` and `computeMaxScrollOffset` in `paint.ts` implement the same logic. Should be extracted to a shared function.
@@ -24,6 +32,8 @@ Remaining work, known bugs, and planned improvements.
2432
2533 ## API Improvements
2634
35+- ❌ **Define TextInput scroll semantics for cursor-follow and resize** β€” After the text layout refactor, the framework now has one canonical visual wrapping model, but the behavior contract around TextInput scrolling still needs to be specified. In particular: when a user has manually scrolled away from the cursor, what actions should re-enable automatic cursor-follow (typing, cursor movement, focus changes, programmatic value changes)? And when a TextInput changes height because of intrinsi …
36+
2737 - ❌ **`repeat: "fill"` should claim flex space in HStack** β€” `Text(" ", { repeat: "fill" })` inside an HStack gets width 0 because its intrinsic width is 0 and no flex distributes remaining space. The workaround is `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`, which is non-obvious. Fix: either make `repeat: "fill"` imply flex behavior in the layout engine, or document the workaround prominently. The former is preferred.
2838
2939 ## Not Yet Implemented
packages/core/src/cel.ts+1βˆ’44
@@ -26,7 +26,7 @@ import {
2626 type EditState,
2727 } from "./text-edit.js";
2828 import type { Terminal } from "./terminal.js";
29-import { visibleWidth } from "./width.js";
29+import { getMaxScrollOffset } from "./scroll.js";
3030
3131 type RenderFn = () => Node | Node[];
3232
@@ -453,49 +453,6 @@ function changeFocus(target: LayoutNode | null): void {
453453 }
454454 }
455455
456-/**
457- * Compute the maximum scroll offset for a scrollable container or TextInput.
458- * Returns 0 if content fits within the viewport.
459- */
460-function getMaxScrollOffset(target: LayoutNode): number {
461- const { rect, children } = target;
462-
463- // TextInput: compute content height from wrapped text value
464- if (target.node.type === "textinput") {
465- const w = rect.width;
466- const value = target.node.props.value;
467- let lineCount = 0;
468- for (const rawLine of value.split("\n")) {
469- const lw = visibleWidth(rawLine);
470- lineCount += w > 0 && lw > w ? Math.ceil(lw / w) : 1;
471- }
472- return Math.max(0, lineCount - rect.height);
473- }
474-
475- const isVertical = target.node.type === "vstack";
476- const props = target.node.type !== "text" ? target.node.props : null;
477- const padX = (props as any)?.padding?.x ?? 0;
478- const padY = (props as any)?.padding?.y ?? 0;
479-
480- if (isVertical) {
481- let contentHeight = 0;
482- for (const child of children) {
483- const childBottom = child.rect.y + child.rect.height - rect.y;
484- if (childBottom > contentHeight) contentHeight = childBottom;
485- }
486- // Viewport is the inner height (minus bottom padding)
487- // Content starts at padY, so contentHeight includes top padding offset
488- return Math.max(0, contentHeight + padY - rect.height);
489- } else {
490- let contentWidth = 0;
491- for (const child of children) {
492- const childRight = child.rect.x + child.rect.width - rect.x;
493- if (childRight > contentWidth) contentWidth = childRight;
494- }
495- return Math.max(0, contentWidth + padX - rect.width);
496- }
497-}
498-
499456 /**
500457 * Resolve the current scroll offset for a layout node.
501458 * Checks controlled (props.scrollOffset), then uncontrolled (path-based map).
packages/core/src/layout.test.ts+17βˆ’1
@@ -89,7 +89,7 @@ describe("layout", () => {
8989 });
9090
9191 test("CJK text word-wrap height uses visible width", () => {
92- // 6 CJK chars = 12 columns wide, wrap at width 5 β†’ ceil(12/5) = 3 lines
92+ // 6 CJK chars = 12 columns wide, wrap at width 5 β†’ 3 visual lines
9393 const node = VStack({ width: 5, height: 24 }, [
9494 Text("δΈ–η•ŒδΈ–η•ŒδΈ–η•Œ", { wrap: "word" }),
9595 ]);
@@ -97,6 +97,22 @@ describe("layout", () => {
9797 expect(childRects(result)[0]!.height).toBe(3);
9898 });
9999
100+ test("Text word-wrap height follows visual word wrapping, not hard width wrapping", () => {
101+ const node = VStack({ width: 6, height: 24 }, [
102+ Text("foo bar baz", { wrap: "word" }),
103+ ]);
104+ const result = layout(node, 80, 24);
105+ expect(childRects(result)[0]!.height).toBe(3);
106+ });
107+
108+ test("TextInput intrinsic height follows visual word wrapping", () => {
109+ const node = VStack({ width: 6, height: 24 }, [
110+ TextInput({ value: "foo bar baz", onChange: () => {} }),
111+ ]);
112+ const result = layout(node, 80, 24);
113+ expect(childRects(result)[0]!.height).toBe(3);
114+ });
115+
100116 test("emoji text intrinsic width counts width 2", () => {
101117 const node = HStack({ height: 10, alignItems: "start" }, [
102118 Text("πŸ˜€hi"), // emoji(2) + h(1) + i(1) = 4
packages/core/src/layout.ts+7βˆ’24
@@ -1,4 +1,5 @@
11 import type { Node, ContainerProps, SizeValue } from "@cel-tui/types";
2+import { layoutText } from "./text-layout.js";
23 import { visibleWidth } from "./width.js";
34
45 /**
@@ -58,20 +59,11 @@ function intrinsicMainSize(
5859 ): number {
5960 if (node.type === "text") {
6061 if (isVertical) {
61- // Height = number of lines
62- if (node.content.length === 0) return 1;
63- const lines = node.content.split("\n");
64- if (node.props.wrap === "word") {
65- let total = 0;
66- for (const line of lines) {
67- total += Math.max(
68- 1,
69- Math.ceil(visibleWidth(line) / Math.max(1, crossSize)),
70- );
71- }
72- return total;
73- }
74- return lines.length;
62+ return layoutText(
63+ node.content,
64+ Math.max(1, crossSize),
65+ node.props.wrap ?? "none",
66+ ).lineCount;
7567 }
7668 // Width (intrinsic)
7769 if (node.props.repeat === "fill") return 0;
@@ -91,16 +83,7 @@ function intrinsicMainSize(
9183 if (isVertical) {
9284 const val = node.props.value || "";
9385 const innerCrossForTI = Math.max(1, crossSize - tiPadX);
94- if (val.length === 0) return 1 + tiPadY;
95- const lines = val.split("\n");
96- let total = 0;
97- for (const line of lines) {
98- total += Math.max(
99- 1,
100- Math.ceil(visibleWidth(line) / Math.max(1, innerCrossForTI)),
101- );
102- }
103- return total + tiPadY;
86+ return layoutText(val, innerCrossForTI, "word").lineCount + tiPadY;
10487 }
10588 return 0 + tiPadX;
10689 }
packages/core/src/paint.test.ts+42βˆ’1
@@ -1,7 +1,11 @@
11 import { describe, expect, test } from "bun:test";
22 import { CellBuffer } from "./cell-buffer.js";
33 import { layout } from "./layout.js";
4-import { paint } from "./paint.js";
4+import {
5+ paint,
6+ getTextInputCursorScreenPos,
7+ setTextInputCursor,
8+} from "./paint.js";
59 import { VStack, HStack } from "./primitives/stacks.js";
610 import { Text } from "./primitives/text.js";
711 import { TextInput } from "./primitives/text-input.js";
@@ -15,6 +19,15 @@ function readRow(buf: CellBuffer, y: number): string {
1519 return row.trimEnd();
1620 }
1721
22+/** Read a row from the buffer without trimming trailing spaces. */
23+function readRawRow(buf: CellBuffer, y: number): string {
24+ let row = "";
25+ for (let x = 0; x < buf.width; x++) {
26+ row += buf.get(x, y).char;
27+ }
28+ return row;
29+}
30+
1831 /** Read all rows as strings. */
1932 function readAll(buf: CellBuffer): string[] {
2033 const rows: string[] = [];
@@ -107,6 +120,34 @@ describe("paint", () => {
107120 expect(cell.italic).toBe(true);
108121 expect(cell.underline).toBe(true);
109122 });
123+
124+ test("word-wrapped text preserves whitespace at soft wrap boundaries", () => {
125+ const node = VStack({ width: 6, height: 3 }, [
126+ Text("foo bar baz", { wrap: "word" }),
127+ ]);
128+ const ln = layout(node, 6, 3);
129+ const buf = new CellBuffer(6, 3);
130+ paint(ln, buf);
131+
132+ expect(readRawRow(buf, 0)).toBe("foo ");
133+ expect(readRawRow(buf, 1)).toBe("bar ");
134+ expect(readRawRow(buf, 2)).toBe("baz ");
135+ });
136+
137+ test("TextInput cursor screen position follows visual word wrapping", () => {
138+ const onChange = () => {};
139+ const props = {
140+ value: "foo bar baz",
141+ onChange,
142+ focused: true,
143+ };
144+
145+ setTextInputCursor(props, 5);
146+
147+ expect(
148+ getTextInputCursorScreenPos(props, { x: 0, y: 0, width: 6, height: 3 }),
149+ ).toEqual({ x: 1, y: 1 });
150+ });
110151 });
111152
112153 describe("layout-driven positioning", () => {
packages/core/src/paint.ts+13βˆ’151
@@ -2,6 +2,8 @@ import type { Color, StyleProps, TextInputProps } from "@cel-tui/types";
22 import type { Cell } from "./cell-buffer.js";
33 import { CellBuffer } from "./cell-buffer.js";
44 import type { LayoutNode, Rect } from "./layout.js";
5+import { getMaxScrollOffset } from "./scroll.js";
6+import { layoutText } from "./text-layout.js";
57 import { visibleWidth } from "./width.js";
68
79 const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
@@ -104,32 +106,6 @@ function fillBackground(
104106 }
105107 }
106108
107-/**
108- * Compute the maximum scroll offset for a scrollable container.
109- * This is the content size minus the viewport size along the main axis.
110- */
111-function computeMaxScrollOffset(ln: LayoutNode, isVertical: boolean): number {
112- const { rect, children } = ln;
113- const props = ln.node.type !== "text" ? ln.node.props : null;
114- const padX = (props as any)?.padding?.x ?? 0;
115- const padY = (props as any)?.padding?.y ?? 0;
116-
117- if (isVertical) {
118- let contentHeight = 0;
119- for (const child of children) {
120- const childBottom = child.rect.y + child.rect.height - rect.y;
121- if (childBottom > contentHeight) contentHeight = childBottom;
122- }
123- return Math.max(0, contentHeight + padY - rect.height);
124- }
125- let contentWidth = 0;
126- for (const child of children) {
127- const childRight = child.rect.x + child.rect.width - rect.x;
128- if (childRight > contentWidth) contentWidth = childRight;
129- }
130- return Math.max(0, contentWidth + padX - rect.width);
131-}
132-
133109 function paintLayoutNode(
134110 ln: LayoutNode,
135111 buf: CellBuffer,
@@ -203,7 +179,7 @@ function paintLayoutNode(
203179 if (isScrollable) {
204180 const raw = containerProps.scrollOffset ?? 0;
205181 // Clamp to valid range so apps can pass large values to mean "scroll to end"
206- const maxOffset = computeMaxScrollOffset(ln, isVertical);
182+ const maxOffset = getMaxScrollOffset(ln);
207183 scrollOffset = Math.max(0, Math.min(raw, maxOffset));
208184 }
209185
@@ -434,26 +410,11 @@ function paintText(
434410 text = content.repeat(props.repeat);
435411 }
436412
437- // Split into lines
438- const rawLines = text.split("\n");
439-
440- // Word-wrap if enabled
441- const lines: string[] = [];
442- if (props.wrap === "word") {
443- for (const rawLine of rawLines) {
444- if (visibleWidth(rawLine) <= w) {
445- lines.push(rawLine);
446- } else {
447- wrapLine(rawLine, w, lines);
448- }
449- }
450- } else {
451- lines.push(...rawLines);
452- }
413+ const textLayout = layoutText(text, w, props.wrap ?? "none");
453414
454415 // Paint lines, clipped to rect (grapheme-aware)
455- for (let row = 0; row < lines.length && row < h; row++) {
456- const line = lines[row]!;
416+ for (let row = 0; row < textLayout.lineCount && row < h; row++) {
417+ const line = textLayout.lines[row]!.text;
457418 paintLineGraphemes(line, x, y + row, w, clipRect, props, buf);
458419 }
459420 }
@@ -510,22 +471,14 @@ function paintTextInput(
510471 return;
511472 }
512473
513- // Word-wrap value (always on for TextInput) using content width
514- const lines: string[] = [];
515- for (const rawLine of value.split("\n")) {
516- if (visibleWidth(rawLine) <= cw) {
517- lines.push(rawLine);
518- } else {
519- wrapLine(rawLine, cw, lines);
520- }
521- }
474+ const textLayout = layoutText(value, cw, "word");
522475
523476 // Framework-managed scroll: auto-scroll to keep cursor visible
524477 let scrollOffset = getTextInputScroll(props);
525478
526479 if (props.focused) {
527480 const cursorOffset = getTextInputCursor(props);
528- const cursorPos = offsetToWrappedPos(value, cursorOffset, cw);
481+ const cursorPos = textLayout.offsetToPosition(cursorOffset);
529482 // Scroll down if cursor is below viewport
530483 if (cursorPos.line >= scrollOffset + ch) {
531484 scrollOffset = cursorPos.line - ch + 1;
@@ -540,8 +493,8 @@ function paintTextInput(
540493 // Paint visible lines (grapheme-aware) in content area
541494 for (let row = 0; row < ch; row++) {
542495 const lineIdx = scrollOffset + row;
543- if (lineIdx >= lines.length) break;
544- const line = lines[lineIdx]!;
496+ if (lineIdx >= textLayout.lineCount) break;
497+ const line = textLayout.lines[lineIdx]!.text;
545498 paintLineGraphemes(line, cx, cy + row, cw, clipRect, props, buf);
546499 }
547500
@@ -551,7 +504,7 @@ function paintTextInput(
551504 // for blinking.
552505 if (props.focused) {
553506 const cursorOffset = getTextInputCursor(props);
554- const pos = offsetToWrappedPos(value, cursorOffset, cw);
507+ const pos = textLayout.offsetToPosition(cursorOffset);
555508 const screenRow = pos.line - scrollOffset;
556509 if (screenRow >= 0 && screenRow < ch && pos.col < cw) {
557510 const absX = cx + pos.col;
@@ -581,43 +534,6 @@ function paintTextInput(
581534 }
582535 }
583536
584-/**
585- * Map a cursor offset in the raw value to a (line, col) position
586- * in the word-wrapped output.
587- */
588-function offsetToWrappedPos(
589- value: string,
590- cursor: number,
591- width: number,
592-): { line: number; col: number } {
593- const rawLines = value.split("\n");
594- let offset = 0;
595- let wrappedLine = 0;
596-
597- for (const rawLine of rawLines) {
598- if (cursor <= offset + rawLine.length) {
599- // Cursor is in this raw line
600- const colInRaw = cursor - offset;
601- if (width <= 0) return { line: wrappedLine, col: colInRaw };
602- // Compute visible width of text before cursor
603- const textBeforeCursor = rawLine.slice(0, colInRaw);
604- const vw = visibleWidth(textBeforeCursor);
605- const extraLines = Math.floor(vw / width);
606- return { line: wrappedLine + extraLines, col: vw % width };
607- }
608- // Count wrapped lines for this raw line
609- const lineVW = visibleWidth(rawLine);
610- if (lineVW <= width || width <= 0) {
611- wrappedLine += 1;
612- } else {
613- wrappedLine += Math.ceil(lineVW / width);
614- }
615- offset += rawLine.length + 1; // +1 for \n
616- }
617-
618- return { line: wrappedLine, col: 0 };
619-}
620-
621537 // --- Framework-managed state ---
622538
623539 import type { ContainerProps } from "@cel-tui/types";
@@ -653,7 +569,8 @@ export function getTextInputCursorScreenPos(
653569 if (cw <= 0 || ch <= 0) return null;
654570
655571 const cursorOffset = getTextInputCursor(props);
656- const pos = offsetToWrappedPos(props.value, cursorOffset, cw);
572+ const textLayout = layoutText(props.value, cw, "word");
573+ const pos = textLayout.offsetToPosition(cursorOffset);
657574 const scrollOffset = getTextInputScroll(props);
658575 const screenRow = pos.line - scrollOffset;
659576
@@ -692,58 +609,3 @@ export function setTextInputScroll(
692609 ): void {
693610 textInputScrolls.set(props.onChange, scroll);
694611 }
695-
696-/**
697- * Simple word-wrap: break a line into multiple lines at word boundaries.
698- */
699-function wrapLine(line: string, width: number, out: string[]): void {
700- if (width <= 0) return;
701-
702- let current = "";
703- let currentW = 0;
704- const words = line.split(" ");
705-
706- for (const word of words) {
707- const wordW = visibleWidth(word);
708- if (currentW === 0) {
709- current = word;
710- currentW = wordW;
711- } else if (currentW + 1 + wordW <= width) {
712- current += " " + word;
713- currentW += 1 + wordW;
714- } else {
715- out.push(current);
716- current = word;
717- currentW = wordW;
718- }
719-
720- // Handle words longer than width (break by grapheme)
721- while (currentW > width) {
722- let taken = "";
723- let takenW = 0;
724- let rest = "";
725- let inRest = false;
726- for (const { segment } of segmenter.segment(current)) {
727- if (inRest) {
728- rest += segment;
729- continue;
730- }
731- const gw = visibleWidth(segment);
732- if (takenW + gw > width) {
733- rest += segment;
734- inRest = true;
735- } else {
736- taken += segment;
737- takenW += gw;
738- }
739- }
740- out.push(taken);
741- current = rest;
742- currentW = visibleWidth(rest);
743- }
744- }
745-
746- if (current.length > 0) {
747- out.push(current);
748- }
749-}
packages/core/src/scroll.test.ts+41βˆ’0
@@ -0,0 +1,41 @@
1+import { describe, expect, test } from "bun:test";
2+import { layout } from "./layout.js";
3+import { VStack } from "./primitives/stacks.js";
4+import { Text } from "./primitives/text.js";
5+import { TextInput } from "./primitives/text-input.js";
6+import { getMaxScrollOffset } from "./scroll.js";
7+
8+describe("scroll", () => {
9+ test("TextInput max scroll offset uses visual wrapping and padding", () => {
10+ const root = layout(
11+ VStack({ width: 8, height: 4 }, [
12+ TextInput({
13+ width: 8,
14+ height: 4,
15+ padding: { x: 1, y: 1 },
16+ value: "foo bar baz",
17+ onChange: () => {},
18+ }),
19+ ]),
20+ 8,
21+ 4,
22+ );
23+
24+ expect(getMaxScrollOffset(root.children[0]!)).toBe(1);
25+ });
26+
27+ test("scrollable VStack max scroll offset matches content overflow", () => {
28+ const root = layout(
29+ VStack({ width: 10, height: 3, overflow: "scroll" }, [
30+ Text("line0"),
31+ Text("line1"),
32+ Text("line2"),
33+ Text("line3"),
34+ ]),
35+ 10,
36+ 3,
37+ );
38+
39+ expect(getMaxScrollOffset(root)).toBe(1);
40+ });
41+});
packages/core/src/scroll.ts+44βˆ’0
@@ -0,0 +1,44 @@
1+import type { LayoutNode } from "./layout.js";
2+import { layoutText } from "./text-layout.js";
3+
4+/**
5+ * Compute the maximum scroll offset for a scrollable layout node.
6+ * Returns 0 if content fits within the viewport.
7+ */
8+export function getMaxScrollOffset(target: LayoutNode): number {
9+ const { rect, children } = target;
10+
11+ if (target.node.type === "textinput") {
12+ const padX = (target.node.props.padding?.x ?? 0) * 2;
13+ const padY = (target.node.props.padding?.y ?? 0) * 2;
14+ const contentWidth = Math.max(1, rect.width - padX);
15+ const contentHeight = Math.max(0, rect.height - padY);
16+ const lineCount = layoutText(
17+ target.node.props.value,
18+ contentWidth,
19+ "word",
20+ ).lineCount;
21+ return Math.max(0, lineCount - contentHeight);
22+ }
23+
24+ const isVertical = target.node.type === "vstack";
25+ const props = target.node.type !== "text" ? target.node.props : null;
26+ const padX = (props as any)?.padding?.x ?? 0;
27+ const padY = (props as any)?.padding?.y ?? 0;
28+
29+ if (isVertical) {
30+ let contentHeight = 0;
31+ for (const child of children) {
32+ const childBottom = child.rect.y + child.rect.height - rect.y;
33+ if (childBottom > contentHeight) contentHeight = childBottom;
34+ }
35+ return Math.max(0, contentHeight + padY - rect.height);
36+ }
37+
38+ let contentWidth = 0;
39+ for (const child of children) {
40+ const childRight = child.rect.x + child.rect.width - rect.x;
41+ if (childRight > contentWidth) contentWidth = childRight;
42+ }
43+ return Math.max(0, contentWidth + padX - rect.width);
44+}
packages/core/src/text-layout.test.ts+48βˆ’0
@@ -0,0 +1,48 @@
1+import { describe, expect, test } from "bun:test";
2+import { layoutText } from "./text-layout.js";
3+
4+describe("text-layout", () => {
5+ test("preserves whitespace at soft wraps and maps offsets using visual lines", () => {
6+ const result = layoutText("foo bar baz", 6, "word");
7+
8+ expect(result.lines.map((line) => line.text)).toEqual([
9+ "foo ",
10+ "bar ",
11+ "baz",
12+ ]);
13+ expect(result.lineCount).toBe(3);
14+
15+ expect(result.offsetToPosition(4)).toEqual({ line: 1, col: 0 });
16+ expect(result.offsetToPosition(5)).toEqual({ line: 1, col: 1 });
17+ expect(result.offsetToPosition(8)).toEqual({ line: 2, col: 0 });
18+ });
19+
20+ test("preserves repeated and trailing spaces", () => {
21+ const result = layoutText("a b ", 3, "word");
22+
23+ expect(result.lines.map((line) => line.text)).toEqual(["a ", "b "]);
24+ expect(result.offsetToPosition(3)).toEqual({ line: 1, col: 0 });
25+ expect(result.offsetToPosition(5)).toEqual({ line: 1, col: 2 });
26+ });
27+
28+ test("preserves explicit trailing newline as an empty final visual line", () => {
29+ const result = layoutText("a\n", 10, "word");
30+
31+ expect(result.lines.map((line) => line.text)).toEqual(["a", ""]);
32+ expect(result.lineCount).toBe(2);
33+ expect(result.offsetToPosition(1)).toEqual({ line: 0, col: 1 });
34+ expect(result.offsetToPosition(2)).toEqual({ line: 1, col: 0 });
35+ });
36+
37+ test("wraps unbroken wide graphemes by grapheme boundaries", () => {
38+ const result = layoutText("δΈ–η•ŒδΈ–η•Œ", 5, "word");
39+
40+ expect(
41+ result.lines.map((line) => ({ text: line.text, width: line.width })),
42+ ).toEqual([
43+ { text: "δΈ–η•Œ", width: 4 },
44+ { text: "δΈ–η•Œ", width: 4 },
45+ ]);
46+ expect(result.offsetToPosition(2)).toEqual({ line: 1, col: 0 });
47+ });
48+});
packages/core/src/text-layout.ts+250βˆ’0
@@ -0,0 +1,250 @@
1+import { visibleWidth } from "./width.js";
2+
3+const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
4+
5+export interface VisualLine {
6+ text: string;
7+ startOffset: number;
8+ endOffset: number;
9+ width: number;
10+}
11+
12+export interface VisualPosition {
13+ line: number;
14+ col: number;
15+}
16+
17+export interface TextLayoutResult {
18+ lines: VisualLine[];
19+ lineCount: number;
20+ offsetToPosition(offset: number): VisualPosition;
21+}
22+
23+interface GraphemeInfo {
24+ text: string;
25+ startOffset: number;
26+ endOffset: number;
27+ width: number;
28+ isWhitespace: boolean;
29+}
30+
31+interface VisualLineData {
32+ line: VisualLine;
33+ graphemes: GraphemeInfo[];
34+}
35+
36+interface Range {
37+ start: number;
38+ end: number;
39+}
40+
41+export function layoutText(
42+ value: string,
43+ width: number,
44+ wrap: "none" | "word",
45+): TextLayoutResult {
46+ const hardLines = splitHardLines(value);
47+ const lines: VisualLineData[] = [];
48+
49+ for (const hardLine of hardLines) {
50+ const graphemes = segmentLine(value, hardLine.start, hardLine.end);
51+ if (wrap === "word") {
52+ lines.push(
53+ ...wrapGraphemes(value, graphemes, Math.max(1, width), hardLine),
54+ );
55+ } else {
56+ lines.push(
57+ ...buildVisualLines(
58+ value,
59+ graphemes,
60+ [[0, graphemes.length]],
61+ hardLine,
62+ ),
63+ );
64+ }
65+ }
66+
67+ if (lines.length === 0) {
68+ const empty: VisualLineData = {
69+ line: { text: "", startOffset: 0, endOffset: 0, width: 0 },
70+ graphemes: [],
71+ };
72+ lines.push(empty);
73+ }
74+
75+ return {
76+ lines: lines.map((entry) => entry.line),
77+ lineCount: lines.length,
78+ offsetToPosition(offset: number): VisualPosition {
79+ return offsetToPosition(lines, clamp(offset, 0, value.length));
80+ },
81+ };
82+}
83+
84+function splitHardLines(value: string): Range[] {
85+ const lines: Range[] = [];
86+ let start = 0;
87+ for (let i = 0; i < value.length; i++) {
88+ if (value[i] === "\n") {
89+ lines.push({ start, end: i });
90+ start = i + 1;
91+ }
92+ }
93+ lines.push({ start, end: value.length });
94+ return lines;
95+}
96+
97+function segmentLine(
98+ value: string,
99+ start: number,
100+ end: number,
101+): GraphemeInfo[] {
102+ const graphemes: GraphemeInfo[] = [];
103+ const text = value.slice(start, end);
104+ let offset = start;
105+
106+ for (const { segment } of segmenter.segment(text)) {
107+ graphemes.push({
108+ text: segment,
109+ startOffset: offset,
110+ endOffset: offset + segment.length,
111+ width: visibleWidth(segment),
112+ isWhitespace: /^\s+$/u.test(segment),
113+ });
114+ offset += segment.length;
115+ }
116+
117+ return graphemes;
118+}
119+
120+function wrapGraphemes(
121+ value: string,
122+ graphemes: GraphemeInfo[],
123+ width: number,
124+ hardLine: Range,
125+): VisualLineData[] {
126+ if (graphemes.length === 0) {
127+ return [makeVisualLine(value, graphemes, 0, 0, hardLine.start)];
128+ }
129+
130+ const prefixWidths = [0];
131+ for (const grapheme of graphemes) {
132+ prefixWidths.push(prefixWidths[prefixWidths.length - 1]! + grapheme.width);
133+ }
134+
135+ const ranges: Array<[number, number]> = [];
136+ let lineStart = 0;
137+
138+ while (lineStart < graphemes.length) {
139+ let lineEnd = lineStart;
140+ let lastBreak = -1;
141+
142+ while (lineEnd < graphemes.length) {
143+ const nextWidth = prefixWidths[lineEnd + 1]! - prefixWidths[lineStart]!;
144+ if (nextWidth > width) break;
145+ lineEnd++;
146+ if (graphemes[lineEnd - 1]!.isWhitespace) {
147+ lastBreak = lineEnd;
148+ }
149+ }
150+
151+ if (lineEnd >= graphemes.length) {
152+ ranges.push([lineStart, graphemes.length]);
153+ break;
154+ }
155+
156+ if (lineEnd === lineStart) {
157+ ranges.push([lineStart, lineStart + 1]);
158+ lineStart++;
159+ continue;
160+ }
161+
162+ if (lastBreak > lineStart) {
163+ ranges.push([lineStart, lastBreak]);
164+ lineStart = lastBreak;
165+ continue;
166+ }
167+
168+ ranges.push([lineStart, lineEnd]);
169+ lineStart = lineEnd;
170+ }
171+
172+ return buildVisualLines(value, graphemes, ranges, hardLine);
173+}
174+
175+function buildVisualLines(
176+ value: string,
177+ graphemes: GraphemeInfo[],
178+ ranges: Array<[number, number]>,
179+ hardLine: Range,
180+): VisualLineData[] {
181+ return ranges.map(([startIndex, endIndex]) =>
182+ makeVisualLine(value, graphemes, startIndex, endIndex, hardLine.start),
183+ );
184+}
185+
186+function makeVisualLine(
187+ value: string,
188+ graphemes: GraphemeInfo[],
189+ startIndex: number,
190+ endIndex: number,
191+ hardLineStart: number,
192+): VisualLineData {
193+ if (startIndex === endIndex) {
194+ return {
195+ line: {
196+ text: "",
197+ startOffset: hardLineStart,
198+ endOffset: hardLineStart,
199+ width: 0,
200+ },
201+ graphemes: [],
202+ };
203+ }
204+
205+ const lineGraphemes = graphemes.slice(startIndex, endIndex);
206+ const startOffset = lineGraphemes[0]!.startOffset;
207+ const endOffset = lineGraphemes[lineGraphemes.length - 1]!.endOffset;
208+
209+ return {
210+ line: {
211+ text: value.slice(startOffset, endOffset),
212+ startOffset,
213+ endOffset,
214+ width: lineGraphemes.reduce((sum, grapheme) => sum + grapheme.width, 0),
215+ },
216+ graphemes: lineGraphemes,
217+ };
218+}
219+
220+function offsetToPosition(
221+ lines: VisualLineData[],
222+ offset: number,
223+): VisualPosition {
224+ for (let i = 1; i < lines.length; i++) {
225+ if (offset === lines[i]!.line.startOffset) {
226+ return { line: i, col: 0 };
227+ }
228+ }
229+
230+ for (let i = 0; i < lines.length; i++) {
231+ const entry = lines[i]!;
232+ const { line, graphemes } = entry;
233+ if (offset < line.startOffset || offset > line.endOffset) continue;
234+
235+ let col = 0;
236+ for (const grapheme of graphemes) {
237+ if (offset <= grapheme.startOffset) break;
238+ if (offset < grapheme.endOffset) break;
239+ col += grapheme.width;
240+ }
241+ return { line: i, col };
242+ }
243+
244+ const last = lines[lines.length - 1]!;
245+ return { line: lines.length - 1, col: last.line.width };
246+}
247+
248+function clamp(value: number, min: number, max: number): number {
249+ return Math.max(min, Math.min(max, value));
250+}