xonecas.io
70160
Ce

cel-tui / commit 092c158

feat(core): end-to-end rendering pipeline

- ANSI emitter: cell buffer → styled ANSI output with synchronized output
- Terminal abstraction: Terminal interface, ProcessTerminal, MockTerminal
- Minimal painter: Text (with repeat/fill), VStack, HStack painting
- cel.init(terminal): initialize framework with terminal instance
- cel.viewport/cel.render: full pipeline (render fn → paint → emit)
- cel.stop(): cleanup and restore terminal state
- 21 new tests (emitter: 12, end-to-end: 9), 63 total all passing

xonecas2026-04-03 092c1583d39f1d52e58949be18705b1c7c999c31 parent 2bb8ffd

7 files changed

packages/core/src/cel.test.ts+128−0
@@ -0,0 +1,128 @@
1+import { afterEach, describe, expect, test } from "bun:test";
2+import { cel } from "./cel.js";
3+import { MockTerminal } from "./terminal.js";
4+import { Text } from "./primitives/text.js";
5+import { VStack } from "./primitives/stacks.js";
6+import { HStack } from "./primitives/stacks.js";
7+
8+describe("cel end-to-end", () => {
9+ let term: MockTerminal;
10+
11+ afterEach(() => {
12+ cel.stop();
13+ });
14+
15+ function setup(columns = 20, rows = 5): MockTerminal {
16+ term = new MockTerminal(columns, rows);
17+ cel.init(term);
18+ return term;
19+ }
20+
21+ async function waitForRender(): Promise<void> {
22+ // process.nextTick batching — wait for it to fire
23+ await new Promise((resolve) => setTimeout(resolve, 10));
24+ }
25+
26+ test("renders a single Text node", async () => {
27+ const term = setup(10, 1);
28+ cel.viewport(() => Text("Hello"));
29+ await waitForRender();
30+
31+ expect(term.output).toContain("Hello");
32+ });
33+
34+ test("renders styled text with color", async () => {
35+ const term = setup(10, 1);
36+ cel.viewport(() => Text("Red", { fgColor: "red" }));
37+ await waitForRender();
38+
39+ expect(term.output).toContain("\x1b[31m");
40+ expect(term.output).toContain("Red");
41+ });
42+
43+ test("renders bold text", async () => {
44+ const term = setup(10, 1);
45+ cel.viewport(() => Text("Bold", { bold: true }));
46+ await waitForRender();
47+
48+ expect(term.output).toContain("\x1b[1m");
49+ expect(term.output).toContain("Bold");
50+ });
51+
52+ test("renders text with repeat fill", async () => {
53+ const term = setup(10, 1);
54+ cel.viewport(() => Text("-", { repeat: "fill" }));
55+ await waitForRender();
56+
57+ expect(term.output).toContain("----------");
58+ });
59+
60+ test("renders VStack with children", async () => {
61+ const term = setup(10, 4);
62+ cel.viewport(() => VStack({}, [Text("Line 1"), Text("Line 2")]));
63+ await waitForRender();
64+
65+ expect(term.output).toContain("Line 1");
66+ expect(term.output).toContain("Line 2");
67+ });
68+
69+ test("renders HStack with children", async () => {
70+ const term = setup(20, 1);
71+ cel.viewport(() => HStack({}, [Text("Left"), Text("Right")]));
72+ await waitForRender();
73+
74+ expect(term.output).toContain("Left");
75+ expect(term.output).toContain("Right");
76+ });
77+
78+ test("re-renders on cel.render()", async () => {
79+ const term = setup(10, 1);
80+ let text = "First";
81+ cel.viewport(() => Text(text));
82+ await waitForRender();
83+
84+ expect(term.output).toContain("First");
85+
86+ term.clearOutput();
87+ text = "Second";
88+ cel.render();
89+ await waitForRender();
90+
91+ expect(term.output).toContain("Second");
92+ });
93+
94+ test("batches multiple render calls", async () => {
95+ const term = setup(10, 1);
96+ let count = 0;
97+ let renderCount = 0;
98+
99+ cel.viewport(() => {
100+ renderCount++;
101+ return Text(`Count: ${count}`);
102+ });
103+ await waitForRender();
104+ expect(renderCount).toBe(1);
105+
106+ // Multiple synchronous render calls — should batch into one
107+ count = 1;
108+ cel.render();
109+ count = 2;
110+ cel.render();
111+ count = 3;
112+ cel.render();
113+
114+ await waitForRender();
115+
116+ expect(renderCount).toBe(2);
117+ expect(term.output).toContain("Count: 3");
118+ });
119+
120+ test("wraps output in synchronized output markers", async () => {
121+ const term = setup(10, 1);
122+ cel.viewport(() => Text("Hi"));
123+ await waitForRender();
124+
125+ expect(term.output).toContain("\x1b[?2026h");
126+ expect(term.output).toContain("\x1b[?2026l");
127+ });
128+});
packages/core/src/cel.ts+73−18
@@ -1,15 +1,46 @@
11 import type { Node } from "@cel-tui/types";
2+import { CellBuffer } from "./cell-buffer.js";
3+import { emitBuffer } from "./emitter.js";
4+import type { Terminal } from "./terminal.js";
5+import { paintNode } from "./paint.js";
26
37 type RenderFn = () => Node | Node[];
48
9+let terminal: Terminal | null = null;
510 let renderFn: RenderFn | null = null;
611 let renderScheduled = false;
12+let currentBuffer: CellBuffer | null = null;
713
814 function doRender(): void {
915 renderScheduled = false;
10- if (!renderFn) return;
11- const _tree = renderFn();
12- // TODO: layout → paint → composite → diff → emit
16+ if (!renderFn || !terminal) return;
17+
18+ const width = terminal.columns;
19+ const height = terminal.rows;
20+
21+ // Create or resize buffer
22+ if (
23+ !currentBuffer ||
24+ currentBuffer.width !== width ||
25+ currentBuffer.height !== height
26+ ) {
27+ currentBuffer = new CellBuffer(width, height);
28+ } else {
29+ currentBuffer.clear();
30+ }
31+
32+ // Get the tree from the render function
33+ const tree = renderFn();
34+ const layers = Array.isArray(tree) ? tree : [tree];
35+
36+ // Paint each layer into the buffer
37+ for (const layer of layers) {
38+ paintNode(layer, currentBuffer, 0, 0, width, height);
39+ }
40+
41+ // Emit to terminal
42+ const output = emitBuffer(currentBuffer);
43+ terminal.write(output);
1344 }
1445
1546 /**
@@ -22,19 +53,37 @@ function doRender(): void {
2253 *
2354 * @example
2455 * ```ts
25- * let count = 0;
56+ * import { cel, VStack, Text } from "@cel-tui/core";
57+ * import { ProcessTerminal } from "@cel-tui/core/terminal";
2658 *
59+ * cel.init(new ProcessTerminal());
2760 * cel.viewport(() =>
2861 * VStack({ height: "100%" }, [
29- * Text(`Count: ${count}`),
30- * HStack({ onClick: () => { count++; cel.render(); } }, [
31- * Text("[+1]"),
32- * ]),
62+ * Text("Hello, world!", { bold: true }),
3363 * ])
3464 * );
3565 * ```
3666 */
3767 export const cel = {
68+ /**
69+ * Initialize the framework with a terminal implementation.
70+ * Must be called before {@link cel.viewport}.
71+ *
72+ * @param term - Terminal to render to (ProcessTerminal or MockTerminal).
73+ */
74+ init(term: Terminal): void {
75+ terminal = term;
76+ terminal.start(
77+ (_data) => {
78+ // TODO: input routing (keys, mouse)
79+ },
80+ () => {
81+ // Terminal resize — trigger re-render
82+ cel.render();
83+ },
84+ );
85+ },
86+
3887 /**
3988 * Set the render function that returns the UI tree.
4089 * Triggers the first render automatically.
@@ -45,16 +94,6 @@ export const cel = {
4594 * nodes (multiple layers, composited bottom-to-top).
4695 *
4796 * @param fn - A function that returns the current UI tree.
48- *
49- * @example
50- * // Single layer
51- * cel.viewport(() => VStack({ height: "100%" }, [...]))
52- *
53- * // Multiple layers (modal on top)
54- * cel.viewport(() => [
55- * VStack({ height: "100%" }, [...mainUI]),
56- * VStack({ height: "100%" }, [...modalUI]),
57- * ])
5897 */
5998 viewport(fn: RenderFn): void {
6099 renderFn = fn;
@@ -73,4 +112,20 @@ export const cel = {
73112 renderScheduled = true;
74113 process.nextTick(doRender);
75114 },
115+
116+ /**
117+ * Stop the framework and restore terminal state.
118+ */
119+ stop(): void {
120+ terminal?.stop();
121+ terminal = null;
122+ renderFn = null;
123+ currentBuffer = null;
124+ renderScheduled = false;
125+ },
126+
127+ /** @internal — exposed for testing. */
128+ _getBuffer(): CellBuffer | null {
129+ return currentBuffer;
130+ },
76131 };
packages/core/src/emitter.test.ts+128−0
@@ -0,0 +1,128 @@
1+import { describe, expect, test } from "bun:test";
2+import { CellBuffer, type Cell } from "./cell-buffer.js";
3+import { emitBuffer } from "./emitter.js";
4+
5+function cell(char: string, overrides: Partial<Cell> = {}): Cell {
6+ return {
7+ char,
8+ fgColor: null,
9+ bgColor: null,
10+ bold: false,
11+ italic: false,
12+ underline: false,
13+ ...overrides,
14+ };
15+}
16+
17+describe("emitBuffer", () => {
18+ test("emits plain text", () => {
19+ const buf = new CellBuffer(5, 1);
20+ buf.set(0, 0, cell("H"));
21+ buf.set(1, 0, cell("e"));
22+ buf.set(2, 0, cell("l"));
23+ buf.set(3, 0, cell("l"));
24+ buf.set(4, 0, cell("o"));
25+ const output = emitBuffer(buf);
26+ // Should contain "Hello" somewhere in the output
27+ expect(output).toContain("Hello");
28+ });
29+
30+ test("emits multiple rows", () => {
31+ const buf = new CellBuffer(2, 2);
32+ buf.set(0, 0, cell("A"));
33+ buf.set(1, 0, cell("B"));
34+ buf.set(0, 1, cell("C"));
35+ buf.set(1, 1, cell("D"));
36+ const output = emitBuffer(buf);
37+ expect(output).toContain("AB");
38+ expect(output).toContain("CD");
39+ });
40+
41+ test("emits foreground color", () => {
42+ const buf = new CellBuffer(1, 1);
43+ buf.set(0, 0, cell("X", { fgColor: "red" }));
44+ const output = emitBuffer(buf);
45+ // CSI 31m = red foreground
46+ expect(output).toContain("\x1b[31m");
47+ expect(output).toContain("X");
48+ });
49+
50+ test("emits background color", () => {
51+ const buf = new CellBuffer(1, 1);
52+ buf.set(0, 0, cell("X", { bgColor: "blue" }));
53+ const output = emitBuffer(buf);
54+ // CSI 44m = blue background
55+ expect(output).toContain("\x1b[44m");
56+ expect(output).toContain("X");
57+ });
58+
59+ test("emits bold", () => {
60+ const buf = new CellBuffer(1, 1);
61+ buf.set(0, 0, cell("X", { bold: true }));
62+ const output = emitBuffer(buf);
63+ expect(output).toContain("\x1b[1m");
64+ });
65+
66+ test("emits italic", () => {
67+ const buf = new CellBuffer(1, 1);
68+ buf.set(0, 0, cell("X", { italic: true }));
69+ const output = emitBuffer(buf);
70+ expect(output).toContain("\x1b[3m");
71+ });
72+
73+ test("emits underline", () => {
74+ const buf = new CellBuffer(1, 1);
75+ buf.set(0, 0, cell("X", { underline: true }));
76+ const output = emitBuffer(buf);
77+ expect(output).toContain("\x1b[4m");
78+ });
79+
80+ test("combines multiple style attributes", () => {
81+ const buf = new CellBuffer(1, 1);
82+ buf.set(
83+ 0,
84+ 0,
85+ cell("X", { bold: true, fgColor: "green", bgColor: "black" }),
86+ );
87+ const output = emitBuffer(buf);
88+ expect(output).toContain("X");
89+ // Should contain bold (1), green fg (32), black bg (40) in some SGR
90+ expect(output).toContain("1");
91+ expect(output).toContain("32");
92+ expect(output).toContain("40");
93+ });
94+
95+ test("resets style between differently styled cells", () => {
96+ const buf = new CellBuffer(2, 1);
97+ buf.set(0, 0, cell("A", { fgColor: "red" }));
98+ buf.set(1, 0, cell("B", { fgColor: "blue" }));
99+ const output = emitBuffer(buf);
100+ expect(output).toContain("A");
101+ expect(output).toContain("B");
102+ // Should contain reset between the two
103+ expect(output).toContain("\x1b[0m");
104+ });
105+
106+ test("wraps output in synchronized output markers", () => {
107+ const buf = new CellBuffer(1, 1);
108+ const output = emitBuffer(buf);
109+ // Begin synchronized output
110+ expect(output.startsWith("\x1b[?2026h")).toBe(true);
111+ // End synchronized output
112+ expect(output.endsWith("\x1b[?2026l")).toBe(true);
113+ });
114+
115+ test("positions cursor at home before rendering", () => {
116+ const buf = new CellBuffer(1, 1);
117+ const output = emitBuffer(buf);
118+ // Should contain cursor home (CSI H)
119+ expect(output).toContain("\x1b[H");
120+ });
121+
122+ test("empty cells render as spaces", () => {
123+ const buf = new CellBuffer(3, 1);
124+ // Leave all cells empty
125+ const output = emitBuffer(buf);
126+ expect(output).toContain(" ");
127+ });
128+});
packages/core/src/emitter.ts+131−0
@@ -0,0 +1,131 @@
1+import type { Color } from "@cel-tui/types";
2+import type { Cell } from "./cell-buffer.js";
3+import { CellBuffer, EMPTY_CELL } from "./cell-buffer.js";
4+
5+// --- Color mapping ---
6+
7+const FG_CODES: Record<Color, number> = {
8+ black: 30,
9+ red: 31,
10+ green: 32,
11+ yellow: 33,
12+ blue: 34,
13+ magenta: 35,
14+ cyan: 36,
15+ white: 37,
16+ brightBlack: 90,
17+ brightRed: 91,
18+ brightGreen: 92,
19+ brightYellow: 93,
20+ brightBlue: 94,
21+ brightMagenta: 95,
22+ brightCyan: 96,
23+ brightWhite: 97,
24+};
25+
26+const BG_CODES: Record<Color, number> = {
27+ black: 40,
28+ red: 41,
29+ green: 42,
30+ yellow: 43,
31+ blue: 44,
32+ magenta: 45,
33+ cyan: 46,
34+ white: 47,
35+ brightBlack: 100,
36+ brightRed: 101,
37+ brightGreen: 102,
38+ brightYellow: 103,
39+ brightBlue: 104,
40+ brightMagenta: 105,
41+ brightCyan: 106,
42+ brightWhite: 107,
43+};
44+
45+// --- SGR generation ---
46+
47+function sgrForCell(cell: Cell): string {
48+ const codes: number[] = [];
49+ if (cell.bold) codes.push(1);
50+ if (cell.italic) codes.push(3);
51+ if (cell.underline) codes.push(4);
52+ if (cell.fgColor) codes.push(FG_CODES[cell.fgColor]);
53+ if (cell.bgColor) codes.push(BG_CODES[cell.bgColor]);
54+ if (codes.length === 0) return "";
55+ return `\x1b[${codes.join(";")}m`;
56+}
57+
58+function styleEquals(a: Cell, b: Cell): boolean {
59+ return (
60+ a.fgColor === b.fgColor &&
61+ a.bgColor === b.bgColor &&
62+ a.bold === b.bold &&
63+ a.italic === b.italic &&
64+ a.underline === b.underline
65+ );
66+}
67+
68+function hasStyle(cell: Cell): boolean {
69+ return (
70+ cell.bold ||
71+ cell.italic ||
72+ cell.underline ||
73+ cell.fgColor !== null ||
74+ cell.bgColor !== null
75+ );
76+}
77+
78+// --- Synchronized output markers ---
79+
80+const SYNC_START = "\x1b[?2026h";
81+const SYNC_END = "\x1b[?2026l";
82+const CURSOR_HOME = "\x1b[H";
83+const RESET = "\x1b[0m";
84+
85+/**
86+ * Emit a full cell buffer as an ANSI string for terminal output.
87+ *
88+ * Generates cursor positioning, SGR styling codes, and character content
89+ * for every cell. Output is wrapped in synchronized output markers
90+ * (CSI 2026) for flicker-free rendering.
91+ *
92+ * Optimizes by batching consecutive cells with the same style and
93+ * only emitting SGR codes when the style changes.
94+ *
95+ * @param buf - The cell buffer to render.
96+ * @returns A complete ANSI string ready to write to the terminal.
97+ */
98+export function emitBuffer(buf: CellBuffer): string {
99+ let out = SYNC_START + CURSOR_HOME;
100+
101+ let lastStyle: Cell | null = null;
102+
103+ for (let y = 0; y < buf.height; y++) {
104+ if (y > 0) out += "\r\n";
105+
106+ for (let x = 0; x < buf.width; x++) {
107+ const cell = buf.get(x, y);
108+
109+ // Emit style change if needed
110+ if (lastStyle === null || !styleEquals(cell, lastStyle)) {
111+ // Reset before applying new style
112+ if (lastStyle !== null && hasStyle(lastStyle)) {
113+ out += RESET;
114+ }
115+ const sgr = sgrForCell(cell);
116+ if (sgr) out += sgr;
117+ lastStyle = cell;
118+ }
119+
120+ out += cell.char;
121+ }
122+ }
123+
124+ // Final reset if any style was active
125+ if (lastStyle !== null && hasStyle(lastStyle)) {
126+ out += RESET;
127+ }
128+
129+ out += SYNC_END;
130+ return out;
131+}
packages/core/src/index.ts+4−0
@@ -42,3 +42,7 @@ export { VStack, HStack } from "./primitives/stacks.js";
4242 export { Text } from "./primitives/text.js";
4343 export { TextInput } from "./primitives/text-input.js";
4444 export { cel } from "./cel.js";
45+export { CellBuffer, EMPTY_CELL, type Cell } from "./cell-buffer.js";
46+export { emitBuffer } from "./emitter.js";
47+export { visibleWidth, extractAnsiCode } from "./width.js";
48+export { type Terminal, ProcessTerminal, MockTerminal } from "./terminal.js";
packages/core/src/paint.ts+138−0
@@ -0,0 +1,138 @@
1+import type { Node, Color } from "@cel-tui/types";
2+import type { Cell } from "./cell-buffer.js";
3+import { CellBuffer } from "./cell-buffer.js";
4+
5+/**
6+ * Paint a node into the cell buffer within the given rect.
7+ *
8+ * This is a minimal implementation for phase 2 — handles Text nodes
9+ * with basic styling. Layout engine will replace the hardcoded rect
10+ * passing in phase 3.
11+ *
12+ * @param node - The node to paint.
13+ * @param buf - Target cell buffer.
14+ * @param x - Left edge of the rect.
15+ * @param y - Top edge of the rect.
16+ * @param w - Width of the rect.
17+ * @param h - Height of the rect.
18+ */
19+export function paintNode(
20+ node: Node,
21+ buf: CellBuffer,
22+ x: number,
23+ y: number,
24+ w: number,
25+ h: number,
26+): void {
27+ switch (node.type) {
28+ case "text":
29+ paintText(node.content, node.props, buf, x, y, w, h);
30+ break;
31+ case "vstack":
32+ paintVStack(node, buf, x, y, w, h);
33+ break;
34+ case "hstack":
35+ paintHStack(node, buf, x, y, w, h);
36+ break;
37+ case "textinput":
38+ // TODO: implement in phase 7
39+ break;
40+ }
41+}
42+
43+function makeCell(
44+ char: string,
45+ props: {
46+ fgColor?: Color;
47+ bgColor?: Color;
48+ bold?: boolean;
49+ italic?: boolean;
50+ underline?: boolean;
51+ },
52+): Cell {
53+ return {
54+ char,
55+ fgColor: props.fgColor ?? null,
56+ bgColor: props.bgColor ?? null,
57+ bold: props.bold ?? false,
58+ italic: props.italic ?? false,
59+ underline: props.underline ?? false,
60+ };
61+}
62+
63+function paintText(
64+ content: string,
65+ props: Node extends { type: "text"; props: infer P } ? P : never,
66+ buf: CellBuffer,
67+ x: number,
68+ y: number,
69+ w: number,
70+ h: number,
71+): void {
72+ // Handle repeat: "fill"
73+ let text = content;
74+ if (props.repeat === "fill" && content.length > 0) {
75+ text = content.repeat(Math.ceil(w / content.length)).slice(0, w);
76+ } else if (typeof props.repeat === "number" && props.repeat > 0) {
77+ text = content.repeat(props.repeat);
78+ }
79+
80+ // Split into lines (preserve \n)
81+ const lines = text.split("\n");
82+
83+ for (let row = 0; row < lines.length && row < h; row++) {
84+ const line = lines[row]!;
85+ for (let col = 0; col < line.length && col < w; col++) {
86+ buf.set(x + col, y + row, makeCell(line[col]!, props));
87+ }
88+ }
89+}
90+
91+/**
92+ * Minimal VStack painter — divides height equally among children.
93+ * Will be replaced by the proper layout engine in phase 3.
94+ */
95+function paintVStack(
96+ node: Extract<Node, { type: "vstack" }>,
97+ buf: CellBuffer,
98+ x: number,
99+ y: number,
100+ w: number,
101+ h: number,
102+): void {
103+ if (node.children.length === 0) return;
104+
105+ // Simple equal distribution for now
106+ const childHeight = Math.floor(h / node.children.length);
107+ let currentY = y;
108+
109+ for (let i = 0; i < node.children.length; i++) {
110+ const ch = i === node.children.length - 1 ? y + h - currentY : childHeight;
111+ paintNode(node.children[i]!, buf, x, currentY, w, ch);
112+ currentY += ch;
113+ }
114+}
115+
116+/**
117+ * Minimal HStack painter — divides width equally among children.
118+ * Will be replaced by the proper layout engine in phase 3.
119+ */
120+function paintHStack(
121+ node: Extract<Node, { type: "hstack" }>,
122+ buf: CellBuffer,
123+ x: number,
124+ y: number,
125+ w: number,
126+ h: number,
127+): void {
128+ if (node.children.length === 0) return;
129+
130+ const childWidth = Math.floor(w / node.children.length);
131+ let currentX = x;
132+
133+ for (let i = 0; i < node.children.length; i++) {
134+ const cw = i === node.children.length - 1 ? x + w - currentX : childWidth;
135+ paintNode(node.children[i]!, buf, currentX, y, cw, h);
136+ currentX += cw;
137+ }
138+}
packages/core/src/terminal.ts+149−0
@@ -0,0 +1,149 @@
1+/**
2+ * Minimal terminal interface.
3+ *
4+ * Abstracts terminal I/O for both real usage (ProcessTerminal)
5+ * and testing (MockTerminal).
6+ */
7+export interface Terminal {
8+ /** Write a string to the terminal output. */
9+ write(data: string): void;
10+ /** Terminal width in columns. */
11+ get columns(): number;
12+ /** Terminal height in rows. */
13+ get rows(): number;
14+ /** Enter raw mode, enable mouse tracking, hide cursor. */
15+ start(onInput: (data: string) => void, onResize: () => void): void;
16+ /** Restore terminal state. */
17+ stop(): void;
18+ /** Hide the terminal cursor. */
19+ hideCursor(): void;
20+ /** Show the terminal cursor. */
21+ showCursor(): void;
22+}
23+
24+/**
25+ * Real terminal using process.stdin/stdout.
26+ */
27+export class ProcessTerminal implements Terminal {
28+ private wasRaw = false;
29+ private resizeHandler?: () => void;
30+
31+ get columns(): number {
32+ return process.stdout.columns || 80;
33+ }
34+
35+ get rows(): number {
36+ return process.stdout.rows || 24;
37+ }
38+
39+ write(data: string): void {
40+ process.stdout.write(data);
41+ }
42+
43+ start(onInput: (data: string) => void, onResize: () => void): void {
44+ this.resizeHandler = onResize;
45+ this.wasRaw = process.stdin.isRaw || false;
46+
47+ if (process.stdin.setRawMode) {
48+ process.stdin.setRawMode(true);
49+ }
50+ process.stdin.setEncoding("utf8");
51+ process.stdin.resume();
52+ process.stdin.on("data", onInput);
53+ process.stdout.on("resize", onResize);
54+
55+ // Enable mouse SGR mode
56+ this.write("\x1b[?1006h");
57+ this.hideCursor();
58+ }
59+
60+ stop(): void {
61+ // Disable mouse mode
62+ this.write("\x1b[?1006l");
63+ this.showCursor();
64+
65+ if (this.resizeHandler) {
66+ process.stdout.removeListener("resize", this.resizeHandler);
67+ }
68+
69+ process.stdin.pause();
70+ if (process.stdin.setRawMode) {
71+ process.stdin.setRawMode(this.wasRaw);
72+ }
73+ }
74+
75+ hideCursor(): void {
76+ this.write("\x1b[?25l");
77+ }
78+
79+ showCursor(): void {
80+ this.write("\x1b[?25h");
81+ }
82+}
83+
84+/**
85+ * In-memory terminal for testing.
86+ *
87+ * Captures all written output into a buffer and allows setting
88+ * fixed dimensions. No real I/O.
89+ */
90+export class MockTerminal implements Terminal {
91+ /** All output written to the terminal. */
92+ output = "";
93+ private _columns: number;
94+ private _rows: number;
95+ private inputHandler?: (data: string) => void;
96+ private resizeHandler?: () => void;
97+
98+ constructor(columns = 80, rows = 24) {
99+ this._columns = columns;
100+ this._rows = rows;
101+ }
102+
103+ get columns(): number {
104+ return this._columns;
105+ }
106+
107+ get rows(): number {
108+ return this._rows;
109+ }
110+
111+ write(data: string): void {
112+ this.output += data;
113+ }
114+
115+ start(onInput: (data: string) => void, onResize: () => void): void {
116+ this.inputHandler = onInput;
117+ this.resizeHandler = onResize;
118+ }
119+
120+ stop(): void {
121+ this.inputHandler = undefined;
122+ this.resizeHandler = undefined;
123+ }
124+
125+ hideCursor(): void {
126+ this.write("\x1b[?25l");
127+ }
128+
129+ showCursor(): void {
130+ this.write("\x1b[?25h");
131+ }
132+
133+ /** Simulate keyboard input. */
134+ sendInput(data: string): void {
135+ this.inputHandler?.(data);
136+ }
137+
138+ /** Simulate terminal resize. */
139+ setSize(columns: number, rows: number): void {
140+ this._columns = columns;
141+ this._rows = rows;
142+ this.resizeHandler?.();
143+ }
144+
145+ /** Clear captured output. */
146+ clearOutput(): void {
147+ this.output = "";
148+ }
149+}