Elffuss BraidHub

kikocis/continue public

b7bed744edb6 · 15.2 KiBRawPermalink
1import { Key } from "ink";
2
3export const COLLAPSE_SIZE = 800; // Characters threshold for collapsing pasted content
4export const RAPID_INPUT_THRESHOLD = 200; // Minimum characters to trigger rapid input detection
5export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image
6export const MAX_IMAGE_COUNT = 20; // Maximum number of images
7export const MAX_TOTAL_IMAGE_MEMORY = 50 * 1024 * 1024; // 50MB total image memory
8
9export 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 if (
327 input.length > RAPID_INPUT_THRESHOLD ||
328 (input.length >= 50 && this._rapidInputBuffer.length === 0)
329 ) {
330 this._rapidInputStartPos = this._cursor;
331
332 // Accumulate chunks without inserting to avoid visual flicker
333 this._rapidInputBuffer = input;
334 this._lastInputTime = now;
335
336 if (this._rapidInputTimer) {
337 clearTimeout(this._rapidInputTimer);
338 }
339
340 // 200ms pause indicates end of paste
341 this._rapidInputTimer = setTimeout(() => {
342 this.finalizeRapidInput();
343 }, 200);
344
345 return true; // Consume input without inserting until finalized
346 }
347
348 this._lastInputTime = now;
349 return false;
350 }
351
352 // Called after rapid input timer expires to collapse or insert buffered content
353 private finalizeRapidInput(): void {
354 if (this._rapidInputBuffer.length > COLLAPSE_SIZE) {
355 const placeholder = this.createPlaceholder(this._rapidInputBuffer);
356 this._pasteMap.set(placeholder, this._rapidInputBuffer);
357
358 this._text =
359 this._text.slice(0, this._rapidInputStartPos) +
360 placeholder +
361 this._text.slice(this._rapidInputStartPos);
362 this._cursor = this._rapidInputStartPos + placeholder.length;
363
364 if (this._onStateChange) {
365 this._onStateChange();
366 }
367 } else {
368 this.insertText(this._rapidInputBuffer);
369
370 if (this._onStateChange) {
371 this._onStateChange();
372 }
373 }
374
375 this._rapidInputBuffer = "";
376 this._rapidInputStartPos = 0;
377 this._rapidInputTimer = null;
378 }
379
380 private handleOptionKey(sequence: string): boolean {
381 // Option + backspace (usually \u001b\u0008 or \u001b\u007f)
382 if (sequence === "\u0008" || sequence === "\u007f") {
383 this.deleteWordBackward();
384 return true;
385 }
386 return true; // Consume other option sequences
387 }
388
389 private handleCtrlKey(input: string): boolean {
390 switch (input) {
391 case "a":
392 this.moveToStart();
393 return true;
394 case "e":
395 this.moveToEnd();
396 return true;
397 case "u":
398 // Delete from cursor to start of line
399 this._text = this._text.slice(this._cursor);
400 this._cursor = 0;
401 return true;
402 case "k":
403 // Delete from cursor to end of line
404 this._text = this._text.slice(0, this._cursor);
405 return true;
406 case "w":
407 this.deleteWordBackward();
408 return true;
409 case "d":
410 this.deleteWordForward();
411 return true;
412 default:
413 return false;
414 }
415 }
416
417 private handleMetaKey(input: string, key: Key): boolean {
418 if (key.backspace || key.delete) {
419 this.deleteWordBackward();
420 return true;
421 }
422 if (key.leftArrow) {
423 this.moveWordLeft();
424 return true;
425 }
426 if (key.rightArrow) {
427 this.moveWordRight();
428 return true;
429 }
430 // Handle option+left/right as characters (on Mac, option+arrow sends character codes)
431 if (input === "b") {
432 this.moveWordLeft();
433 return true;
434 }
435 if (input === "f") {
436 this.moveWordRight();
437 return true;
438 }
439 return false;
440 }
441
442 private handleArrowKeys(key: Key): boolean {
443 if (key.leftArrow && !key.meta) {
444 this.moveLeft();
445 return true;
446 }
447 if (key.rightArrow && !key.meta) {
448 this.moveRight();
449 return true;
450 }
451 return false;
452 }
453
454 private handleDeleteKeys(key: Key): boolean {
455 // On Mac, backspace key registers as key.delete, so treat it as backward deletion
456 if ((key.delete || key.backspace) && !key.meta) {
457 this.deleteBackward();
458 return true;
459 }
460 return false;
461 }
462
463 handleInput(input: string, key: Key): boolean {
464 // Handle bracketed paste sequences first
465 if (this.handleBracketedPaste(input)) {
466 return true;
467 }
468
469 // If we're in paste mode, accumulate the pasted content but DON'T insert it yet
470 if (this._inPasteMode) {
471 this._pasteBuffer += input;
472 // Don't insert text during paste mode - wait until paste ends
473 return true;
474 }
475
476 // Detect option key combinations through escape sequences
477 const isOptionKey = input.startsWith("\u001b") && input.length > 1;
478
479 // Handle option key combinations (detected through escape sequences)
480 if (isOptionKey) {
481 return this.handleOptionKey(input.slice(1));
482 }
483
484 // Handle special key combinations based on input character
485 if (key.ctrl) {
486 const handled = this.handleCtrlKey(input);
487 if (handled) return true;
488 }
489
490 // Handle meta key combinations (cmd on Mac)
491 if (key.meta) {
492 const handled = this.handleMetaKey(input, key);
493 if (handled) return true;
494 }
495
496 // Handle arrow keys
497 if (this.handleArrowKeys(key)) {
498 return true;
499 }
500
501 // Handle backspace/delete
502 if (this.handleDeleteKeys(key)) {
503 return true;
504 }
505
506 if (input && input.length >= 1 && !key.ctrl && !key.meta && !isOptionKey) {
507 // Direct paste detection: single large input - but delay insertion to catch split pastes
508 if (input.length > COLLAPSE_SIZE && this._rapidInputBuffer.length === 0) {
509 // Start rapid input mode immediately to delay placeholder creation
510 this._rapidInputStartPos = this._cursor;
511 this._rapidInputBuffer = input;
512 this._lastInputTime = Date.now();
513
514 if (this._rapidInputTimer) {
515 clearTimeout(this._rapidInputTimer);
516 }
517
518 // Wait 250ms to see if more content comes (split paste)
519 this._rapidInputTimer = setTimeout(() => {
520 this.finalizeRapidInput();
521 }, 250);
522
523 return true;
524 }
525
526 // Fallback: detect chunked paste operations
527 if (this.handleRapidInput(input)) {
528 return true;
529 }
530
531 this.insertText(input);
532 return true;
533 }
534
535 return false;
536 }
537
538 // Helper method to render text with cursor
539 renderWithCursor(placeholder?: string): {
540 text: string;
541 cursorPosition: number;
542 } {
543 if (this._text.length === 0 && placeholder) {
544 return { text: placeholder, cursorPosition: 0 };
545 }
546
547 return {
548 text: this._text,
549 cursorPosition: this._cursor,
550 };
551 }
552}