70160
Ce
cel-tui / files
cel-tui / packages / core / src / terminal.ts
8.1 KB
1import type { KittyKeyboardOptions } from "@cel-tui/types"; 2 3/** Optional terminal modes selected by `cel.init()`. */ 4export interface TerminalStartOptions { 5 /** Kitty progressive-enhancement flags beyond baseline disambiguation. */ 6 kittyKeyboard?: KittyKeyboardOptions; 7} 8 9function kittyKeyboardFlags(options?: KittyKeyboardOptions): number { 10 let flags = 1; // Disambiguate escape codes (the existing default). 11 if (options?.reportEventTypes) flags |= 2; 12 if (options?.reportAlternateKeys) flags |= 4; 13 if (options?.reportAllKeys || options?.reportAssociatedText) flags |= 8; 14 if (options?.reportAssociatedText) flags |= 16; 15 return flags; 16} 17 18/** 19 * Minimal terminal interface. 20 * 21 * Abstracts terminal I/O for both real usage (ProcessTerminal) 22 * and testing (MockTerminal). 23 */ 24export interface Terminal { 25 /** Write a string to the terminal output. */ 26 write(data: string): void; 27 /** Terminal width in columns. */ 28 get columns(): number; 29 /** Terminal height in rows. */ 30 get rows(): number; 31 /** 32 * Enter raw mode, push Kitty keyboard flags, enable bracketed paste mode, 33 * enable mouse tracking, and hide the cursor. 34 * 35 * The framework prefers Kitty semantics but its parser also accepts mixed 36 * tmux/legacy keyboard encodings that may still arrive on stdin. 37 */ 38 start( 39 onInput: (data: string) => void, 40 onResize: () => void, 41 options?: TerminalStartOptions, 42 ): void; 43 /** Restore terminal modes, visibility, and the configured default cursor shape. */ 44 stop(): void; 45 /** Hide the terminal cursor. */ 46 hideCursor(): void; 47 /** Show the terminal cursor. */ 48 showCursor(): void; 49} 50 51/** 52 * Real terminal using process.stdin/stdout. 53 * 54 * Enables Kitty keyboard protocol baseline disambiguation plus requested 55 * progressive enhancements, bracketed paste mode, SGR mouse tracking, and 56 * raw mode. The runtime prefers Kitty semantics for full 57 * modifier fidelity, while the parser remains compatible with mixed 58 * tmux/legacy keyboard encodings that may still arrive on stdin. All modes are 59 * restored on stop/crash. 60 */ 61export class ProcessTerminal implements Terminal { 62 private wasRaw = false; 63 private resizeHandler?: () => void; 64 private inputHandler?: (data: string) => void; 65 private cleanupBound?: () => void; 66 private sigintHandler?: () => void; 67 private sigtermHandler?: () => void; 68 private uncaughtExceptionHandler?: (err: unknown) => void; 69 private unhandledRejectionHandler?: (err: unknown) => void; 70 private stopped = false; 71 72 get columns(): number { 73 return process.stdout.columns || 80; 74 } 75 76 get rows(): number { 77 return process.stdout.rows || 24; 78 } 79 80 write(data: string): void { 81 process.stdout.write(data); 82 } 83 84 start( 85 onInput: (data: string) => void, 86 onResize: () => void, 87 options?: TerminalStartOptions, 88 ): void { 89 this.stopped = false; 90 this.inputHandler = onInput; 91 this.resizeHandler = () => { 92 // Clear screen on resize to avoid scrollback artifacts 93 this.write("\x1b[2J\x1b[H"); 94 onResize(); 95 }; 96 this.wasRaw = process.stdin.isRaw || false; 97 98 if (process.stdin.setRawMode) { 99 process.stdin.setRawMode(true); 100 } 101 process.stdin.setEncoding("utf8"); 102 process.stdin.resume(); 103 process.stdin.on("data", onInput); 104 process.stdout.on("resize", this.resizeHandler); 105 106 // Switch to alternate screen buffer (restored on exit) 107 this.write("\x1b[?1049h"); 108 // Push Kitty keyboard flags after entering the alternate screen. The 109 // baseline remains disambiguation-only unless enhancements were requested. 110 this.write(`\x1b[>${kittyKeyboardFlags(options?.kittyKeyboard)}u`); 111 // Enable bracketed paste mode 112 this.write("\x1b[?2004h"); 113 // Enable mouse tracking (normal mode) + SGR encoding 114 this.write("\x1b[?1000h\x1b[?1006h"); 115 this.hideCursor(); 116 117 // Register cleanup handlers for crash/exit scenarios 118 this.cleanupBound = () => this.cleanup(); 119 this.sigintHandler = () => this.terminateFromSignal("SIGINT"); 120 this.sigtermHandler = () => this.terminateFromSignal("SIGTERM"); 121 this.uncaughtExceptionHandler = (err) => { 122 this.cleanup(); 123 console.error(err); 124 process.exit(1); 125 }; 126 this.unhandledRejectionHandler = (err) => { 127 this.cleanup(); 128 console.error(err); 129 process.exit(1); 130 }; 131 132 process.on("exit", this.cleanupBound); 133 process.on("SIGINT", this.sigintHandler); 134 process.on("SIGTERM", this.sigtermHandler); 135 process.on("uncaughtException", this.uncaughtExceptionHandler); 136 process.on("unhandledRejection", this.unhandledRejectionHandler); 137 } 138 139 stop(): void { 140 this.cleanup(); 141 } 142 143 /** Restore terminal state, then unconditionally re-deliver the signal. */ 144 private terminateFromSignal(signal: "SIGINT" | "SIGTERM"): void { 145 this.cleanup(); 146 // Other application listeners may otherwise consume the re-delivered 147 // signal and leave a half-stopped process alive. The process is committed 148 // to termination at this point; removing listeners preserves the native 149 // signal exit status instead of substituting process.exit(). 150 process.removeAllListeners(signal); 151 process.kill(process.pid, signal); 152 } 153 154 /** 155 * Restore terminal state. Safe to call multiple times. 156 */ 157 private cleanup(): void { 158 if (this.stopped) return; 159 this.stopped = true; 160 161 // Disable mouse tracking + SGR encoding 162 this.write("\x1b[?1006l\x1b[?1000l"); 163 // Disable bracketed paste mode 164 this.write("\x1b[?2004l"); 165 // Pop Kitty keyboard protocol mode 166 this.write("\x1b[<u"); 167 // Restore the user's configured cursor shape before making it visible. 168 this.write("\x1b[0 q"); 169 this.showCursor(); 170 // Restore main screen buffer 171 this.write("\x1b[?1049l"); 172 173 if (this.resizeHandler) { 174 process.stdout.removeListener("resize", this.resizeHandler); 175 } 176 if (this.inputHandler) { 177 process.stdin.removeListener("data", this.inputHandler); 178 } 179 180 process.stdin.pause(); 181 if (process.stdin.setRawMode) { 182 process.stdin.setRawMode(this.wasRaw); 183 } 184 185 // Remove process handlers 186 if (this.cleanupBound) { 187 process.removeListener("exit", this.cleanupBound); 188 } 189 if (this.sigintHandler) { 190 process.removeListener("SIGINT", this.sigintHandler); 191 } 192 if (this.sigtermHandler) { 193 process.removeListener("SIGTERM", this.sigtermHandler); 194 } 195 if (this.uncaughtExceptionHandler) { 196 process.removeListener( 197 "uncaughtException", 198 this.uncaughtExceptionHandler, 199 ); 200 } 201 if (this.unhandledRejectionHandler) { 202 process.removeListener( 203 "unhandledRejection", 204 this.unhandledRejectionHandler, 205 ); 206 } 207 } 208 209 hideCursor(): void { 210 this.write("\x1b[?25l"); 211 } 212 213 showCursor(): void { 214 this.write("\x1b[?25h"); 215 } 216} 217 218/** 219 * In-memory terminal for testing. 220 * 221 * Captures all written output into a buffer and allows setting 222 * fixed dimensions. No real I/O. 223 */ 224export class MockTerminal implements Terminal { 225 /** All output written to the terminal. */ 226 output = ""; 227 private _columns: number; 228 private _rows: number; 229 private inputHandler?: (data: string) => void; 230 private resizeHandler?: () => void; 231 232 constructor(columns = 80, rows = 24) { 233 this._columns = columns; 234 this._rows = rows; 235 } 236 237 get columns(): number { 238 return this._columns; 239 } 240 241 get rows(): number { 242 return this._rows; 243 } 244 245 write(data: string): void { 246 this.output += data; 247 } 248 249 start( 250 onInput: (data: string) => void, 251 onResize: () => void, 252 _options?: TerminalStartOptions, 253 ): void { 254 this.inputHandler = onInput; 255 this.resizeHandler = onResize; 256 } 257 258 stop(): void { 259 this.inputHandler = undefined; 260 this.resizeHandler = undefined; 261 } 262 263 hideCursor(): void { 264 this.write("\x1b[?25l"); 265 } 266 267 showCursor(): void { 268 this.write("\x1b[?25h"); 269 } 270 271 /** Simulate keyboard input. */ 272 sendInput(data: string): void { 273 this.inputHandler?.(data); 274 } 275 276 /** Simulate terminal resize. */ 277 setSize(columns: number, rows: number): void { 278 this._columns = columns; 279 this._rows = rows; 280 this.resizeHandler?.(); 281 } 282 283 /** Clear captured output. */ 284 clearOutput(): void { 285 this.output = ""; 286 } 287}