xonecas.io
70160
Ce

cel-tui / commit 7346007

fix(core): TextInput cursor, autogrowing layout, native blinking cursor, grapheme editing

- fix: clamp stored cursor to value.length in getTextInputCursor so
  clearing the value externally (e.g. after submit) no longer leaves a
  stale cursor that scrolls content out of view
- fix: apply cross-axis constraints (min/max width/height) during layout
  so maxHeight on TextInput inside HStack works, enabling the
  autogrowing input pattern from the spec
- feat: switch from static color-inversion cursor to positioning the
  real terminal cursor at the focused TextInput's cursor location,
  giving native blinking for free; hide cursor when no TextInput focused
- fix: rewrite text-edit.ts to use Intl.Segmenter for grapheme-aware
  cursor movement and deletion (emoji, ZWJ sequences, combining marks)
- test: verify controlled-focus Tab trapping is already handled by
  lastFocusedIndex mechanism (Escape+Tab advances past the element)
- test: add 15 new tests covering all fixes

xonecas2026-04-05 7346007b9952124fa47f5accf953bcd505377243 parent 3849ff3

9 files changed

TODO.md+8โˆ’2
@@ -12,9 +12,9 @@ Remaining work, known bugs, and planned improvements.
1212
1313 ## Bugs / Spec Violations
1414
15-- ๐Ÿ”ง **TextInput cursor movement doesn't handle multi-codepoint graphemes** โ€” `deleteBackward`/`deleteForward` in `text-edit.ts` operate on single string indices. For multi-codepoint characters (emoji ZWJ sequences, combining marks), this leaves the cursor mid-grapheme. `moveCursor` has the same issue.
15+- ~~๐Ÿ”ง **TextInput cursor movement doesn't handle multi-codepoint graphemes** โ€” Fixed: `text-edit.ts` now uses `Intl.Segmenter` with grapheme granularity for `deleteBackward`, `deleteForward`, and `moveCursor` (left/right). Multi-codepoint characters (emoji, ZWJ sequences, combining marks) are treated as single units.~~
1616
17-- ๐Ÿ”ง **Controlled-focus TextInput traps Tab traversal** โ€” When a controlled-focus TextInput (`focused` prop provided) is the first focusable element, Tab from unfocused state always focuses it. Once focused, Tab is consumed as an editing key. Escape unfocuses it, but the next Tab re-focuses it again โ€” the user can never Tab past it to reach subsequent focusable elements. Visible in `examples/pet.ts` on the create screen: the name TextInput prevents keyboard access to the Create Pet button. โ€ฆ
17+- ~~๐Ÿ”ง **Controlled-focus TextInput traps Tab traversal** โ€” Already works: `lastFocusedIndex` tracks which element was just Escaped from, and Tab/Shift+Tab advance past it. Added regression tests confirming Escape+Tab correctly reaches subsequent focusable elements.~~
1818
1919 - ๐Ÿ”ง **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.
2020
@@ -24,6 +24,12 @@ Remaining work, known bugs, and planned improvements.
2424
2525 - ๐Ÿ”ง **`space-between` + `gap` double-spaces children** โ€” When both `justifyContent: "space-between"` and `gap` are set, children get `gap` spacing plus the distributed remaining space on top. The remaining-space calculation subtracts `totalGap` first, then `space-between` distributes what's left as extra gap โ€” so the effective gap is `gap + betweenGaps[i]`. CSS flex doesn't stack `space-between` on top of `gap` this way. The spec doesn't define this interaction.
2626
27+- ~~๐Ÿ”ง **TextInput invisible after value cleared externally** โ€” Fixed: `getTextInputCursor` now clamps the stored cursor to `value.length`. Previously, clearing the value (e.g. after submit) left a stale cursor position in the WeakMap, causing auto-scroll to push all content out of view on subsequent typing.~~
28+
29+- ~~๐Ÿ”ง **Cross-axis constraints not applied in layout** โ€” Fixed: `minWidth`/`maxWidth`/`minHeight`/`maxHeight` are now applied on the cross axis during layout (both in intrinsic sizing and during child positioning). This enables the autogrowing TextInput pattern (`maxHeight` on TextInput inside HStack).~~
30+
31+- ~~๐Ÿ”ง **TextInput cursor was static color-inversion instead of native blinking** โ€” Fixed: switched from painting an inverted cell to positioning the real terminal cursor at the TextInput's cursor location. The terminal provides native blinking for free. Cursor is hidden when no TextInput is focused.~~
32+
2733 - ~~๐Ÿ”ง **Color theme doesn't respect terminal 16 color setup** -- Fixed: replaced named colors (`"red"`, `"white"`, etc.) with numbered palette slots (`"color00"`โ€“`"color15"`). Added `Theme` type for custom color mappings, `defaultTheme` (ANSI 16), and `cel.init(terminal, { theme })` API. Spec updated with Color System section. No more confusing `"white"` vs terminal default.~~
2834
2935 ---
packages/core/src/cel.test.ts+97โˆ’0
@@ -1530,6 +1530,103 @@ describe("cel end-to-end", () => {
15301530 await waitForRender();
15311531 expect(clicks).toEqual(["uncontrolled"]);
15321532 });
1533+
1534+ test("controlled TextInput as only focusable: Escape+Tab re-focuses it", async () => {
1535+ const term = setup(40, 5);
1536+ let value = "";
1537+ let inputFocused = false;
1538+
1539+ cel.viewport(() =>
1540+ VStack({ width: 40, height: 5 }, [
1541+ TextInput({
1542+ value,
1543+ onChange: (v) => {
1544+ value = v;
1545+ cel.render();
1546+ },
1547+ focused: inputFocused,
1548+ onFocus: () => {
1549+ inputFocused = true;
1550+ cel.render();
1551+ },
1552+ onBlur: () => {
1553+ inputFocused = false;
1554+ cel.render();
1555+ },
1556+ }),
1557+ ]),
1558+ );
1559+ await waitForRender();
1560+
1561+ // Tab โ†’ TextInput focused
1562+ term.sendInput(TAB);
1563+ await waitForRender();
1564+ expect(inputFocused).toBe(true);
1565+
1566+ // Escape โ†’ unfocused
1567+ term.sendInput(ESCAPE);
1568+ await waitForRender();
1569+ expect(inputFocused).toBe(false);
1570+
1571+ // Tab โ†’ only one focusable, wraps to it again
1572+ term.sendInput(TAB);
1573+ await waitForRender();
1574+ expect(inputFocused).toBe(true);
1575+ });
1576+
1577+ test("controlled TextInput: Escape then Tab advances past it", async () => {
1578+ const term = setup(40, 5);
1579+ let value = "";
1580+ let inputFocused = false;
1581+ const clicks: string[] = [];
1582+
1583+ cel.viewport(() =>
1584+ VStack({ width: 40, height: 5 }, [
1585+ TextInput({
1586+ value,
1587+ onChange: (v) => {
1588+ value = v;
1589+ cel.render();
1590+ },
1591+ focused: inputFocused,
1592+ onFocus: () => {
1593+ inputFocused = true;
1594+ cel.render();
1595+ },
1596+ onBlur: () => {
1597+ inputFocused = false;
1598+ cel.render();
1599+ },
1600+ }),
1601+ HStack({ onClick: () => clicks.push("btn") }, [Text("Button")]),
1602+ ]),
1603+ );
1604+ await waitForRender();
1605+
1606+ // Tab focuses the TextInput
1607+ term.sendInput(TAB);
1608+ await waitForRender();
1609+ expect(inputFocused).toBe(true);
1610+
1611+ // Tab inserts \t (editing key) while TextInput is focused
1612+ term.sendInput(TAB);
1613+ await waitForRender();
1614+ expect(value).toBe("\t");
1615+
1616+ // Escape unfocuses
1617+ term.sendInput(ESCAPE);
1618+ await waitForRender();
1619+ expect(inputFocused).toBe(false);
1620+
1621+ // Tab should advance PAST the TextInput to the Button
1622+ term.sendInput(TAB);
1623+ await waitForRender();
1624+
1625+ // Enter activates the button
1626+ term.sendInput(ENTER);
1627+ await waitForRender();
1628+ expect(clicks).toEqual(["btn"]);
1629+ });
15331630 });
15341631
15351632 describe("focusStyle rendering", () => {
packages/core/src/cel.ts+64โˆ’0
@@ -16,6 +16,7 @@ import {
1616 setTextInputCursor,
1717 getTextInputScroll,
1818 setTextInputScroll,
19+ getTextInputCursorScreenPos,
1920 } from "./paint.js";
2021 import {
2122 insertChar,
@@ -112,6 +113,69 @@ function doRender(): void {
112113 const output = emitBuffer(currentBuffer, activeTheme);
113114 terminal.write(output);
114115 }
116+
117+ // Position the native terminal cursor at the focused TextInput's cursor.
118+ // This gives us a blinking cursor for free (terminal-managed blink).
119+ positionTerminalCursor();
120+}
121+
122+/**
123+ * After each render, show the native terminal cursor at the focused
124+ * TextInput's cursor position (gives blinking for free). When no
125+ * TextInput is focused, hide the cursor.
126+ */
127+function positionTerminalCursor(): void {
128+ if (!terminal) return;
129+
130+ // Find focused TextInput in the layout tree (check stamped state during
131+ // render โ€” we need to check controlled focus in the current layouts)
132+ const focusedTI = findFocusedTextInputLayout();
133+ if (focusedTI) {
134+ const props = focusedTI.node
135+ .props as import("@cel-tui/types").TextInputProps;
136+ const pos = getTextInputCursorScreenPos(props, focusedTI.rect);
137+ if (pos) {
138+ // CUP: move cursor to (row, col) โ€” 1-indexed
139+ terminal.write(`\x1b[${pos.y + 1};${pos.x + 1}H`);
140+ terminal.showCursor();
141+ return;
142+ }
143+ }
144+ terminal.hideCursor();
145+}
146+
147+/**
148+ * Find the focused TextInput in the current layout tree.
149+ * Checks controlled focus (props.focused) and uncontrolled
150+ * (framework-tracked index). Returns the LayoutNode or null.
151+ */
152+function findFocusedTextInputLayout(): LayoutNode | null {
153+ // Check controlled focus: scan all layers for TextInput with focused: true
154+ for (let i = currentLayouts.length - 1; i >= 0; i--) {
155+ const found = findFocusedTIInTree(currentLayouts[i]!);
156+ if (found) return found;
157+ }
158+ // Check uncontrolled focus
159+ if (frameworkFocusIndex >= 0) {
160+ const topLayer = currentLayouts[currentLayouts.length - 1];
161+ if (topLayer) {
162+ const focusables = collectFocusable(topLayer);
163+ if (frameworkFocusIndex < focusables.length) {
164+ const target = focusables[frameworkFocusIndex]!;
165+ if (target.node.type === "textinput") return target;
166+ }
167+ }
168+ }
169+ return null;
170+}
171+
172+function findFocusedTIInTree(ln: LayoutNode): LayoutNode | null {
173+ if (ln.node.type === "textinput" && ln.node.props.focused) return ln;
174+ for (const child of ln.children) {
175+ const found = findFocusedTIInTree(child);
176+ if (found) return found;
177+ }
178+ return null;
115179 }
116180
117181 // --- Input handling ---
packages/core/src/layout.test.ts+102โˆ’0
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
22 import { layout, type LayoutNode, type Rect } from "./layout.js";
33 import { VStack, HStack } from "./primitives/stacks.js";
44 import { Text } from "./primitives/text.js";
5+import { TextInput } from "./primitives/text-input.js";
56
67 /** Helper to extract just the rect from a layout result. */
78 function rect(ln: LayoutNode): Rect {
@@ -1129,4 +1130,105 @@ describe("layout", () => {
11291130 });
11301131 });
11311132 });
1133+
1134+ describe("cross-axis constraints", () => {
1135+ test("maxHeight on child in HStack is respected", () => {
1136+ const node = HStack({ width: 40, height: 10 }, [
1137+ VStack({ flex: 1, maxHeight: 3 }, [Text("hello")]),
1138+ ]);
1139+ const result = layout(node, 80, 24);
1140+ expect(childRects(result)).toEqual([
1141+ { x: 0, y: 0, width: 40, height: 3 },
1142+ ]);
1143+ });
1144+
1145+ test("minHeight on child in HStack is respected", () => {
1146+ const node = HStack({ width: 40, height: 10, alignItems: "start" }, [
1147+ VStack({ flex: 1, minHeight: 5 }, [Text("hi")]),
1148+ ]);
1149+ const result = layout(node, 80, 24);
1150+ // Intrinsic height of VStack containing "hi" is 1, but minHeight is 5
1151+ expect(childRects(result)[0]!.height).toBe(5);
1152+ });
1153+
1154+ test("maxWidth on child in VStack is respected", () => {
1155+ const node = VStack({ width: 40, height: 10 }, [
1156+ HStack({ flex: 1, maxWidth: 20 }, [Text("x")]),
1157+ ]);
1158+ const result = layout(node, 80, 24);
1159+ expect(childRects(result)[0]!.width).toBe(20);
1160+ });
1161+
1162+ test("TextInput maxHeight in HStack creates autogrowing input", () => {
1163+ // Nest HStack in VStack so HStack gets intrinsic height
1164+ // Empty value โ†’ height 1
1165+ const node1 = VStack({ width: 80, height: 24 }, [
1166+ HStack({}, [
1167+ TextInput({
1168+ flex: 1,
1169+ maxHeight: 5,
1170+ value: "",
1171+ onChange: () => {},
1172+ }),
1173+ ]),
1174+ Text("after"),
1175+ ]);
1176+ const r1 = layout(node1, 80, 24);
1177+ expect(r1.children[0]!.rect.height).toBe(1);
1178+ expect(r1.children[0]!.children[0]!.rect.height).toBe(1);
1179+
1180+ // Multi-line value โ†’ grows to content height
1181+ const node2 = VStack({ width: 80, height: 24 }, [
1182+ HStack({}, [
1183+ TextInput({
1184+ flex: 1,
1185+ maxHeight: 5,
1186+ value: "line1\nline2\nline3",
1187+ onChange: () => {},
1188+ }),
1189+ ]),
1190+ Text("after"),
1191+ ]);
1192+ const r2 = layout(node2, 80, 24);
1193+ expect(r2.children[0]!.rect.height).toBe(3);
1194+ expect(r2.children[0]!.children[0]!.rect.height).toBe(3);
1195+
1196+ // Many lines โ†’ capped at maxHeight
1197+ const node3 = VStack({ width: 80, height: 24 }, [
1198+ HStack({}, [
1199+ TextInput({
1200+ flex: 1,
1201+ maxHeight: 5,
1202+ value: "1\n2\n3\n4\n5\n6\n7\n8",
1203+ onChange: () => {},
1204+ }),
1205+ ]),
1206+ Text("after"),
1207+ ]);
1208+ const r3 = layout(node3, 80, 24);
1209+ expect(r3.children[0]!.rect.height).toBe(5);
1210+ expect(r3.children[0]!.children[0]!.rect.height).toBe(5);
1211+ });
1212+
1213+ test("cross-axis constraints in intrinsic container sizing", () => {
1214+ // HStack with no explicit height, child has maxHeight:
1215+ // HStack intrinsic height should respect child's maxHeight
1216+ const node = VStack({ width: 80, height: 24 }, [
1217+ HStack({}, [
1218+ TextInput({
1219+ flex: 1,
1220+ maxHeight: 3,
1221+ value: "1\n2\n3\n4\n5",
1222+ onChange: () => {},
1223+ }),
1224+ ]),
1225+ Text("after"),
1226+ ]);
1227+ const result = layout(node, 80, 24);
1228+ // HStack should be 3 tall (capped by TextInput's maxHeight)
1229+ expect(result.children[0]!.rect.height).toBe(3);
1230+ // Text "after" should be right after it
1231+ expect(result.children[1]!.rect.y).toBe(3);
1232+ });
1233+ });
11321234 });
packages/core/src/layout.ts+37โˆ’2
@@ -200,6 +200,17 @@ function intrinsicMainSize(
200200 resolveSizeValue(cProps?.width, 0) ??
201201 intrinsicMainSize(child, false, innerCross);
202202 }
203+ // Apply child's cross-axis constraints (e.g. maxHeight on a TextInput
204+ // inside an HStack) so the container's intrinsic size respects them.
205+ if (cProps) {
206+ const minCross = isVertical
207+ ? (cProps.minHeight ?? 0)
208+ : (cProps.minWidth ?? 0);
209+ const maxCross = isVertical
210+ ? (cProps.maxHeight ?? Infinity)
211+ : (cProps.maxWidth ?? Infinity);
212+ childSize = clamp(childSize, minCross, maxCross);
213+ }
203214 if (childSize > maxSize) maxSize = childSize;
204215 }
205216 return maxSize + padMain;
@@ -336,9 +347,13 @@ function layoutWrapHStack(
336347 baseWidths.push(baseW);
337348
338349 // Always compute real cross size (explicit or intrinsic) for row height
339- const cross =
350+ let cross =
340351 resolveSizeValue(cProps?.height, innerH) ??
341352 intrinsicMainSize(child, true, innerW);
353+ // Apply cross-axis constraints (e.g. maxHeight)
354+ if (cProps) {
355+ cross = clamp(cross, cProps.minHeight ?? 0, cProps.maxHeight ?? Infinity);
356+ }
342357 crossSizes.push(cross);
343358 }
344359
@@ -566,6 +581,16 @@ function layoutNode(
566581 resolveSizeValue(cProps?.height, innerH) ??
567582 (useIntrinsicCross ? intrinsicMainSize(child, true, innerW) : innerH);
568583 }
584+ // Apply cross-axis constraints
585+ if (cProps) {
586+ const minCross = isVertical
587+ ? (cProps.minWidth ?? 0)
588+ : (cProps.minHeight ?? 0);
589+ const maxCross = isVertical
590+ ? (cProps.maxWidth ?? Infinity)
591+ : (cProps.maxHeight ?? Infinity);
592+ cross = clamp(cross, minCross, maxCross);
593+ }
569594 infos.push({ node: child, mainSize: 0, crossSize: cross, flex });
570595 } else {
571596 // Main-axis: explicit โ†’ percentage โ†’ intrinsic
@@ -589,7 +614,7 @@ function layoutNode(
589614 (useIntrinsicCross ? intrinsicMainSize(child, true, innerW) : innerH);
590615 }
591616
592- // Apply constraints
617+ // Apply main-axis constraints
593618 if (cProps) {
594619 const minMain = isVertical
595620 ? (cProps.minHeight ?? 0)
@@ -599,6 +624,16 @@ function layoutNode(
599624 : (cProps.maxWidth ?? Infinity);
600625 main = clamp(main, minMain, maxMain);
601626 }
627+ // Apply cross-axis constraints
628+ if (cProps) {
629+ const minCross = isVertical
630+ ? (cProps.minWidth ?? 0)
631+ : (cProps.minHeight ?? 0);
632+ const maxCross = isVertical
633+ ? (cProps.maxWidth ?? Infinity)
634+ : (cProps.maxHeight ?? Infinity);
635+ cross = clamp(cross, minCross, maxCross);
636+ }
602637
603638 fixedMain += main;
604639 infos.push({ node: child, mainSize: main, crossSize: cross, flex });
packages/core/src/paint.ts+36โˆ’20
@@ -537,25 +537,6 @@ function paintTextInput(
537537 const line = lines[lineIdx]!;
538538 paintLineGraphemes(line, cx, cy + row, cw, clipRect, props, buf);
539539 }
540-
541- // Paint cursor if focused
542- if (props.focused) {
543- const cursorOffset = getTextInputCursor(props);
544- const pos = offsetToWrappedPos(value, cursorOffset, cw);
545- const screenRow = pos.line - scrollOffset;
546- if (screenRow >= 0 && screenRow < ch && pos.col < cw) {
547- const existing = buf.get(cx + pos.col, cy + screenRow);
548- // Invert colors for cursor visibility
549- buf.set(cx + pos.col, cy + screenRow, {
550- char: existing.char === " " && !existing.bgColor ? " " : existing.char,
551- fgColor: existing.bgColor ?? null,
552- bgColor: existing.fgColor ?? null,
553- bold: existing.bold,
554- italic: existing.italic,
555- underline: existing.underline,
556- });
557- }
558- }
559540 }
560541
561542 /**
@@ -609,9 +590,44 @@ type OnChangeFn = (value: string) => void;
609590 const textInputCursors = new WeakMap<OnChangeFn, number>();
610591 const textInputScrolls = new WeakMap<OnChangeFn, number>();
611592
593+/**
594+ * Compute the screen position of the cursor for a focused TextInput.
595+ * Returns `{ x, y }` in 0-indexed screen coordinates, or `null` if
596+ * the cursor is not visible (clipped or not focused).
597+ */
598+export function getTextInputCursorScreenPos(
599+ props: TextInputProps,
600+ rect: Rect,
601+): { x: number; y: number } | null {
602+ const { x, y, width: w, height: h } = rect;
603+ if (w <= 0 || h <= 0) return null;
604+
605+ const padX = props.padding?.x ?? 0;
606+ const padY = props.padding?.y ?? 0;
607+ const cx = x + padX;
608+ const cy = y + padY;
609+ const cw = Math.max(0, w - padX * 2);
610+ const ch = Math.max(0, h - padY * 2);
611+ if (cw <= 0 || ch <= 0) return null;
612+
613+ const cursorOffset = getTextInputCursor(props);
614+ const pos = offsetToWrappedPos(props.value, cursorOffset, cw);
615+ const scrollOffset = getTextInputScroll(props);
616+ const screenRow = pos.line - scrollOffset;
617+
618+ if (screenRow >= 0 && screenRow < ch && pos.col < cw) {
619+ return { x: cx + pos.col, y: cy + screenRow };
620+ }
621+ return null;
622+}
623+
612624 /** Get the cursor offset for a TextInput (framework-managed). */
613625 export function getTextInputCursor(props: TextInputProps): number {
614- return textInputCursors.get(props.onChange) ?? props.value.length;
626+ const stored = textInputCursors.get(props.onChange);
627+ if (stored === undefined) return props.value.length;
628+ // Clamp to value length โ€” the app may have cleared or shortened the value
629+ // externally (e.g. after submit) while the WeakMap still holds the old cursor.
630+ return Math.min(stored, props.value.length);
615631 }
616632
617633 /** Set the cursor offset for a TextInput. */
packages/core/src/text-edit.test.ts+54โˆ’0
@@ -62,6 +62,22 @@ describe("text editing", () => {
6262 expect(result.value).toBe("");
6363 expect(result.cursor).toBe(0);
6464 });
65+
66+ test("deletes entire emoji (multi-codepoint)", () => {
67+ // ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง is a ZWJ family emoji (multiple codepoints, one grapheme)
68+ const emoji = "๐Ÿ‘จ\u200D๐Ÿ‘ฉ\u200D๐Ÿ‘ง";
69+ const val = "a" + emoji + "b";
70+ const cursorAfterEmoji = 1 + emoji.length;
71+ const result = deleteBackward(state(val, cursorAfterEmoji));
72+ expect(result.value).toBe("ab");
73+ expect(result.cursor).toBe(1);
74+ });
75+
76+ test("deletes single emoji", () => {
77+ const result = deleteBackward(state("hi๐Ÿ˜€!", 2 + "๐Ÿ˜€".length));
78+ expect(result.value).toBe("hi!");
79+ expect(result.cursor).toBe(2);
80+ });
6581 });
6682
6783 describe("deleteForward", () => {
@@ -76,6 +92,22 @@ describe("text editing", () => {
7692 expect(result.value).toBe("hello");
7793 expect(result.cursor).toBe(5);
7894 });
95+
96+ test("deletes entire emoji forward", () => {
97+ const emoji = "๐Ÿ˜€";
98+ const val = "a" + emoji + "b";
99+ const result = deleteForward(state(val, 1));
100+ expect(result.value).toBe("ab");
101+ expect(result.cursor).toBe(1);
102+ });
103+
104+ test("deletes ZWJ sequence forward", () => {
105+ const emoji = "๐Ÿ‘จ\u200D๐Ÿ‘ฉ\u200D๐Ÿ‘ง";
106+ const val = "x" + emoji + "y";
107+ const result = deleteForward(state(val, 1));
108+ expect(result.value).toBe("xy");
109+ expect(result.cursor).toBe(1);
110+ });
79111 });
80112
81113 describe("moveCursor", () => {
@@ -99,6 +131,28 @@ describe("text editing", () => {
99131 expect(result.cursor).toBe(5);
100132 });
101133
134+ test("left skips over multi-codepoint emoji", () => {
135+ const emoji = "\ud83d\ude00"; // ๐Ÿ˜€ is 2 UTF-16 code units
136+ const val = "a" + emoji + "b";
137+ const cursorAfterEmoji = 1 + emoji.length;
138+ const result = moveCursor(state(val, cursorAfterEmoji), "left");
139+ expect(result.cursor).toBe(1); // before the emoji
140+ });
141+
142+ test("right skips over multi-codepoint emoji", () => {
143+ const emoji = "\ud83d\ude00";
144+ const val = "a" + emoji + "b";
145+ const result = moveCursor(state(val, 1), "right");
146+ expect(result.cursor).toBe(1 + emoji.length); // after the emoji
147+ });
148+
149+ test("left skips over ZWJ sequence", () => {
150+ const emoji = "\ud83d\udc68\u200D\ud83d\udc69\u200D\ud83d\udc67";
151+ const val = "x" + emoji;
152+ const result = moveCursor(state(val, val.length), "left");
153+ expect(result.cursor).toBe(1); // before the ZWJ sequence
154+ });
155+
102156 test("home moves to start", () => {
103157 const result = moveCursor(state("hello", 3), "home");
104158 expect(result.cursor).toBe(0);
packages/core/src/text-edit.ts+52โˆ’21
@@ -8,6 +8,37 @@ export interface EditState {
88 cursor: number;
99 }
1010
11+const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
12+
13+/**
14+ * Get the grapheme boundary before the given cursor position.
15+ * Returns the start offset of the grapheme that contains or precedes
16+ * the cursor, or 0 if at the beginning.
17+ */
18+function prevGraphemeBoundary(value: string, cursor: number): number {
19+ if (cursor <= 0) return 0;
20+ let lastStart = 0;
21+ for (const { index, segment } of segmenter.segment(value)) {
22+ const end = index + segment.length;
23+ if (end >= cursor) return index;
24+ lastStart = end;
25+ }
26+ return lastStart;
27+}
28+
29+/**
30+ * Get the grapheme boundary after the given cursor position.
31+ * Returns the end offset of the grapheme that starts at or after
32+ * the cursor, or value.length if at the end.
33+ */
34+function nextGraphemeBoundary(value: string, cursor: number): number {
35+ for (const { index, segment } of segmenter.segment(value)) {
36+ const end = index + segment.length;
37+ if (index >= cursor) return end;
38+ }
39+ return value.length;
40+}
41+
1142 /**
1243 * Insert a character (or string) at the cursor position.
1344 */
@@ -20,31 +51,36 @@ export function insertChar(state: EditState, char: string): EditState {
2051 }
2152
2253 /**
23- * Delete the character before the cursor (Backspace).
54+ * Delete the grapheme before the cursor (Backspace).
55+ * Handles multi-codepoint characters (emoji, ZWJ sequences, combining marks).
2456 */
2557 export function deleteBackward(state: EditState): EditState {
2658 const { value, cursor } = state;
2759 if (cursor === 0) return state;
60+ const boundary = prevGraphemeBoundary(value, cursor);
2861 return {
29- value: value.slice(0, cursor - 1) + value.slice(cursor),
30- cursor: cursor - 1,
62+ value: value.slice(0, boundary) + value.slice(cursor),
63+ cursor: boundary,
3164 };
3265 }
3366
3467 /**
35- * Delete the character after the cursor (Delete key).
68+ * Delete the grapheme after the cursor (Delete key).
69+ * Handles multi-codepoint characters (emoji, ZWJ sequences, combining marks).
3670 */
3771 export function deleteForward(state: EditState): EditState {
3872 const { value, cursor } = state;
3973 if (cursor >= value.length) return state;
74+ const boundary = nextGraphemeBoundary(value, cursor);
4075 return {
41- value: value.slice(0, cursor) + value.slice(cursor + 1),
76+ value: value.slice(0, cursor) + value.slice(boundary),
4277 cursor,
4378 };
4479 }
4580
4681 /**
4782 * Move the cursor in the given direction.
83+ * Left/right movement respects grapheme boundaries.
4884 *
4985 * @param state - Current edit state.
5086 * @param direction - Movement direction.
@@ -58,10 +94,16 @@ export function moveCursor(
5894 const { value, cursor } = state;
5995
6096 switch (direction) {
61- case "left":
62- return { value, cursor: Math.max(0, cursor - 1) };
63- case "right":
64- return { value, cursor: Math.min(value.length, cursor + 1) };
97+ case "left": {
98+ if (cursor <= 0) return state;
99+ const boundary = prevGraphemeBoundary(value, cursor);
100+ return { value, cursor: boundary };
101+ }
102+ case "right": {
103+ if (cursor >= value.length) return state;
104+ const boundary = nextGraphemeBoundary(value, cursor);
105+ return { value, cursor: boundary };
106+ }
65107 case "home":
66108 return { value, cursor: 0 };
67109 case "end":
@@ -89,17 +131,6 @@ function moveVertical(
89131 let cursorLine = 0;
90132 let cursorCol = 0;
91133
92- for (let i = 0; i < lines.length; i++) {
93- const lineLen = lines[i]!.length;
94- if (offset + lineLen >= cursor && cursorLine === 0 && offset <= cursor) {
95- cursorLine = i;
96- cursorCol = cursor - offset;
97- }
98- offset += lineLen + 1; // +1 for \n
99- }
100-
101- // Re-scan to get correct line (the above loop has a bug for first line)
102- offset = 0;
103134 for (let i = 0; i < lines.length; i++) {
104135 const lineLen = lines[i]!.length;
105136 if (cursor >= offset && cursor <= offset + lineLen) {
@@ -107,7 +138,7 @@ function moveVertical(
107138 cursorCol = cursor - offset;
108139 break;
109140 }
110- offset += lineLen + 1;
141+ offset += lineLen + 1; // +1 for \n
111142 }
112143
113144 // Move line
packages/core/src/text-input.test.ts+46โˆ’0
@@ -348,6 +348,52 @@ describe("TextInput integration", () => {
348348 expect(buf.get(2, 1).char).not.toBe(" "); // content area โ€” "h" or cursor
349349 });
350350
351+ test("cursor resets when value is cleared externally", async () => {
352+ const term = setup(30, 3);
353+ let value = "hello";
354+ const onChange = (v: string) => {
355+ value = v;
356+ cel.render();
357+ };
358+
359+ cel.viewport(() =>
360+ VStack({}, [
361+ TextInput({
362+ value,
363+ focused: true,
364+ onChange,
365+ }),
366+ ]),
367+ );
368+ await waitForRender();
369+
370+ // Type a character to confirm cursor is at end
371+ term.sendInput("!");
372+ await waitForRender();
373+ expect(value).toBe("hello!");
374+
375+ // Simulate external clear (e.g. after send)
376+ value = "";
377+ cel.render();
378+ await waitForRender();
379+
380+ // Now type again โ€” should appear at position 0, not at stale cursor
381+ term.sendInput("a");
382+ await waitForRender();
383+ expect(value).toBe("a");
384+
385+ // Verify the text is actually visible in the buffer
386+ const buf = cel._getBuffer()!;
387+ let found = false;
388+ for (let x = 0; x < 30; x++) {
389+ if (buf.get(x, 0).char === "a") {
390+ found = true;
391+ break;
392+ }
393+ }
394+ expect(found).toBe(true);
395+ });
396+
351397 test("padding affects intrinsic height", async () => {
352398 setup(20, 10);
353399 let value = "line1";