xonecas.io
70160
Ce

cel-tui / commit d7fde7d

fix(core): prevent native cursor flicker during rerenders

xonecas2026-04-07 d7fde7d282d83747cc668859887bcfab726b6299 parent ede7e68

5 files changed

TODO.md+0โˆ’4
@@ -12,12 +12,8 @@ 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-
1715 - ๐Ÿ”ง **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 โ€ฆ
1816
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-
2117 - ๐Ÿ”ง **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 โ€ฆ
2218
2319 - ๐Ÿ”ง **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.
packages/core/src/cel.ts+33โˆ’25
@@ -30,6 +30,14 @@ import { getMaxScrollOffset } from "./scroll.js";
3030
3131 type RenderFn = () => Node | Node[];
3232
33+type TerminalCursorState =
34+ | { visible: false }
35+ | {
36+ visible: true;
37+ x: number;
38+ y: number;
39+ };
40+
3341 let terminal: Terminal | null = null;
3442 let activeTheme: Theme = defaultTheme;
3543 let renderFn: RenderFn | null = null;
@@ -60,6 +68,9 @@ const uncontrolledScrollOffsets = new Map<string, number>();
6068 /** Nodes whose props were stamped with scrollOffset during the last paint. */
6169 let stampedScrollNodes: { node: Node; key: string }[] = [];
6270
71+/** The cursor state currently expected on the terminal. */
72+let lastTerminalCursor: TerminalCursorState | null = { visible: false };
73+
6374 function doRender(): void {
6475 renderScheduled = false;
6576 if (!renderFn || !terminal) return;
@@ -105,43 +116,38 @@ function doRender(): void {
105116 unstampUncontrolledFocus();
106117 unstampUncontrolledScroll();
107118
119+ const nextCursor = getDesiredTerminalCursor();
120+
108121 // Emit to terminal โ€” differential when possible
109122 if (prevBuffer) {
110- const output = emitDiff(prevBuffer, currentBuffer, activeTheme);
123+ const output = emitDiff(prevBuffer, currentBuffer, activeTheme, {
124+ cursor: nextCursor,
125+ previousCursor: lastTerminalCursor,
126+ });
111127 if (output.length > 0) terminal.write(output);
112128 } else {
113- const output = emitBuffer(currentBuffer, activeTheme);
129+ const output = emitBuffer(currentBuffer, activeTheme, {
130+ cursor: nextCursor,
131+ previousCursor: lastTerminalCursor,
132+ });
114133 terminal.write(output);
115134 }
116135
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();
136+ lastTerminalCursor = nextCursor;
120137 }
121138
122139 /**
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.
140+ * Resolve the final terminal cursor state for the current frame.
141+ * The cursor is shown only for a focused TextInput whose cursor is visible
142+ * within the clipped viewport.
126143 */
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)
144+function getDesiredTerminalCursor(): TerminalCursorState {
132145 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();
146+ if (!focusedTI) return { visible: false };
147+
148+ const props = focusedTI.node.props as import("@cel-tui/types").TextInputProps;
149+ const pos = getTextInputCursorScreenPos(props, focusedTI.rect);
150+ return pos ? { visible: true, x: pos.x, y: pos.y } : { visible: false };
145151 }
146152
147153 /**
@@ -847,6 +853,7 @@ export const cel = {
847853 init(term: Terminal, options?: { theme?: Theme }): void {
848854 terminal = term;
849855 activeTheme = options?.theme ?? defaultTheme;
856+ lastTerminalCursor = { visible: false };
850857 terminal.start(handleInput, () => cel.render());
851858 },
852859
@@ -892,6 +899,7 @@ export const cel = {
892899 stampedNode = null;
893900 uncontrolledScrollOffsets.clear();
894901 stampedScrollNodes = [];
902+ lastTerminalCursor = { visible: false };
895903 activeTheme = defaultTheme;
896904 },
897905
packages/core/src/emitter.test.ts+38โˆ’1
@@ -1,7 +1,7 @@
11 import { describe, expect, test } from "bun:test";
22 import type { Theme } from "@cel-tui/types";
33 import { CellBuffer, type Cell } from "./cell-buffer.js";
4-import { emitBuffer, emitDiff } from "./emitter.js";
4+import { defaultTheme, emitBuffer, emitDiff } from "./emitter.js";
55
66 function cell(char: string, overrides: Partial<Cell> = {}): Cell {
77 return {
@@ -278,6 +278,43 @@ describe("emitDiff", () => {
278278 expect(output).not.toContain("\u4e16 ");
279279 });
280280
281+ test("restores an unchanged visible cursor inside synchronized diff output", () => {
282+ const prev = new CellBuffer(5, 1);
283+ const next = new CellBuffer(5, 1);
284+ next.set(2, 0, cell("X"));
285+
286+ const output = emitDiff(prev, next, defaultTheme, {
287+ cursor: { visible: true, x: 4, y: 2 },
288+ previousCursor: { visible: true, x: 4, y: 2 },
289+ });
290+
291+ expect(output.startsWith("\x1b[?2026h\x1b7")).toBe(true);
292+ expect(output.endsWith("\x1b8\x1b[?2026l")).toBe(true);
293+ expect(output).not.toContain("\x1b[?25h");
294+ });
295+
296+ test("moves and shows the cursor before ending synchronized full output", () => {
297+ const buf = new CellBuffer(2, 1);
298+ const output = emitBuffer(buf, defaultTheme, {
299+ cursor: { visible: true, x: 1, y: 0 },
300+ previousCursor: { visible: false },
301+ });
302+
303+ expect(output.endsWith("\x1b[1;2H\x1b[?25h\x1b[?2026l")).toBe(true);
304+ });
305+
306+ test("hides a previously visible cursor inside synchronized diff output", () => {
307+ const prev = new CellBuffer(1, 1);
308+ const next = new CellBuffer(1, 1);
309+
310+ const output = emitDiff(prev, next, defaultTheme, {
311+ cursor: { visible: false },
312+ previousCursor: { visible: true, x: 0, y: 0 },
313+ });
314+
315+ expect(output).toBe("\x1b[?2026h\x1b[?25l\x1b[?2026l");
316+ });
317+
281318 test("custom theme applies to diff output", () => {
282319 const prev = new CellBuffer(3, 1);
283320 const next = new CellBuffer(3, 1);
packages/core/src/emitter.ts+65โˆ’6
@@ -100,8 +100,61 @@ function hasStyle(cell: Cell): boolean {
100100 const SYNC_START = "\x1b[?2026h";
101101 const SYNC_END = "\x1b[?2026l";
102102 const CURSOR_HOME = "\x1b[H";
103+const HIDE_CURSOR = "\x1b[?25l";
104+const SHOW_CURSOR = "\x1b[?25h";
105+const SAVE_CURSOR = "\x1b7";
106+const RESTORE_CURSOR = "\x1b8";
103107 const RESET = "\x1b[0m";
104108
109+type CursorState =
110+ | { visible: false }
111+ | {
112+ visible: true;
113+ x: number;
114+ y: number;
115+ };
116+
117+interface EmitOptions {
118+ cursor?: CursorState;
119+ previousCursor?: CursorState | null;
120+}
121+
122+function sameVisibleCursor(
123+ a: CursorState | null | undefined,
124+ b: CursorState | null | undefined,
125+): boolean {
126+ return (
127+ a?.visible === true && b?.visible === true && a.x === b.x && a.y === b.y
128+ );
129+}
130+
131+function getCursorControls(
132+ options: EmitOptions | undefined,
133+ hasPaintOutput: boolean,
134+): { prefix: string; suffix: string } {
135+ const cursor = options?.cursor ?? { visible: false };
136+ const previous = options?.previousCursor ?? null;
137+
138+ if (sameVisibleCursor(cursor, previous)) {
139+ return hasPaintOutput
140+ ? { prefix: SAVE_CURSOR, suffix: RESTORE_CURSOR }
141+ : { prefix: "", suffix: "" };
142+ }
143+
144+ if (cursor.visible) {
145+ return {
146+ prefix: "",
147+ suffix:
148+ `\x1b[${cursor.y + 1};${cursor.x + 1}H` +
149+ (previous?.visible === true ? "" : SHOW_CURSOR),
150+ };
151+ }
152+
153+ return previous?.visible === true
154+ ? { prefix: "", suffix: HIDE_CURSOR }
155+ : { prefix: "", suffix: "" };
156+}
157+
105158 /**
106159 * Emit a full cell buffer as an ANSI string for terminal output.
107160 *
@@ -114,13 +167,16 @@ const RESET = "\x1b[0m";
114167 *
115168 * @param buf - The cell buffer to render.
116169 * @param theme - Color theme mapping. Defaults to the ANSI 16 theme.
170+ * @param options - Optional terminal cursor state to apply before the synchronized output ends.
117171 * @returns A complete ANSI string ready to write to the terminal.
118172 */
119173 export function emitBuffer(
120174 buf: CellBuffer,
121175 theme: Theme = defaultTheme,
176+ options?: EmitOptions,
122177 ): string {
123- let out = SYNC_START + CURSOR_HOME;
178+ const cursorControls = getCursorControls(options, true);
179+ let out = SYNC_START + cursorControls.prefix + CURSOR_HOME;
124180
125181 let lastStyle: Cell | null = null;
126182
@@ -153,7 +209,7 @@ export function emitBuffer(
153209 out += RESET;
154210 }
155211
156- out += SYNC_END;
212+ out += cursorControls.suffix + SYNC_END;
157213 return out;
158214 }
159215
@@ -167,18 +223,21 @@ export function emitBuffer(
167223 * @param prev - The previous buffer.
168224 * @param next - The new buffer.
169225 * @param theme - Color theme mapping. Defaults to the ANSI 16 theme.
226+ * @param options - Optional terminal cursor state to apply before the synchronized output ends.
170227 * @returns An ANSI string with only the changed cells.
171228 */
172229 export function emitDiff(
173230 prev: CellBuffer,
174231 next: CellBuffer,
175232 theme: Theme = defaultTheme,
233+ options?: EmitOptions,
176234 ): string {
177- let out = SYNC_START;
178-
179235 const changes = prev.diff(next);
236+ const cursorControls = getCursorControls(options, changes.length > 0);
237+ let out = SYNC_START + cursorControls.prefix;
238+
180239 if (changes.length === 0) {
181- return out + SYNC_END;
240+ return out + cursorControls.suffix + SYNC_END;
182241 }
183242
184243 let lastStyle: Cell | null = null;
@@ -222,6 +281,6 @@ export function emitDiff(
222281 out += RESET;
223282 }
224283
225- out += SYNC_END;
284+ out += cursorControls.suffix + SYNC_END;
226285 return out;
227286 }
packages/core/src/text-input.test.ts+28โˆ’0
@@ -375,6 +375,34 @@ describe("TextInput integration", () => {
375375 expect(value).toBe("abcXdef");
376376 });
377377
378+ test("animated sibling updates do not emit cursor commands after synchronized output", async () => {
379+ const term = setup(20, 3);
380+ let tick = 0;
381+ const onChange = () => {};
382+
383+ cel.viewport(() =>
384+ VStack({ height: "100%" }, [
385+ Text(`tick:${tick}`),
386+ TextInput({
387+ value: "abc",
388+ focused: true,
389+ onChange,
390+ }),
391+ ]),
392+ );
393+ await waitForRender();
394+
395+ term.clearOutput();
396+ tick = 1;
397+ cel.render();
398+ await waitForRender();
399+
400+ expect(term.output.endsWith("\x1b[?2026l")).toBe(true);
401+ expect(term.output).not.toContain("\x1b[?25h");
402+ expect(term.output).toContain("\x1b7");
403+ expect(term.output).toContain("\x1b8");
404+ });
405+
378406 test("auto-scrolls to keep cursor visible when typing past viewport", async () => {
379407 const term = setup(20, 3); // 3 rows tall
380408 let value = "line1\nline2\nline3";