Elffuss BraidHub

kikocis/continue public

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