| 1 | import { Key } from "ink"; |
| 2 | |
| 3 | export const COLLAPSE_SIZE = 800; // Characters threshold for collapsing pasted content |
| 4 | export const RAPID_INPUT_THRESHOLD = 200; // Minimum characters to trigger rapid input detection |
| 5 | export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image |
| 6 | export const MAX_IMAGE_COUNT = 20; // Maximum number of images |
| 7 | export const MAX_TOTAL_IMAGE_MEMORY = 50 * 1024 * 1024; // 50MB total image memory |
| 8 | |
| 9 | export class TextBuffer { |
| 10 | private _text: string = ""; |
| 11 | private _cursor: number = 0; |
| 12 | private _pasteBuffer: string = ""; |
| 13 | private _inPasteMode: boolean = false; |
| 14 | private _rapidInputBuffer: string = ""; |
| 15 | private _rapidInputStartPos: number = 0; |
| 16 | private _lastInputTime: number = 0; |
| 17 | private _rapidInputTimer: NodeJS.Timeout | null = null; |
| 18 | private _onStateChange?: () => void; |
| 19 | private _pasteMap = new Map<string, string>(); // placeholder -> original content |
| 20 | private _pasteCounter: number = 0; |
| 21 | private _imageMap = new Map<string, Buffer>(); // placeholder -> image buffer |
| 22 | private _imageCounter: number = 0; |
| 23 | |
| 24 | constructor(initialText: string = "") { |
| 25 | this._text = initialText; |
| 26 | this._cursor = initialText.length; |
| 27 | } |
| 28 | |
| 29 | get text(): string { |
| 30 | return this._text; |
| 31 | } |
| 32 | |
| 33 | get cursor(): number { |
| 34 | return this._cursor; |
| 35 | } |
| 36 | |
| 37 | setText(text: string): void { |
| 38 | this._text = text; |
| 39 | this._cursor = Math.min(this._cursor, text.length); |
| 40 | } |
| 41 | |
| 42 | setCursor(position: number): void { |
| 43 | this._cursor = Math.max(0, Math.min(position, this._text.length)); |
| 44 | } |
| 45 | |
| 46 | insertText(text: string): void { |
| 47 | // Normalize line endings to prevent terminal display issues |
| 48 | const normalizedText = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); |
| 49 | this._text = |
| 50 | this._text.slice(0, this._cursor) + |
| 51 | normalizedText + |
| 52 | this._text.slice(this._cursor); |
| 53 | this._cursor += normalizedText.length; |
| 54 | } |
| 55 | |
| 56 | deleteCharAt(position: number): void { |
| 57 | if (position >= 0 && position < this._text.length) { |
| 58 | this._text = |
| 59 | this._text.slice(0, position) + this._text.slice(position + 1); |
| 60 | if (this._cursor > position) { |
| 61 | this._cursor--; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | deleteBackward(): void { |
| 67 | if (this._cursor > 0) { |
| 68 | this.deleteCharAt(this._cursor - 1); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | deleteForward(): void { |
| 73 | if (this._cursor < this._text.length) { |
| 74 | this.deleteCharAt(this._cursor); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | private findWordBoundary( |
| 79 | position: number, |
| 80 | direction: "left" | "right", |
| 81 | ): number { |
| 82 | if (direction === "left") { |
| 83 | // Find start of current word or previous word |
| 84 | let pos = Math.max(0, position - 1); |
| 85 | |
| 86 | // Skip whitespace |
| 87 | while (pos > 0 && /\s/.test(this._text[pos])) { |
| 88 | pos--; |
| 89 | } |
| 90 | |
| 91 | // Find word boundary |
| 92 | while (pos > 0 && !/\s/.test(this._text[pos - 1])) { |
| 93 | pos--; |
| 94 | } |
| 95 | |
| 96 | return pos; |
| 97 | } else { |
| 98 | // Find end of current word or next word |
| 99 | let pos = position; |
| 100 | |
| 101 | // Skip whitespace |
| 102 | while (pos < this._text.length && /\s/.test(this._text[pos])) { |
| 103 | pos++; |
| 104 | } |
| 105 | |
| 106 | // Find word boundary |
| 107 | while (pos < this._text.length && !/\s/.test(this._text[pos])) { |
| 108 | pos++; |
| 109 | } |
| 110 | |
| 111 | return pos; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | moveWordLeft(): void { |
| 116 | this._cursor = this.findWordBoundary(this._cursor, "left"); |
| 117 | } |
| 118 | |
| 119 | moveWordRight(): void { |
| 120 | this._cursor = this.findWordBoundary(this._cursor, "right"); |
| 121 | } |
| 122 | |
| 123 | deleteWordBackward(): void { |
| 124 | const wordStart = this.findWordBoundary(this._cursor, "left"); |
| 125 | if (wordStart < this._cursor) { |
| 126 | this._text = |
| 127 | this._text.slice(0, wordStart) + this._text.slice(this._cursor); |
| 128 | this._cursor = wordStart; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | deleteWordForward(): void { |
| 133 | const wordEnd = this.findWordBoundary(this._cursor, "right"); |
| 134 | if (wordEnd > this._cursor) { |
| 135 | this._text = |
| 136 | this._text.slice(0, this._cursor) + this._text.slice(wordEnd); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | moveToStart(): void { |
| 141 | this._cursor = 0; |
| 142 | } |
| 143 | |
| 144 | moveToEnd(): void { |
| 145 | this._cursor = this._text.length; |
| 146 | } |
| 147 | |
| 148 | moveLeft(): void { |
| 149 | this._cursor = Math.max(0, this._cursor - 1); |
| 150 | } |
| 151 | |
| 152 | moveRight(): void { |
| 153 | this._cursor = Math.min(this._text.length, this._cursor + 1); |
| 154 | } |
| 155 | |
| 156 | clear(): void { |
| 157 | this._text = ""; |
| 158 | this._cursor = 0; |
| 159 | this._pasteMap.clear(); |
| 160 | this._pasteCounter = 0; |
| 161 | this._imageMap.clear(); |
| 162 | this._imageCounter = 0; |
| 163 | this._pasteBuffer = ""; |
| 164 | this._inPasteMode = false; |
| 165 | this._rapidInputBuffer = ""; |
| 166 | this._rapidInputStartPos = 0; |
| 167 | this._lastInputTime = 0; |
| 168 | if (this._rapidInputTimer) { |
| 169 | clearTimeout(this._rapidInputTimer); |
| 170 | this._rapidInputTimer = null; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | isInPasteMode(): boolean { |
| 175 | return this._inPasteMode; |
| 176 | } |
| 177 | |
| 178 | isInRapidInputMode(): boolean { |
| 179 | return this._rapidInputBuffer.length > 0; |
| 180 | } |
| 181 | |
| 182 | setStateChangeCallback(callback: () => void): void { |
| 183 | this._onStateChange = callback; |
| 184 | } |
| 185 | |
| 186 | // Called on Enter to expand full pasted content before submission |
| 187 | expandAllPasteBlocks(): void { |
| 188 | for (const [placeholder, originalContent] of this._pasteMap.entries()) { |
| 189 | const regex = new RegExp(this.escapeRegex(placeholder), "g"); |
| 190 | // Normalize line endings to prevent terminal display issues |
| 191 | const normalizedContent = originalContent |
| 192 | .replace(/\r\n/g, "\n") |
| 193 | .replace(/\r/g, "\n"); |
| 194 | this._text = this._text.replace(regex, normalizedContent); |
| 195 | } |
| 196 | this._pasteMap.clear(); |
| 197 | } |
| 198 | |
| 199 | // Add image to buffer and return placeholder |
| 200 | addImage(imageBuffer: Buffer): string { |
| 201 | // Validate image size |
| 202 | if (imageBuffer.length > MAX_IMAGE_SIZE) { |
| 203 | throw new Error( |
| 204 | `Image size ${(imageBuffer.length / 1024 / 1024).toFixed(1)}MB exceeds maximum allowed size of ${MAX_IMAGE_SIZE / 1024 / 1024}MB`, |
| 205 | ); |
| 206 | } |
| 207 | |
| 208 | // Check image count limit |
| 209 | if (this._imageMap.size >= MAX_IMAGE_COUNT) { |
| 210 | throw new Error(`Cannot add more than ${MAX_IMAGE_COUNT} images`); |
| 211 | } |
| 212 | |
| 213 | // Check total memory usage |
| 214 | const currentMemoryUsage = Array.from(this._imageMap.values()).reduce( |
| 215 | (total, buffer) => total + buffer.length, |
| 216 | 0, |
| 217 | ); |
| 218 | |
| 219 | if (currentMemoryUsage + imageBuffer.length > MAX_TOTAL_IMAGE_MEMORY) { |
| 220 | const currentUsageMB = (currentMemoryUsage / 1024 / 1024).toFixed(1); |
| 221 | const maxUsageMB = MAX_TOTAL_IMAGE_MEMORY / 1024 / 1024; |
| 222 | throw new Error( |
| 223 | `Adding image would exceed total memory limit. Current usage: ${currentUsageMB}MB, Maximum: ${maxUsageMB}MB`, |
| 224 | ); |
| 225 | } |
| 226 | |
| 227 | this._imageCounter++; |
| 228 | const placeholder = `[Image #${this._imageCounter}]`; |
| 229 | this._imageMap.set(placeholder, imageBuffer); |
| 230 | this.insertText(placeholder); |
| 231 | return placeholder; |
| 232 | } |
| 233 | |
| 234 | // Get all images for message formatting |
| 235 | getAllImages(): Map<string, Buffer> { |
| 236 | return new Map(this._imageMap); |
| 237 | } |
| 238 | |
| 239 | // Clear images after message submission |
| 240 | clearImages(): void { |
| 241 | this._imageMap.clear(); |
| 242 | this._imageCounter = 0; |
| 243 | } |
| 244 | |
| 245 | // Test helper: forces immediate finalization without waiting for timers |
| 246 | flushPendingInput(): void { |
| 247 | if (this._rapidInputTimer) { |
| 248 | clearTimeout(this._rapidInputTimer); |
| 249 | this._rapidInputTimer = null; |
| 250 | this.finalizeRapidInput(); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | private escapeRegex(str: string): string { |
| 255 | return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 256 | } |
| 257 | |
| 258 | // Creates placeholder for single line or multi-line pastes |
| 259 | private createPlaceholder(originalText: string): string { |
| 260 | this._pasteCounter++; |
| 261 | const lineCount = originalText.split(/\r\n|\r|\n/).length; |
| 262 | |
| 263 | if (lineCount === 1) { |
| 264 | return `[Paste #${this._pasteCounter}]`; |
| 265 | } else { |
| 266 | return `[Paste #${this._pasteCounter}, ${lineCount} lines]`; |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // Handles bracketed paste: \e[200~ (start) and \e[201~ (end) sequences |
| 271 | private handleBracketedPaste(input: string): boolean { |
| 272 | // Modern terminals wrap pasted content in escape sequences |
| 273 | if (input === "\u001b[200~") { |
| 274 | // Clear any pending rapid input timer to avoid conflicts |
| 275 | if (this._rapidInputTimer) { |
| 276 | clearTimeout(this._rapidInputTimer); |
| 277 | this._rapidInputTimer = null; |
| 278 | } |
| 279 | this._inPasteMode = true; |
| 280 | this._pasteBuffer = ""; |
| 281 | return true; |
| 282 | } |
| 283 | |
| 284 | if (input === "\u001b[201~") { |
| 285 | this._inPasteMode = false; |
| 286 | |
| 287 | if (this._pasteBuffer.length > COLLAPSE_SIZE) { |
| 288 | const placeholder = this.createPlaceholder(this._pasteBuffer); |
| 289 | this._pasteMap.set(placeholder, this._pasteBuffer); |
| 290 | this.insertText(placeholder); |
| 291 | } else { |
| 292 | this.insertText(this._pasteBuffer); |
| 293 | } |
| 294 | |
| 295 | this._pasteBuffer = ""; |
| 296 | return true; |
| 297 | } |
| 298 | |
| 299 | return false; |
| 300 | } |
| 301 | |
| 302 | // Fallback paste detection: detects rapid chunks by timing and size RAPID_INPUT_THRESHOLD |
| 303 | private handleRapidInput(input: string): boolean { |
| 304 | const now = Date.now(); |
| 305 | const timeSinceLastInput = now - this._lastInputTime; |
| 306 | |
| 307 | // If we're already in rapid input mode and this comes quickly, add to buffer |
| 308 | if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 100) { |
| 309 | this._rapidInputBuffer += input; |
| 310 | this._lastInputTime = now; |
| 311 | |
| 312 | if (this._rapidInputTimer) { |
| 313 | clearTimeout(this._rapidInputTimer); |
| 314 | } |
| 315 | |
| 316 | // Reset timer: 200ms pause indicates end of paste |
| 317 | this._rapidInputTimer = setTimeout(() => { |
| 318 | this.finalizeRapidInput(); |
| 319 | }, 200); |
| 320 | |
| 321 | return true; |
| 322 | } |
| 323 | |
| 324 | // Fallback paste detection: some terminals send large pastes as rapid chunks |
| 325 | // instead of using bracketed paste mode. We detect this by timing between inputs. |
| 326 | // Only trigger for actually large chunks to avoid interfering with normal typing |
| 327 | if (input.length > RAPID_INPUT_THRESHOLD) { |
| 328 | this._rapidInputStartPos = this._cursor; |
| 329 | |
| 330 | // Accumulate chunks without inserting to avoid visual flicker |
| 331 | this._rapidInputBuffer = input; |
| 332 | this._lastInputTime = now; |
| 333 | |
| 334 | if (this._rapidInputTimer) { |
| 335 | clearTimeout(this._rapidInputTimer); |
| 336 | } |
| 337 | |
| 338 | // 200ms pause indicates end of paste |
| 339 | this._rapidInputTimer = setTimeout(() => { |
| 340 | this.finalizeRapidInput(); |
| 341 | }, 200); |
| 342 | |
| 343 | return true; // Consume input without inserting until finalized |
| 344 | } |
| 345 | |
| 346 | this._lastInputTime = now; |
| 347 | return false; |
| 348 | } |
| 349 | |
| 350 | // Called after rapid input timer expires to collapse or insert buffered content |
| 351 | private finalizeRapidInput(): void { |
| 352 | if (this._rapidInputBuffer.length > COLLAPSE_SIZE) { |
| 353 | const placeholder = this.createPlaceholder(this._rapidInputBuffer); |
| 354 | this._pasteMap.set(placeholder, this._rapidInputBuffer); |
| 355 | |
| 356 | this._text = |
| 357 | this._text.slice(0, this._rapidInputStartPos) + |
| 358 | placeholder + |
| 359 | this._text.slice(this._rapidInputStartPos); |
| 360 | this._cursor = this._rapidInputStartPos + placeholder.length; |
| 361 | |
| 362 | if (this._onStateChange) { |
| 363 | this._onStateChange(); |
| 364 | } |
| 365 | } else { |
| 366 | this.insertText(this._rapidInputBuffer); |
| 367 | |
| 368 | if (this._onStateChange) { |
| 369 | this._onStateChange(); |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | this._rapidInputBuffer = ""; |
| 374 | this._rapidInputStartPos = 0; |
| 375 | this._rapidInputTimer = null; |
| 376 | } |
| 377 | |
| 378 | private handleOptionKey(sequence: string): boolean { |
| 379 | // Option + backspace (usually \u001b\u0008 or \u001b\u007f) |
| 380 | if (sequence === "\u0008" || sequence === "\u007f") { |
| 381 | this.deleteWordBackward(); |
| 382 | return true; |
| 383 | } |
| 384 | return true; // Consume other option sequences |
| 385 | } |
| 386 | |
| 387 | private handleCtrlKey(input: string): boolean { |
| 388 | switch (input) { |
| 389 | case "a": |
| 390 | this.moveToStart(); |
| 391 | return true; |
| 392 | case "e": |
| 393 | this.moveToEnd(); |
| 394 | return true; |
| 395 | case "u": |
| 396 | // Delete from cursor to start of line |
| 397 | this._text = this._text.slice(this._cursor); |
| 398 | this._cursor = 0; |
| 399 | return true; |
| 400 | case "k": |
| 401 | // Delete from cursor to end of line |
| 402 | this._text = this._text.slice(0, this._cursor); |
| 403 | return true; |
| 404 | case "w": |
| 405 | this.deleteWordBackward(); |
| 406 | return true; |
| 407 | case "d": |
| 408 | this.deleteWordForward(); |
| 409 | return true; |
| 410 | default: |
| 411 | return false; |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | private handleMetaKey(input: string, key: Key): boolean { |
| 416 | if (key.backspace || key.delete) { |
| 417 | this.deleteWordBackward(); |
| 418 | return true; |
| 419 | } |
| 420 | if (key.leftArrow) { |
| 421 | this.moveWordLeft(); |
| 422 | return true; |
| 423 | } |
| 424 | if (key.rightArrow) { |
| 425 | this.moveWordRight(); |
| 426 | return true; |
| 427 | } |
| 428 | // Handle option+left/right as characters (on Mac, option+arrow sends character codes) |
| 429 | if (input === "b") { |
| 430 | this.moveWordLeft(); |
| 431 | return true; |
| 432 | } |
| 433 | if (input === "f") { |
| 434 | this.moveWordRight(); |
| 435 | return true; |
| 436 | } |
| 437 | return false; |
| 438 | } |
| 439 | |
| 440 | private handleArrowKeys(key: Key): boolean { |
| 441 | if (key.leftArrow && !key.meta) { |
| 442 | this.moveLeft(); |
| 443 | return true; |
| 444 | } |
| 445 | if (key.rightArrow && !key.meta) { |
| 446 | this.moveRight(); |
| 447 | return true; |
| 448 | } |
| 449 | return false; |
| 450 | } |
| 451 | |
| 452 | private handleDeleteKeys(key: Key): boolean { |
| 453 | // On Mac, backspace key registers as key.delete, so treat it as backward deletion |
| 454 | if ((key.delete || key.backspace) && !key.meta) { |
| 455 | this.deleteBackward(); |
| 456 | return true; |
| 457 | } |
| 458 | return false; |
| 459 | } |
| 460 | |
| 461 | private handleSpecialKeys(input: string, key: Key): boolean { |
| 462 | // Detect option key combinations through escape sequences |
| 463 | const isOptionKey = input.startsWith("\u001b") && input.length > 1; |
| 464 | |
| 465 | // Handle option key combinations (detected through escape sequences) |
| 466 | if (isOptionKey) { |
| 467 | return this.handleOptionKey(input.slice(1)); |
| 468 | } |
| 469 | |
| 470 | // Handle special key combinations based on input character |
| 471 | if (key.ctrl && this.handleCtrlKey(input)) { |
| 472 | return true; |
| 473 | } |
| 474 | |
| 475 | // Handle meta key combinations (cmd on Mac) |
| 476 | if (key.meta && this.handleMetaKey(input, key)) { |
| 477 | return true; |
| 478 | } |
| 479 | |
| 480 | // Handle arrow keys |
| 481 | if (this.handleArrowKeys(key)) { |
| 482 | return true; |
| 483 | } |
| 484 | |
| 485 | // Handle backspace/delete |
| 486 | if (this.handleDeleteKeys(key)) { |
| 487 | return true; |
| 488 | } |
| 489 | |
| 490 | return false; |
| 491 | } |
| 492 | |
| 493 | private handleTextInput(input: string): boolean { |
| 494 | // Direct paste detection: single large input - but delay insertion to catch split pastes |
| 495 | if (input.length > COLLAPSE_SIZE && this._rapidInputBuffer.length === 0) { |
| 496 | // Start rapid input mode immediately to delay placeholder creation |
| 497 | this._rapidInputStartPos = this._cursor; |
| 498 | this._rapidInputBuffer = input; |
| 499 | this._lastInputTime = Date.now(); |
| 500 | |
| 501 | if (this._rapidInputTimer) { |
| 502 | clearTimeout(this._rapidInputTimer); |
| 503 | } |
| 504 | |
| 505 | // Wait 250ms to see if more content comes (split paste) |
| 506 | this._rapidInputTimer = setTimeout(() => { |
| 507 | this.finalizeRapidInput(); |
| 508 | }, 250); |
| 509 | |
| 510 | return true; |
| 511 | } |
| 512 | |
| 513 | // Fallback: detect chunked paste operations |
| 514 | // Don't trigger rapid input detection for small inputs (e.g. single characters like "/" or "@") |
| 515 | if (input.length > 50 && this.handleRapidInput(input)) { |
| 516 | return true; |
| 517 | } |
| 518 | |
| 519 | this.insertText(input); |
| 520 | return true; |
| 521 | } |
| 522 | |
| 523 | handleInput(input: string, key: Key): boolean { |
| 524 | // Handle bracketed paste sequences first |
| 525 | if (this.handleBracketedPaste(input)) { |
| 526 | return true; |
| 527 | } |
| 528 | |
| 529 | // If we're in paste mode, accumulate the pasted content but DON'T insert it yet |
| 530 | if (this._inPasteMode) { |
| 531 | this._pasteBuffer += input; |
| 532 | // Don't insert text during paste mode - wait until paste ends |
| 533 | return true; |
| 534 | } |
| 535 | |
| 536 | // Handle special keys (option, ctrl, meta, arrows, delete) |
| 537 | if (this.handleSpecialKeys(input, key)) { |
| 538 | return true; |
| 539 | } |
| 540 | |
| 541 | // Handle regular text input |
| 542 | const isOptionKey = input.startsWith("\u001b") && input.length > 1; |
| 543 | if (input && input.length >= 1 && !key.ctrl && !key.meta && !isOptionKey) { |
| 544 | return this.handleTextInput(input); |
| 545 | } |
| 546 | |
| 547 | return false; |
| 548 | } |
| 549 | |
| 550 | // Helper method to render text with cursor |
| 551 | renderWithCursor(placeholder?: string): { |
| 552 | text: string; |
| 553 | cursorPosition: number; |
| 554 | } { |
| 555 | if (this._text.length === 0 && placeholder) { |
| 556 | return { text: placeholder, cursorPosition: 0 }; |
| 557 | } |
| 558 | |
| 559 | return { |
| 560 | text: this._text, |
| 561 | cursorPosition: this._cursor, |
| 562 | }; |
| 563 | } |
| 564 | } |