64875
Mc
mini-coder / files
mini-coder / src / tui / term.ts
13.3 KB
1const COMBINING = /\p{M}/u; 2 3function charWidth(code: number): number { 4 if (code < 32 || (code >= 0x7f && code < 0xa0)) return 0; 5 if (code === 0x200b || code === 0x200c || code === 0x200d || code === 0xfeff) return 0; 6 if (code >= 0xfe00 && code <= 0xfe0f) return 0; 7 if (code >= 0xe0100 && code <= 0xe01ef) return 0; 8 if (COMBINING.test(String.fromCodePoint(code))) return 0; 9 if ( 10 (code >= 0x1100 && code <= 0x115f) || 11 (code >= 0x2e80 && code <= 0x303e) || 12 (code >= 0x3041 && code <= 0x33ff) || 13 (code >= 0x3400 && code <= 0x4dbf) || 14 (code >= 0x4e00 && code <= 0x9fff) || 15 (code >= 0xa000 && code <= 0xa4cf) || 16 (code >= 0xac00 && code <= 0xd7a3) || 17 (code >= 0xf900 && code <= 0xfaff) || 18 (code >= 0xfe10 && code <= 0xfe19) || 19 (code >= 0xfe30 && code <= 0xfe6f) || 20 (code >= 0xff00 && code <= 0xff60) || 21 (code >= 0xffe0 && code <= 0xffe6) || 22 (code >= 0x1f300 && code <= 0x1faff) || 23 (code >= 0x20000 && code <= 0x3fffd) 24 ) { 25 return 2; 26 } 27 return 1; 28} 29 30export function displayWidth(text: string): number { 31 let width = 0; 32 for (const ch of text) width += charWidth(ch.codePointAt(0)!); 33 return width; 34} 35 36/** An SGR sequence: zero cells wide, so it never affects a row break. */ 37const SGR = /^\x1b\[[0-9;]*m/; 38 39/** 40 * Everything a tool, a file or a model can emit that the terminal would act on 41 * but the TUI did not write itself: control bytes and every escape sequence but 42 * SGR. Dropped before the text is measured, so a row's width is its visible 43 * width and a result can only add rows — never move the cursor, erase the 44 * screen, or break the row model. Tabs survive to `expandTabs`, which owns them. 45 */ 46const UNSAFE = /(\x1b\[[0-9;]*m)|\x1b(?:\[[0-9;?]*[ -/]*[@-~]|.)|[\x00-\x08\x0a-\x1f\x7f-\x9f]/g; 47 48export function sanitize(text: string): string { 49 return text.replace(UNSAFE, (_match, sgr: string | undefined) => sgr ?? ""); 50} 51 52export function expandTabs(text: string, size = 4): string { 53 if (!text.includes("\t")) return text; 54 let column = 0; 55 let out = ""; 56 for (let i = 0; i < text.length; ) { 57 const escape = SGR.exec(text.slice(i)); 58 if (escape !== null) { 59 out += escape[0]; 60 i += escape[0].length; 61 continue; 62 } 63 const ch = String.fromCodePoint(text.codePointAt(i)!); 64 i += ch.length; 65 if (ch === "\t") { 66 const spaces = size - (column % size); 67 out += " ".repeat(spaces); 68 column += spaces; 69 } else { 70 out += ch; 71 column += charWidth(ch.codePointAt(0)!); 72 } 73 } 74 return out; 75} 76 77/** 78 * Splits one logical line into physical rows no wider than `width` cells. SGR 79 * sequences count as zero cells and stay attached to the text that follows. 80 */ 81export function wrapLine(text: string, width: number): string[] { 82 if (width <= 0) return [""]; 83 if (text === "") return [""]; 84 const rows: string[] = []; 85 let current = ""; 86 let used = 0; 87 for (let i = 0; i < text.length; ) { 88 if (text.charCodeAt(i) === 0x1b) { 89 const escape = SGR.exec(text.slice(i)); 90 if (escape !== null) { 91 current += escape[0]; 92 i += escape[0].length; 93 continue; 94 } 95 } 96 const ch = String.fromCodePoint(text.codePointAt(i)!); 97 const w = charWidth(ch.codePointAt(0)!); 98 if (used + w > width && current !== "") { 99 rows.push(current); 100 current = ""; 101 used = 0; 102 } 103 current += ch; 104 used += w; 105 i += ch.length; 106 } 107 rows.push(current); 108 return rows; 109} 110 111export type Key = 112 | { type: "text"; text: string } 113 | { type: "submit" } 114 | { type: "newline" } 115 | { type: "backspace" } 116 | { type: "delete" } 117 | { type: "wordBack" } 118 | { type: "left" } 119 | { type: "right" } 120 | { type: "wordLeft" } 121 | { type: "wordRight" } 122 | { type: "up" } 123 | { type: "down" } 124 | { type: "home" } 125 | { type: "end" } 126 | { type: "docStart" } 127 | { type: "docEnd" } 128 | { type: "tab" } 129 | { type: "escape" } 130 | { type: "interrupt" } 131 | { type: "eof" }; 132 133const PASTE_START = "\x1b[200~"; 134const PASTE_END = "\x1b[201~"; 135 136const SHIFT = 1; 137const ALT = 2; 138const CTRL = 4; 139/** Only real modifiers are acted on; lock bits and the rest are ignored. */ 140const MODS = SHIFT | ALT | CTRL; 141 142/** Codes for keys without a printable form, matching kitty's functional range. */ 143const CODE = { 144 enter: 13, 145 escape: 27, 146 tab: 9, 147 backspace: 127, 148 delete: 57349, 149 left: 57350, 150 right: 57351, 151 up: 57352, 152 down: 57353, 153 home: 57356, 154 end: 57357, 155} as const; 156 157/** The one table every input path resolves through: code and modifiers to key. */ 158const KEYS: Record<string, Key | undefined> = { 159 [`${CODE.enter}:0`]: { type: "submit" }, 160 [`${CODE.enter}:${ALT}`]: { type: "newline" }, 161 [`${CODE.enter}:${SHIFT}`]: { type: "newline" }, 162 [`${CODE.escape}:0`]: { type: "escape" }, 163 [`${CODE.tab}:0`]: { type: "tab" }, 164 [`${CODE.backspace}:0`]: { type: "backspace" }, 165 [`${CODE.backspace}:${CTRL}`]: { type: "wordBack" }, 166 [`${CODE.delete}:0`]: { type: "delete" }, 167 [`${CODE.left}:0`]: { type: "left" }, 168 [`${CODE.left}:${CTRL}`]: { type: "wordLeft" }, 169 [`${CODE.right}:0`]: { type: "right" }, 170 [`${CODE.right}:${CTRL}`]: { type: "wordRight" }, 171 [`${CODE.up}:0`]: { type: "up" }, 172 [`${CODE.down}:0`]: { type: "down" }, 173 [`${CODE.home}:0`]: { type: "home" }, 174 [`${CODE.home}:${CTRL}`]: { type: "docStart" }, 175 [`${CODE.end}:0`]: { type: "end" }, 176 [`${CODE.end}:${CTRL}`]: { type: "docEnd" }, 177 ["97:4"]: { type: "home" }, // Ctrl+A 178 ["98:2"]: { type: "wordBack" }, // Alt+B 179 ["99:4"]: { type: "interrupt" }, // Ctrl+C 180 ["100:4"]: { type: "eof" }, // Ctrl+D 181 ["101:4"]: { type: "end" }, // Ctrl+E 182 ["106:4"]: { type: "newline" }, // Ctrl+J 183 ["119:4"]: { type: "wordBack" }, // Ctrl+W 184}; 185 186const CSI_FINALS: Record<string, number | undefined> = { 187 A: CODE.up, 188 B: CODE.down, 189 C: CODE.right, 190 D: CODE.left, 191 H: CODE.home, 192 F: CODE.end, 193}; 194 195const CSI_TILDES: Record<number, number | undefined> = { 196 1: CODE.home, 197 3: CODE.delete, 198 4: CODE.end, 199 7: CODE.home, 200 8: CODE.end, 201}; 202 203interface Chord { 204 code: number; 205 mods: number; 206} 207 208function lookup(code: number, mods: number): Key | null { 209 return KEYS[`${code}:${mods}`] ?? null; 210} 211 212/** Control bytes are never text: they resolve through the table or vanish. */ 213function mapPoint(code: number): Key | null { 214 if (code === 0x7f) return lookup(CODE.backspace, 0); 215 if (code < 0x20) { 216 // A legacy control byte, as the chord the same key arrives as elsewhere. 217 if (code === 0x08) return lookup(CODE.backspace, 0); 218 if (code === 0x09) return lookup(CODE.tab, 0); 219 if (code === 0x0d) return lookup(CODE.enter, 0); 220 return lookup(code + 0x60, CTRL); 221 } 222 return { type: "text", text: String.fromCodePoint(code) }; 223} 224 225function modsOf(field: string | undefined): number { 226 const raw = Number.parseInt(field ?? "", 10); 227 return Number.isFinite(raw) && raw > 0 ? (raw - 1) & MODS : 0; 228} 229 230/** `code[:shifted[:base]];mods[:event];text` */ 231function csiUChord(params: string): Chord | null { 232 const fields = params.split(";"); 233 const code = Number.parseInt(fields[0].split(":")[0], 10); 234 if (!Number.isFinite(code)) return null; // probe replies and private forms 235 if (code >= 57344) return null; // functional keys never arrive as CSI-u 236 return { code, mods: modsOf(fields[1]?.split(":")[0]) }; 237} 238 239/** `params final`: the legacy `CSI 1;5D` form and SS3's bare `A`. */ 240function legacyChord(final: string, params: string): Chord | null { 241 const fields = params.split(";"); 242 const code = final === "~" ? CSI_TILDES[Number.parseInt(fields[0], 10)] : CSI_FINALS[final]; 243 return code === undefined ? null : { code, mods: modsOf(fields[1]) }; 244} 245 246function normalizePaste(text: string): string { 247 return text.replace(/\r\n?/g, "\n"); 248} 249 250class KeyParser { 251 private buffer = ""; 252 private pasting = false; 253 254 /** What the buffer may still complete: a lone ESC, a partial sequence, or nothing. */ 255 pending(): "escape" | "sequence" | null { 256 if (this.pasting) return null; 257 if (this.buffer === "\x1b") return "escape"; 258 return this.buffer.length > 1 ? "sequence" : null; 259 } 260 261 flushEscape(): Key[] { 262 if (this.buffer !== "\x1b") return []; 263 this.buffer = ""; 264 return [{ type: "escape" }]; 265 } 266 267 flushSequence(): void { 268 this.buffer = ""; 269 } 270 271 feed(chunk: string): Key[] { 272 this.buffer += chunk; 273 const keys: Key[] = []; 274 for (;;) { 275 if (this.pasting) { 276 const end = this.buffer.indexOf(PASTE_END); 277 if (end >= 0) { 278 if (end > 0) keys.push({ type: "text", text: normalizePaste(this.buffer.slice(0, end)) }); 279 this.buffer = this.buffer.slice(end + PASTE_END.length); 280 this.pasting = false; 281 continue; 282 } 283 if (this.buffer.length > PASTE_END.length) { 284 const keep = PASTE_END.length - 1; 285 const emit = this.buffer.slice(0, this.buffer.length - keep); 286 this.buffer = this.buffer.slice(this.buffer.length - keep); 287 if (emit) keys.push({ type: "text", text: normalizePaste(emit) }); 288 } 289 break; 290 } 291 292 if (this.buffer === "") break; 293 if (this.buffer.startsWith(PASTE_START)) { 294 this.buffer = this.buffer.slice(PASTE_START.length); 295 this.pasting = true; 296 continue; 297 } 298 if (this.buffer[0] === "\x1b") { 299 if (!this.parseEscape(keys)) break; 300 continue; 301 } 302 303 const code = this.buffer.codePointAt(0)!; 304 const ch = String.fromCodePoint(code); 305 this.buffer = this.buffer.slice(ch.length); 306 const key = mapPoint(code); 307 if (key) keys.push(key); 308 } 309 return keys; 310 } 311 312 private parseEscape(keys: Key[]): boolean { 313 const buffer = this.buffer; 314 if (buffer.length < 2) return false; 315 const next = buffer[1]; 316 if (next === "[" || next === "O") return this.parseCsi(keys); 317 if (next === "]") return this.skipString(true); 318 if (next === "P" || next === "X" || next === "^" || next === "_") return this.skipString(false); 319 this.buffer = buffer.slice(2); 320 const key = lookup(next.codePointAt(0)!, ALT); 321 if (key) keys.push(key); 322 return true; 323 } 324 325 private parseCsi(keys: Key[]): boolean { 326 const buffer = this.buffer; 327 let i = 2; 328 while (i < buffer.length) { 329 const code = buffer.charCodeAt(i); 330 if (code >= 0x40 && code <= 0x7e) break; 331 i++; 332 } 333 if (i >= buffer.length) return false; 334 const final = buffer[i]; 335 const params = buffer.slice(2, i); 336 this.buffer = buffer.slice(i + 1); 337 const chord = final === "u" ? csiUChord(params) : legacyChord(final, params); 338 if (chord !== null) { 339 const key = lookup(chord.code, chord.mods); 340 if (key) keys.push(key); 341 } 342 return true; 343 } 344 345 /** OSC ends at BEL or ST; DCS/APC/PM/SOS end at ST. Skipped whole. */ 346 private skipString(bel: boolean): boolean { 347 const st = this.buffer.indexOf("\x1b\\", 2); 348 const bell = bel ? this.buffer.indexOf("\x07", 2) : -1; 349 let end = -1; 350 if (bell >= 0 && (st < 0 || bell < st)) end = bell + 1; 351 else if (st >= 0) end = st + 2; 352 if (end < 0) return false; 353 this.buffer = this.buffer.slice(end); 354 return true; 355 } 356} 357 358interface TerminalHandlers { 359 onKey: (key: Key) => void; 360 onResize: () => void; 361} 362 363export class Terminal { 364 private readonly handlers: TerminalHandlers; 365 private parser = new KeyParser(); 366 private escapeTimer: NodeJS.Timeout | undefined; 367 private sequenceTimer: NodeJS.Timeout | undefined; 368 private started = false; 369 370 constructor(handlers: TerminalHandlers) { 371 this.handlers = handlers; 372 } 373 374 get width(): number { 375 return process.stdout.columns && process.stdout.columns > 0 ? process.stdout.columns : 80; 376 } 377 378 get height(): number { 379 return process.stdout.rows && process.stdout.rows > 0 ? process.stdout.rows : 24; 380 } 381 382 start(): void { 383 if (this.started) return; 384 this.started = true; 385 process.stdin.setEncoding("utf8"); 386 if (process.stdin.isTTY) process.stdin.setRawMode(true); 387 process.stdin.resume(); 388 process.stdin.on("data", this.onData); 389 process.stdout.on("resize", this.onResize); 390 // Bracketed paste, then kitty flag 1 so `Shift+Enter` is distinguishable. 391 if (process.stdout.isTTY) process.stdout.write("\x1b[?2004h\x1b[>1u\x1b[?u"); 392 } 393 394 stop(): void { 395 if (!this.started) return; 396 this.started = false; 397 this.clearTimers(); 398 process.stdin.off("data", this.onData); 399 process.stdout.off("resize", this.onResize); 400 if (process.stdout.isTTY) process.stdout.write("\x1b[<u\x1b[?2004l"); 401 if (process.stdin.isTTY) process.stdin.setRawMode(false); 402 process.stdin.pause(); 403 } 404 405 write(text: string): void { 406 process.stdout.write(text); 407 } 408 409 private clearTimers(): void { 410 if (this.escapeTimer) clearTimeout(this.escapeTimer); 411 if (this.sequenceTimer) clearTimeout(this.sequenceTimer); 412 this.escapeTimer = undefined; 413 this.sequenceTimer = undefined; 414 } 415 416 private onData = (chunk: string): void => { 417 // Both timers reset on every chunk, so `Alt`+key stays snappy and an 418 // incomplete sequence never wedges the buffer. 419 this.clearTimers(); 420 for (const key of this.parser.feed(chunk)) this.handlers.onKey(key); 421 const pending = this.parser.pending(); 422 if (pending === "escape") { 423 this.escapeTimer = setTimeout(() => { 424 this.escapeTimer = undefined; 425 for (const key of this.parser.flushEscape()) this.handlers.onKey(key); 426 }, 30); 427 } else if (pending === "sequence") { 428 this.sequenceTimer = setTimeout(() => { 429 this.sequenceTimer = undefined; 430 this.parser.flushSequence(); 431 }, 150); 432 } 433 }; 434 435 private onResize = (): void => this.handlers.onResize(); 436}