-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathinput-handler.ts
More file actions
1149 lines (1009 loc) · 34.1 KB
/
input-handler.ts
File metadata and controls
1149 lines (1009 loc) · 34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* InputHandler - Converts browser keyboard events to terminal input
*
* Handles:
* - Keyboard event listening on a container element
* - Mapping KeyboardEvent.code to USB HID Key codes
* - Extracting modifier keys (Ctrl, Alt, Shift, Meta)
* - Encoding keys using Ghostty's KeyEncoder
* - Emitting data for Terminal to send to PTY
*
* Limitations:
* - Does not handle IME/composition events (CJK input) - to be added later
* - Captures all keyboard input (preventDefault on everything)
*/
import type { Ghostty } from './ghostty';
import type { KeyEncoder } from './ghostty';
import type { IKeyEvent } from './interfaces';
import { Key, KeyAction, KeyEncoderOption, Mods } from './types';
/**
* Map KeyboardEvent.code values to USB HID Key enum values
* Based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code
*/
const KEY_MAP: Record<string, Key> = {
// Letters
KeyA: Key.A,
KeyB: Key.B,
KeyC: Key.C,
KeyD: Key.D,
KeyE: Key.E,
KeyF: Key.F,
KeyG: Key.G,
KeyH: Key.H,
KeyI: Key.I,
KeyJ: Key.J,
KeyK: Key.K,
KeyL: Key.L,
KeyM: Key.M,
KeyN: Key.N,
KeyO: Key.O,
KeyP: Key.P,
KeyQ: Key.Q,
KeyR: Key.R,
KeyS: Key.S,
KeyT: Key.T,
KeyU: Key.U,
KeyV: Key.V,
KeyW: Key.W,
KeyX: Key.X,
KeyY: Key.Y,
KeyZ: Key.Z,
// Numbers
Digit1: Key.ONE,
Digit2: Key.TWO,
Digit3: Key.THREE,
Digit4: Key.FOUR,
Digit5: Key.FIVE,
Digit6: Key.SIX,
Digit7: Key.SEVEN,
Digit8: Key.EIGHT,
Digit9: Key.NINE,
Digit0: Key.ZERO,
// Special keys
Enter: Key.ENTER,
Escape: Key.ESCAPE,
Backspace: Key.BACKSPACE,
Tab: Key.TAB,
Space: Key.SPACE,
// Punctuation
Minus: Key.MINUS,
Equal: Key.EQUAL,
BracketLeft: Key.BRACKET_LEFT,
BracketRight: Key.BRACKET_RIGHT,
Backslash: Key.BACKSLASH,
Semicolon: Key.SEMICOLON,
Quote: Key.QUOTE,
Backquote: Key.GRAVE,
Comma: Key.COMMA,
Period: Key.PERIOD,
Slash: Key.SLASH,
// Function keys
CapsLock: Key.CAPS_LOCK,
F1: Key.F1,
F2: Key.F2,
F3: Key.F3,
F4: Key.F4,
F5: Key.F5,
F6: Key.F6,
F7: Key.F7,
F8: Key.F8,
F9: Key.F9,
F10: Key.F10,
F11: Key.F11,
F12: Key.F12,
// Special function keys
PrintScreen: Key.PRINT_SCREEN,
ScrollLock: Key.SCROLL_LOCK,
Pause: Key.PAUSE,
Insert: Key.INSERT,
Home: Key.HOME,
PageUp: Key.PAGE_UP,
Delete: Key.DELETE,
End: Key.END,
PageDown: Key.PAGE_DOWN,
// Arrow keys
ArrowRight: Key.RIGHT,
ArrowLeft: Key.LEFT,
ArrowDown: Key.DOWN,
ArrowUp: Key.UP,
// Keypad
NumLock: Key.NUM_LOCK,
NumpadDivide: Key.KP_DIVIDE,
NumpadMultiply: Key.KP_MULTIPLY,
NumpadSubtract: Key.KP_MINUS,
NumpadAdd: Key.KP_PLUS,
NumpadEnter: Key.KP_ENTER,
Numpad1: Key.KP_1,
Numpad2: Key.KP_2,
Numpad3: Key.KP_3,
Numpad4: Key.KP_4,
Numpad5: Key.KP_5,
Numpad6: Key.KP_6,
Numpad7: Key.KP_7,
Numpad8: Key.KP_8,
Numpad9: Key.KP_9,
Numpad0: Key.KP_0,
NumpadDecimal: Key.KP_PERIOD,
// International
IntlBackslash: Key.INTL_BACKSLASH,
ContextMenu: Key.CONTEXT_MENU,
// Additional function keys
F13: Key.F13,
F14: Key.F14,
F15: Key.F15,
F16: Key.F16,
F17: Key.F17,
F18: Key.F18,
F19: Key.F19,
F20: Key.F20,
F21: Key.F21,
F22: Key.F22,
F23: Key.F23,
F24: Key.F24,
};
/**
* InputHandler class
* Attaches keyboard event listeners to a container and converts
* keyboard events to terminal input data
*/
/**
* Mouse tracking configuration
*/
export interface MouseTrackingConfig {
/** Check if any mouse tracking mode is enabled */
hasMouseTracking: () => boolean;
/** Check if SGR extended mouse mode is enabled (mode 1006) */
hasSgrMouseMode: () => boolean;
/** Get cell dimensions for pixel to cell conversion */
getCellDimensions: () => { width: number; height: number };
/** Get canvas/container offset for accurate position calculation */
getCanvasOffset: () => { left: number; top: number };
}
export class InputHandler {
private encoder: KeyEncoder;
private container: HTMLElement;
private inputElement?: HTMLElement;
private onDataCallback: (data: string) => void;
private onBellCallback: () => void;
private onKeyCallback?: (keyEvent: IKeyEvent) => void;
private customKeyEventHandler?: (event: KeyboardEvent) => boolean;
private getModeCallback?: (mode: number) => boolean;
private onCopyCallback?: () => boolean;
private mouseConfig?: MouseTrackingConfig;
private keydownListener: ((e: KeyboardEvent) => void) | null = null;
private keypressListener: ((e: KeyboardEvent) => void) | null = null;
private pasteListener: ((e: ClipboardEvent) => void) | null = null;
private beforeInputListener: ((e: InputEvent) => void) | null = null;
private compositionStartListener: ((e: CompositionEvent) => void) | null = null;
private compositionUpdateListener: ((e: CompositionEvent) => void) | null = null;
private compositionEndListener: ((e: CompositionEvent) => void) | null = null;
private mousedownListener: ((e: MouseEvent) => void) | null = null;
private mouseupListener: ((e: MouseEvent) => void) | null = null;
private mousemoveListener: ((e: MouseEvent) => void) | null = null;
private wheelListener: ((e: WheelEvent) => void) | null = null;
private isComposing = false;
private compositionJustEnded = false; // Block keydown briefly after composition ends
private pendingKeyAfterComposition: string | null = null; // Key to output after composition
private isDisposed = false;
private mouseButtonsPressed = 0; // Track which buttons are pressed for motion reporting
private lastKeyDownData: string | null = null;
private lastKeyDownTime = 0;
private lastPasteData: string | null = null;
private lastPasteTime = 0;
private lastPasteSource: 'paste' | 'beforeinput' | null = null;
private lastCompositionData: string | null = null;
private lastCompositionTime = 0;
private lastBeforeInputData: string | null = null;
private lastBeforeInputTime = 0;
private static readonly BEFORE_INPUT_IGNORE_MS = 100;
/**
* Create a new InputHandler
* @param ghostty - Ghostty instance (for creating KeyEncoder)
* @param container - DOM element to attach listeners to
* @param onData - Callback for terminal data (escape sequences to send to PTY)
* @param onBell - Callback for bell/beep event
* @param onKey - Optional callback for raw key events
* @param customKeyEventHandler - Optional custom key event handler
* @param getMode - Optional callback to query terminal mode state (for application cursor mode)
* @param onCopy - Optional callback to handle copy (Cmd+C/Ctrl+C with selection)
* @param inputElement - Optional input element for beforeinput events
* @param mouseConfig - Optional mouse tracking configuration
*/
constructor(
ghostty: Ghostty,
container: HTMLElement,
onData: (data: string) => void,
onBell: () => void,
onKey?: (keyEvent: IKeyEvent) => void,
customKeyEventHandler?: (event: KeyboardEvent) => boolean,
getMode?: (mode: number) => boolean,
onCopy?: () => boolean,
inputElement?: HTMLElement,
mouseConfig?: MouseTrackingConfig
) {
this.encoder = ghostty.createKeyEncoder();
this.container = container;
this.inputElement = inputElement;
this.onDataCallback = onData;
this.onBellCallback = onBell;
this.onKeyCallback = onKey;
this.customKeyEventHandler = customKeyEventHandler;
this.getModeCallback = getMode;
this.onCopyCallback = onCopy;
this.mouseConfig = mouseConfig;
// Attach event listeners
this.attach();
}
/**
* Set custom key event handler (for runtime updates)
*/
setCustomKeyEventHandler(handler: (event: KeyboardEvent) => boolean): void {
this.customKeyEventHandler = handler;
}
/**
* Attach keyboard event listeners to container
*/
private attach(): void {
// Make container focusable so it can receive keyboard events (browser only)
if (
typeof this.container.hasAttribute === 'function' &&
typeof this.container.setAttribute === 'function'
) {
if (!this.container.hasAttribute('tabindex')) {
this.container.setAttribute('tabindex', '0');
}
// Add visual focus indication (only if style exists - for browser environments)
if (this.container.style) {
this.container.style.outline = 'none'; // Remove default outline
}
}
this.keydownListener = this.handleKeyDown.bind(this);
this.container.addEventListener('keydown', this.keydownListener);
this.pasteListener = this.handlePaste.bind(this);
this.container.addEventListener('paste', this.pasteListener);
if (this.inputElement && this.inputElement !== this.container) {
this.inputElement.addEventListener('paste', this.pasteListener);
}
if (this.inputElement) {
this.beforeInputListener = this.handleBeforeInput.bind(this);
this.inputElement.addEventListener('beforeinput', this.beforeInputListener);
}
// Attach composition events to inputElement (textarea) if available.
// IME composition events fire on the focused element, and when using a hidden
// textarea for input (as ghostty-web does), the textarea receives focus,
// not the container. This fixes Korean/Chinese/Japanese IME input.
const compositionTarget = this.inputElement || this.container;
this.compositionStartListener = this.handleCompositionStart.bind(this);
compositionTarget.addEventListener('compositionstart', this.compositionStartListener);
this.compositionUpdateListener = this.handleCompositionUpdate.bind(this);
compositionTarget.addEventListener('compositionupdate', this.compositionUpdateListener);
this.compositionEndListener = this.handleCompositionEnd.bind(this);
compositionTarget.addEventListener('compositionend', this.compositionEndListener);
// Mouse event listeners (for terminal mouse tracking)
this.mousedownListener = this.handleMouseDown.bind(this);
this.container.addEventListener('mousedown', this.mousedownListener);
this.mouseupListener = this.handleMouseUp.bind(this);
this.container.addEventListener('mouseup', this.mouseupListener);
this.mousemoveListener = this.handleMouseMove.bind(this);
this.container.addEventListener('mousemove', this.mousemoveListener);
this.wheelListener = this.handleWheel.bind(this);
this.container.addEventListener('wheel', this.wheelListener, { passive: false });
}
/**
* Map KeyboardEvent.code to USB HID Key enum value
* @param code - KeyboardEvent.code value
* @returns Key enum value or null if unmapped
*/
private mapKeyCode(code: string): Key | null {
return KEY_MAP[code] ?? null;
}
/**
* Extract modifier flags from KeyboardEvent
* @param event - KeyboardEvent
* @returns Mods flags
*/
private extractModifiers(event: KeyboardEvent): Mods {
let mods = Mods.NONE;
if (event.shiftKey) mods |= Mods.SHIFT;
if (event.ctrlKey) mods |= Mods.CTRL;
if (event.altKey) mods |= Mods.ALT;
if (event.metaKey) mods |= Mods.SUPER;
// Note: CapsLock and NumLock are not in KeyboardEvent modifiers
// They would need to be tracked separately if needed
// For now, we don't set CAPSLOCK or NUMLOCK flags
return mods;
}
/**
* Check if this is a printable character with no special modifiers
* @param event - KeyboardEvent
* @returns true if printable character
*/
private isPrintableCharacter(event: KeyboardEvent): boolean {
// If Ctrl, Alt, or Meta (Cmd on Mac) is pressed, it's not a simple printable character
// Exception: AltGr (Ctrl+Alt on some keyboards) can produce printable characters
if (event.ctrlKey && !event.altKey) return false;
if (event.altKey && !event.ctrlKey) return false;
if (event.metaKey) return false; // Cmd key on Mac
// If key produces a single printable character
return event.key.length === 1;
}
/**
* Handle keydown event
* @param event - KeyboardEvent
*/
private handleKeyDown(event: KeyboardEvent): void {
if (this.isDisposed) return;
// Ignore keydown events during composition
// Note: Some browsers send keyCode 229 for all keys during composition
if (event.isComposing || event.keyCode === 229) {
return;
}
// If we're still in composition (our flag) but browser says composition ended,
// this is the key that ended the composition (space, period, etc.).
// Queue it to be processed after compositionend to maintain correct order.
if (this.isComposing) {
// Store the key to be processed after composition ends
this.pendingKeyAfterComposition = event.key;
event.preventDefault();
return;
}
// Block the key that triggered composition end if we just processed a pending key
if (this.compositionJustEnded) {
this.compositionJustEnded = false;
return;
}
// Emit onKey event first (before any processing)
if (this.onKeyCallback) {
this.onKeyCallback({ key: event.key, domEvent: event });
}
// Check custom key event handler
if (this.customKeyEventHandler) {
const handled = this.customKeyEventHandler(event);
if (handled) {
// Custom handler consumed the event
event.preventDefault();
return;
}
}
// Allow Ctrl+V and Cmd+V to trigger paste event (don't preventDefault)
if ((event.ctrlKey || event.metaKey) && event.code === 'KeyV') {
// Let the browser's native paste event fire
return;
}
// Handle Cmd+C for copy (on Mac, Cmd+C should copy, not send interrupt)
// Note: Ctrl+C on all platforms sends interrupt signal (0x03)
if (event.metaKey && event.code === 'KeyC') {
// Try to copy selection via callback
// If there's a selection and copy succeeds, prevent default
// If no selection, let it fall through (browser may have other text selected)
if (this.onCopyCallback && this.onCopyCallback()) {
event.preventDefault();
}
return;
}
// For printable characters without modifiers, send the character directly
// This handles: a-z, A-Z (with shift), 0-9, punctuation, etc.
if (this.isPrintableCharacter(event)) {
event.preventDefault();
this.onDataCallback(event.key);
this.recordKeyDownData(event.key);
return;
}
// Map the physical key code
const key = this.mapKeyCode(event.code);
if (key === null) {
// Unknown key - ignore it
return;
}
// Extract modifiers
const mods = this.extractModifiers(event);
// Handle simple special keys that produce standard sequences
if (mods === Mods.NONE || mods === Mods.SHIFT) {
let simpleOutput: string | null = null;
switch (key) {
case Key.ENTER:
simpleOutput = '\r'; // Carriage return
break;
case Key.TAB:
if (mods === Mods.SHIFT) {
simpleOutput = '\x1b[Z'; // Backtab
} else {
simpleOutput = '\t'; // Tab
}
break;
case Key.BACKSPACE:
simpleOutput = '\x7F'; // DEL (most terminals use 0x7F for backspace)
break;
case Key.ESCAPE:
simpleOutput = '\x1B'; // ESC
break;
// Arrow keys are handled by the encoder (respects application cursor mode)
// Navigation keys
case Key.HOME:
simpleOutput = '\x1B[H';
break;
case Key.END:
simpleOutput = '\x1B[F';
break;
case Key.INSERT:
simpleOutput = '\x1B[2~';
break;
case Key.DELETE:
simpleOutput = '\x1B[3~';
break;
case Key.PAGE_UP:
simpleOutput = '\x1B[5~';
break;
case Key.PAGE_DOWN:
simpleOutput = '\x1B[6~';
break;
// Function keys
case Key.F1:
simpleOutput = '\x1BOP';
break;
case Key.F2:
simpleOutput = '\x1BOQ';
break;
case Key.F3:
simpleOutput = '\x1BOR';
break;
case Key.F4:
simpleOutput = '\x1BOS';
break;
case Key.F5:
simpleOutput = '\x1B[15~';
break;
case Key.F6:
simpleOutput = '\x1B[17~';
break;
case Key.F7:
simpleOutput = '\x1B[18~';
break;
case Key.F8:
simpleOutput = '\x1B[19~';
break;
case Key.F9:
simpleOutput = '\x1B[20~';
break;
case Key.F10:
simpleOutput = '\x1B[21~';
break;
case Key.F11:
simpleOutput = '\x1B[23~';
break;
case Key.F12:
simpleOutput = '\x1B[24~';
break;
}
if (simpleOutput !== null) {
event.preventDefault();
this.onDataCallback(simpleOutput);
this.recordKeyDownData(simpleOutput);
return;
}
}
// Determine action (we only care about PRESS for now, not RELEASE or REPEAT)
const action = KeyAction.PRESS;
// For non-printable keys or keys with modifiers, encode using Ghostty
try {
// Sync encoder options with terminal mode state
// Mode 1 (DECCKM) controls whether arrow keys send CSI or SS3 sequences
if (this.getModeCallback) {
const appCursorMode = this.getModeCallback(1);
this.encoder.setOption(KeyEncoderOption.CURSOR_KEY_APPLICATION, appCursorMode);
}
// For letter/number keys, even with modifiers, pass the base character
// This helps the encoder produce correct control sequences (e.g., Ctrl+A = 0x01)
// For special keys (Enter, Arrow keys, etc.), don't pass utf8
const utf8 =
event.key.length === 1 && event.key.charCodeAt(0) < 128
? event.key.toLowerCase() // Use lowercase for consistency
: undefined;
const encoded = this.encoder.encode({
action,
key,
mods,
utf8,
});
// Convert Uint8Array to string
const decoder = new TextDecoder();
const data = decoder.decode(encoded);
// Prevent default browser behavior
event.preventDefault();
event.stopPropagation();
// Emit the data
if (data.length > 0) {
this.onDataCallback(data);
this.recordKeyDownData(data);
}
} catch (error) {
// Encoding failed - log but don't crash
console.warn('Failed to encode key:', event.code, error);
}
}
/**
* Handle paste event from clipboard
* @param event - ClipboardEvent
*/
private handlePaste(event: ClipboardEvent): void {
if (this.isDisposed) return;
// Prevent default paste behavior
event.preventDefault();
event.stopPropagation();
// Get clipboard data
const clipboardData = event.clipboardData;
if (!clipboardData) {
console.warn('No clipboard data available');
return;
}
// Get text from clipboard
const text = clipboardData.getData('text/plain');
if (!text) {
console.warn('No text in clipboard');
return;
}
if (this.shouldIgnorePasteEvent(text, 'paste')) {
return;
}
this.emitPasteData(text);
this.recordPasteData(text, 'paste');
}
/**
* Handle beforeinput event (mobile/IME input)
* @param event - InputEvent
*/
private handleBeforeInput(event: InputEvent): void {
if (this.isDisposed) return;
if (this.isComposing || event.isComposing) {
return;
}
const inputType = event.inputType;
const data = event.data ?? '';
let output: string | null = null;
switch (inputType) {
case 'insertText':
case 'insertReplacementText':
output = data.length > 0 ? data.replace(/\n/g, '\r') : null;
break;
case 'insertLineBreak':
case 'insertParagraph':
output = '\r';
break;
case 'deleteContentBackward':
output = '\x7F';
break;
case 'deleteContentForward':
output = '\x1B[3~';
break;
case 'insertFromPaste':
if (!data) {
return;
}
if (this.shouldIgnorePasteEvent(data, 'beforeinput')) {
event.preventDefault();
event.stopPropagation();
return;
}
event.preventDefault();
event.stopPropagation();
this.emitPasteData(data);
this.recordPasteData(data, 'beforeinput');
return;
default:
return;
}
if (!output) {
return;
}
if (this.shouldIgnoreBeforeInput(output)) {
event.preventDefault();
event.stopPropagation();
return;
}
if (data && this.shouldIgnoreBeforeInputFromComposition(data)) {
event.preventDefault();
event.stopPropagation();
return;
}
event.preventDefault();
event.stopPropagation();
this.onDataCallback(output);
if (data) {
this.recordBeforeInputData(data);
}
}
/**
* Handle compositionstart event
*/
private handleCompositionStart(_event: CompositionEvent): void {
if (this.isDisposed) return;
this.isComposing = true;
}
/**
* Handle compositionupdate event
*/
private handleCompositionUpdate(_event: CompositionEvent): void {
if (this.isDisposed) return;
// We could track the current composition string here if we wanted to
// display it in a custom way, but for now we rely on the browser's
// input method editor UI.
}
/**
* Handle compositionend event
*/
private handleCompositionEnd(event: CompositionEvent): void {
if (this.isDisposed) return;
this.isComposing = false;
const data = event.data;
if (data && data.length > 0) {
if (this.shouldIgnoreCompositionEnd(data)) {
this.cleanupCompositionTextNodes();
// Still process pending key even if composition data is ignored
this.processPendingKeyAfterComposition();
return;
}
this.onDataCallback(data);
this.recordCompositionData(data);
}
this.cleanupCompositionTextNodes();
// Process the key that ended composition (space, period, etc.)
// This ensures correct order: composed text first, then the terminating key
this.processPendingKeyAfterComposition();
}
/**
* Process the pending key that was queued during composition
*/
private processPendingKeyAfterComposition(): void {
if (this.pendingKeyAfterComposition) {
const key = this.pendingKeyAfterComposition;
this.pendingKeyAfterComposition = null;
// Output the key that ended composition
this.onDataCallback(key);
}
}
/**
* Cleanup text nodes in container after composition
*/
private cleanupCompositionTextNodes(): void {
// Cleanup text nodes in container (fix for duplicate text display)
// When the container is contenteditable, the browser might insert text nodes
// upon composition end. We need to remove them to prevent duplicate display.
if (this.container && this.container.childNodes) {
for (let i = this.container.childNodes.length - 1; i >= 0; i--) {
const node = this.container.childNodes[i];
// Node.TEXT_NODE === 3
if (node.nodeType === 3) {
this.container.removeChild(node);
}
}
}
}
// ==========================================================================
// Mouse Event Handling (for terminal mouse tracking)
// ==========================================================================
/**
* Convert pixel coordinates to terminal cell coordinates
*/
private pixelToCell(event: MouseEvent): { col: number; row: number } | null {
if (!this.mouseConfig) return null;
const dims = this.mouseConfig.getCellDimensions();
const offset = this.mouseConfig.getCanvasOffset();
if (dims.width <= 0 || dims.height <= 0) return null;
const x = event.clientX - offset.left;
const y = event.clientY - offset.top;
// Convert to 1-based cell coordinates (terminal uses 1-based)
const col = Math.floor(x / dims.width) + 1;
const row = Math.floor(y / dims.height) + 1;
// Clamp to valid range (at least 1)
return {
col: Math.max(1, col),
row: Math.max(1, row),
};
}
/**
* Get modifier flags for mouse event
*/
private getMouseModifiers(event: MouseEvent): number {
let mods = 0;
if (event.shiftKey) mods |= 4;
if (event.metaKey) mods |= 8; // Meta (Cmd on Mac)
if (event.ctrlKey) mods |= 16;
return mods;
}
/**
* Encode mouse event as SGR sequence
* SGR format: \x1b[<Btn;Col;RowM (press/motion) or \x1b[<Btn;Col;Rowm (release)
*/
private encodeMouseSGR(
button: number,
col: number,
row: number,
isRelease: boolean,
modifiers: number
): string {
const btn = button + modifiers;
const suffix = isRelease ? 'm' : 'M';
return `\x1b[<${btn};${col};${row}${suffix}`;
}
/**
* Encode mouse event as X10/normal sequence (legacy format)
* Format: \x1b[M<Btn+32><Col+32><Row+32>
*/
private encodeMouseX10(button: number, col: number, row: number, modifiers: number): string {
// X10 format adds 32 to all values and encodes as characters
// Button encoding: 0=left, 1=middle, 2=right, 3=release
const btn = button + modifiers + 32;
const colChar = String.fromCharCode(Math.min(col + 32, 255));
const rowChar = String.fromCharCode(Math.min(row + 32, 255));
return `\x1b[M${String.fromCharCode(btn)}${colChar}${rowChar}`;
}
/**
* Send mouse event to terminal
*/
private sendMouseEvent(
button: number,
col: number,
row: number,
isRelease: boolean,
event: MouseEvent
): void {
const modifiers = this.getMouseModifiers(event);
// Check if SGR extended mode is enabled (mode 1006)
const useSGR = this.mouseConfig?.hasSgrMouseMode?.() ?? true;
let sequence: string;
if (useSGR) {
sequence = this.encodeMouseSGR(button, col, row, isRelease, modifiers);
} else {
// X10/normal mode doesn't support release events directly
// Button 3 means release in X10 mode
const x10Button = isRelease ? 3 : button;
sequence = this.encodeMouseX10(x10Button, col, row, modifiers);
}
this.onDataCallback(sequence);
}
/**
* Handle mousedown event
*/
private handleMouseDown(event: MouseEvent): void {
if (this.isDisposed) return;
if (!this.mouseConfig?.hasMouseTracking()) return;
const cell = this.pixelToCell(event);
if (!cell) return;
// Map browser button to terminal button
// event.button: 0=left, 1=middle, 2=right
// Terminal: 0=left, 1=middle, 2=right
const button = event.button;
// Track pressed buttons for motion events
this.mouseButtonsPressed |= 1 << button;
this.sendMouseEvent(button, cell.col, cell.row, false, event);
// Don't prevent default - let SelectionManager handle selection
// Only prevent if we actually handled the event
// event.preventDefault();
}
/**
* Handle mouseup event
*/
private handleMouseUp(event: MouseEvent): void {
if (this.isDisposed) return;
if (!this.mouseConfig?.hasMouseTracking()) return;
const cell = this.pixelToCell(event);
if (!cell) return;
const button = event.button;
// Clear pressed button
this.mouseButtonsPressed &= ~(1 << button);
this.sendMouseEvent(button, cell.col, cell.row, true, event);
}
/**
* Handle mousemove event
*/
private handleMouseMove(event: MouseEvent): void {
if (this.isDisposed) return;
if (!this.mouseConfig?.hasMouseTracking()) return;
// Check if button motion mode or any-event tracking is enabled
// Mode 1002 = button motion, Mode 1003 = any motion
const hasButtonMotion = this.getModeCallback?.(1002) ?? false;
const hasAnyMotion = this.getModeCallback?.(1003) ?? false;
if (!hasButtonMotion && !hasAnyMotion) return;
// In button motion mode, only report if a button is pressed
if (hasButtonMotion && !hasAnyMotion && this.mouseButtonsPressed === 0) return;
const cell = this.pixelToCell(event);
if (!cell) return;
// Determine which button to report (or 32 for motion with no button)
let button = 32; // Motion flag
if (this.mouseButtonsPressed & 1)
button += 0; // Left
else if (this.mouseButtonsPressed & 2)
button += 1; // Middle
else if (this.mouseButtonsPressed & 4) button += 2; // Right
this.sendMouseEvent(button, cell.col, cell.row, false, event);
}
/**
* Handle wheel event (scroll)
*/
private handleWheel(event: WheelEvent): void {
if (this.isDisposed) return;
if (!this.mouseConfig?.hasMouseTracking()) return;
const cell = this.pixelToCell(event);
if (!cell) return;
// Wheel events: button 64 = scroll up, button 65 = scroll down
const button = event.deltaY < 0 ? 64 : 65;
this.sendMouseEvent(button, cell.col, cell.row, false, event);
// Prevent default scrolling when mouse tracking is active
event.preventDefault();
}
/**
* Emit paste data with bracketed paste support
*/
private emitPasteData(text: string): void {
const hasBracketedPaste = this.getModeCallback?.(2004) ?? false;
if (hasBracketedPaste) {
this.onDataCallback('\x1b[200~' + text + '\x1b[201~');
} else {
this.onDataCallback(text);
}
}
/**
* Record keydown data for beforeinput de-duplication
*/
private recordKeyDownData(data: string): void {
this.lastKeyDownData = data;
this.lastKeyDownTime = this.getNow();
}
/**
* Record paste data for beforeinput de-duplication
*/
private recordPasteData(data: string, source: 'paste' | 'beforeinput'): void {
this.lastPasteData = data;
this.lastPasteTime = this.getNow();
this.lastPasteSource = source;
}
/**
* Check if beforeinput should be ignored due to a recent keydown
*/
private shouldIgnoreBeforeInput(data: string): boolean {
if (!this.lastKeyDownData) {
return false;
}
const now = this.getNow();
const isDuplicate =
now - this.lastKeyDownTime < InputHandler.BEFORE_INPUT_IGNORE_MS &&
this.lastKeyDownData === data;
this.lastKeyDownData = null;
return isDuplicate;
}
/**
* Check if beforeinput text should be ignored due to a recent composition end
*/
private shouldIgnoreBeforeInputFromComposition(data: string): boolean {
if (!this.lastCompositionData) {
return false;