-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathterminal.ts
More file actions
1903 lines (1639 loc) · 62.4 KB
/
terminal.ts
File metadata and controls
1903 lines (1639 loc) · 62.4 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
/**
* Terminal - Main terminal emulator class
*
* Provides an xterm.js-compatible API wrapping Ghostty's WASM terminal emulator.
*
* Usage:
* ```typescript
* import { init, Terminal } from 'ghostty-web';
*
* await init();
* const term = new Terminal();
* term.open(document.getElementById('container'));
* term.write('Hello, World!\n');
* term.onData(data => console.log('User typed:', data));
* ```
*/
import { BufferNamespace } from './buffer';
import { EventEmitter } from './event-emitter';
import type { Ghostty, GhosttyCell, GhosttyTerminal, GhosttyTerminalConfig } from './ghostty';
import { getGhostty } from './index';
import { InputHandler, type MouseTrackingConfig } from './input-handler';
import type {
IBufferNamespace,
IBufferRange,
IDisposable,
IEvent,
IKeyEvent,
ITerminalAddon,
ITerminalCore,
ITerminalOptions,
IUnicodeVersionProvider,
} from './interfaces';
import { LinkDetector } from './link-detector';
import { OSC8LinkProvider } from './providers/osc8-link-provider';
import { UrlRegexProvider } from './providers/url-regex-provider';
import { CanvasRenderer } from './renderer';
import { SelectionManager } from './selection-manager';
import type { ILink, ILinkProvider } from './types';
// ============================================================================
// Terminal Class
// ============================================================================
export class Terminal implements ITerminalCore {
// Public properties (xterm.js compatibility)
public cols: number;
public rows: number;
public element?: HTMLElement;
public textarea?: HTMLTextAreaElement;
// Buffer API (xterm.js compatibility)
public readonly buffer: IBufferNamespace;
// Unicode API (xterm.js compatibility)
public readonly unicode: IUnicodeVersionProvider = {
get activeVersion(): string {
return '15.1'; // Ghostty supports Unicode 15.1
},
};
// Options (public for xterm.js compatibility)
public readonly options!: Required<ITerminalOptions>;
// Components (created on open())
private ghostty?: Ghostty;
public wasmTerm?: GhosttyTerminal; // Made public for link providers
public renderer?: CanvasRenderer; // Made public for FitAddon
private inputHandler?: InputHandler;
private selectionManager?: SelectionManager;
private canvas?: HTMLCanvasElement;
private compositionPreview?: HTMLDivElement;
// Link detection system
private linkDetector?: LinkDetector;
private currentHoveredLink?: ILink;
private mouseMoveThrottleTimeout?: number;
private pendingMouseMove?: MouseEvent;
// Event emitters
private dataEmitter = new EventEmitter<string>();
private resizeEmitter = new EventEmitter<{ cols: number; rows: number }>();
private bellEmitter = new EventEmitter<void>();
private selectionChangeEmitter = new EventEmitter<void>();
private keyEmitter = new EventEmitter<IKeyEvent>();
private titleChangeEmitter = new EventEmitter<string>();
private scrollEmitter = new EventEmitter<number>();
private renderEmitter = new EventEmitter<{ start: number; end: number }>();
private cursorMoveEmitter = new EventEmitter<void>();
// Public event accessors (xterm.js compatibility)
public readonly onData: IEvent<string> = this.dataEmitter.event;
public readonly onResize: IEvent<{ cols: number; rows: number }> = this.resizeEmitter.event;
public readonly onBell: IEvent<void> = this.bellEmitter.event;
public readonly onSelectionChange: IEvent<void> = this.selectionChangeEmitter.event;
public readonly onKey: IEvent<IKeyEvent> = this.keyEmitter.event;
public readonly onTitleChange: IEvent<string> = this.titleChangeEmitter.event;
public readonly onScroll: IEvent<number> = this.scrollEmitter.event;
public readonly onRender: IEvent<{ start: number; end: number }> = this.renderEmitter.event;
public readonly onCursorMove: IEvent<void> = this.cursorMoveEmitter.event;
// Lifecycle state
private isOpen = false;
private isDisposed = false;
private animationFrameId?: number;
// Addons
private addons: ITerminalAddon[] = [];
// Phase 1: Custom event handlers
private customKeyEventHandler?: (event: KeyboardEvent) => boolean;
// Phase 1: Title tracking
private currentTitle: string = '';
// Phase 2: Viewport and scrolling state
public viewportY: number = 0; // Top line of viewport in scrollback buffer (0 = at bottom, can be fractional during smooth scroll)
private targetViewportY: number = 0; // Target viewport position for smooth scrolling
private scrollAnimationStartTime?: number;
private scrollAnimationStartY?: number;
private scrollAnimationFrame?: number;
private customWheelEventHandler?: (event: WheelEvent) => boolean;
private lastCursorY: number = 0; // Track cursor position for onCursorMove
// Scrollbar interaction state
private isDraggingScrollbar: boolean = false;
private scrollbarDragStart: number | null = null;
private scrollbarDragStartViewportY: number = 0;
// Scrollbar visibility/auto-hide state
private scrollbarVisible: boolean = false;
private scrollbarOpacity: number = 0;
private scrollbarHideTimeout?: number;
private readonly SCROLLBAR_HIDE_DELAY_MS = 1500; // Hide after 1.5 seconds
private readonly SCROLLBAR_FADE_DURATION_MS = 200; // 200ms fade animation
constructor(options: ITerminalOptions = {}) {
// Use provided Ghostty instance (for test isolation) or get module-level instance
this.ghostty = options.ghostty ?? getGhostty();
// Create base options object with all defaults (excluding ghostty)
const baseOptions = {
cols: options.cols ?? 80,
rows: options.rows ?? 24,
cursorBlink: options.cursorBlink ?? false,
cursorStyle: options.cursorStyle ?? 'block',
theme: options.theme ?? {},
scrollback: options.scrollback ?? 10000,
fontSize: options.fontSize ?? 15,
fontFamily: options.fontFamily ?? 'monospace',
allowTransparency: options.allowTransparency ?? false,
convertEol: options.convertEol ?? false,
disableStdin: options.disableStdin ?? false,
smoothScrollDuration: options.smoothScrollDuration ?? 100, // Default: 100ms smooth scroll
};
// Wrap in Proxy to intercept runtime changes (xterm.js compatibility)
(this.options as any) = new Proxy(baseOptions, {
set: (target: any, prop: string, value: any) => {
const oldValue = target[prop];
target[prop] = value;
// Apply runtime changes if terminal is open
if (this.isOpen) {
this.handleOptionChange(prop, value, oldValue);
}
return true;
},
});
this.cols = this.options.cols;
this.rows = this.options.rows;
// Initialize buffer API
this.buffer = new BufferNamespace(this);
}
// ==========================================================================
// Option Change Handling (for mutable options)
// ==========================================================================
/**
* Handle runtime option changes (called when options are modified after terminal is open)
* This enables xterm.js compatibility where options can be changed at runtime
*/
private handleOptionChange(key: string, newValue: any, oldValue: any): void {
if (newValue === oldValue) return;
switch (key) {
case 'disableStdin':
// Input handler already checks this.options.disableStdin dynamically
// No action needed
break;
case 'cursorBlink':
case 'cursorStyle':
if (this.renderer) {
this.renderer.setCursorStyle(this.options.cursorStyle);
this.renderer.setCursorBlink(this.options.cursorBlink);
}
break;
case 'theme':
if (this.renderer) {
console.warn('ghostty-web: theme changes after open() are not yet fully supported');
}
break;
case 'fontSize':
if (this.renderer) {
this.renderer.setFontSize(this.options.fontSize);
this.handleFontChange();
}
break;
case 'fontFamily':
if (this.renderer) {
this.renderer.setFontFamily(this.options.fontFamily);
this.handleFontChange();
}
break;
case 'cols':
case 'rows':
// Redirect to resize method
this.resize(this.options.cols, this.options.rows);
break;
}
}
/**
* Handle font changes (fontSize or fontFamily)
* Updates canvas size to match new font metrics and forces a full re-render
*/
private handleFontChange(): void {
if (!this.renderer || !this.wasmTerm || !this.canvas) return;
// Clear any active selection since pixel positions have changed
if (this.selectionManager) {
this.selectionManager.clearSelection();
}
// Resize canvas to match new font metrics
this.renderer.resize(this.cols, this.rows);
// Update canvas element dimensions to match renderer
const metrics = this.renderer.getMetrics();
this.canvas.width = metrics.width * this.cols;
this.canvas.height = metrics.height * this.rows;
this.canvas.style.width = `${metrics.width * this.cols}px`;
this.canvas.style.height = `${metrics.height * this.rows}px`;
// Force full re-render with new font
this.renderer.render(this.wasmTerm, true, this.viewportY, this);
}
/**
* Parse a CSS color string to 0xRRGGBB format.
* Returns 0 if the color is undefined or invalid.
*/
private parseColorToHex(color?: string): number {
if (!color) return 0;
// Handle hex colors (#RGB, #RRGGBB)
if (color.startsWith('#')) {
let hex = color.slice(1);
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
const value = Number.parseInt(hex, 16);
return Number.isNaN(value) ? 0 : value;
}
// Handle rgb(r, g, b) format
const match = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
if (match) {
const r = Number.parseInt(match[1], 10);
const g = Number.parseInt(match[2], 10);
const b = Number.parseInt(match[3], 10);
return (r << 16) | (g << 8) | b;
}
return 0;
}
/**
* Convert terminal options to WASM terminal config.
*/
private buildWasmConfig(): GhosttyTerminalConfig | undefined {
const theme = this.options.theme;
const scrollback = this.options.scrollback;
// If no theme and default scrollback, use defaults
if (!theme && scrollback === 10000) {
return undefined;
}
// Build palette array from theme colors
// Order: black, red, green, yellow, blue, magenta, cyan, white,
// brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite
const palette: number[] = [
this.parseColorToHex(theme?.black),
this.parseColorToHex(theme?.red),
this.parseColorToHex(theme?.green),
this.parseColorToHex(theme?.yellow),
this.parseColorToHex(theme?.blue),
this.parseColorToHex(theme?.magenta),
this.parseColorToHex(theme?.cyan),
this.parseColorToHex(theme?.white),
this.parseColorToHex(theme?.brightBlack),
this.parseColorToHex(theme?.brightRed),
this.parseColorToHex(theme?.brightGreen),
this.parseColorToHex(theme?.brightYellow),
this.parseColorToHex(theme?.brightBlue),
this.parseColorToHex(theme?.brightMagenta),
this.parseColorToHex(theme?.brightCyan),
this.parseColorToHex(theme?.brightWhite),
];
return {
scrollbackLimit: scrollback,
fgColor: this.parseColorToHex(theme?.foreground),
bgColor: this.parseColorToHex(theme?.background),
cursorColor: this.parseColorToHex(theme?.cursor),
palette,
};
}
// ==========================================================================
// Lifecycle Methods
// ==========================================================================
/**
* Open terminal in a parent element
*
* Initializes all components and starts rendering.
* Requires a pre-loaded Ghostty instance passed to the constructor.
*/
open(parent: HTMLElement): void {
if (this.isOpen) {
throw new Error('Terminal is already open');
}
if (this.isDisposed) {
throw new Error('Terminal has been disposed');
}
// Store parent element
this.element = parent;
this.isOpen = true;
try {
// Set tabindex="-1" on parent so it's not focusable via click/tab.
// We want all focus to go to the hidden textarea for proper IME handling.
// The textarea will handle keyboard input and composition events.
parent.setAttribute('tabindex', '-1');
// Note: We intentionally do NOT set contenteditable on the parent container.
// Setting contenteditable causes IME (Korean, Chinese, Japanese) input to be
// inserted directly into the container as text nodes, bypassing our textarea.
// Instead, we use the hidden textarea for all keyboard/IME input.
// Add accessibility attributes for screen readers and extensions
parent.setAttribute('role', 'textbox');
parent.setAttribute('aria-label', 'Terminal input');
parent.setAttribute('aria-multiline', 'true');
// Create WASM terminal with current dimensions and config
const config = this.buildWasmConfig();
this.wasmTerm = this.ghostty!.createTerminal(this.cols, this.rows, config);
// Create canvas element
this.canvas = document.createElement('canvas');
this.canvas.style.display = 'block';
parent.appendChild(this.canvas);
// Create hidden textarea for keyboard input (must be inside parent for event bubbling)
this.textarea = document.createElement('textarea');
this.textarea.setAttribute('autocorrect', 'off');
this.textarea.setAttribute('autocapitalize', 'off');
this.textarea.setAttribute('spellcheck', 'false');
this.textarea.setAttribute('tabindex', '0'); // Allow focus for mobile keyboard
this.textarea.setAttribute('aria-label', 'Terminal input');
// Use clip-path to completely hide the textarea and its caret
this.textarea.style.position = 'absolute';
this.textarea.style.left = '0';
this.textarea.style.top = '0';
this.textarea.style.width = '1px';
this.textarea.style.height = '1px';
this.textarea.style.padding = '0';
this.textarea.style.border = 'none';
this.textarea.style.margin = '0';
this.textarea.style.opacity = '0';
this.textarea.style.clipPath = 'inset(50%)'; // Clip everything including caret
this.textarea.style.overflow = 'hidden';
this.textarea.style.whiteSpace = 'nowrap';
this.textarea.style.resize = 'none';
parent.appendChild(this.textarea);
// Create composition preview element for IME input (Korean, Chinese, Japanese)
this.compositionPreview = document.createElement('div');
this.compositionPreview.style.position = 'absolute';
this.compositionPreview.style.top = '4px';
this.compositionPreview.style.right = '4px';
this.compositionPreview.style.padding = '2px 8px';
this.compositionPreview.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
this.compositionPreview.style.color = '#ffcc00';
this.compositionPreview.style.fontFamily = 'monospace';
this.compositionPreview.style.fontSize = '12px';
this.compositionPreview.style.borderRadius = '3px';
this.compositionPreview.style.display = 'none';
this.compositionPreview.style.zIndex = '1000';
parent.appendChild(this.compositionPreview);
// Listen to composition events for preview
this.textarea.addEventListener('compositionupdate', (e: CompositionEvent) => {
if (e.data) {
this.compositionPreview!.textContent = `조합중: ${e.data}`;
this.compositionPreview!.style.display = 'block';
}
});
this.textarea.addEventListener('compositionend', () => {
this.compositionPreview!.style.display = 'none';
});
// Focus textarea on interaction - preventDefault before focus
const textarea = this.textarea;
// Desktop: mousedown on canvas
this.canvas.addEventListener('mousedown', (ev) => {
ev.preventDefault();
textarea.focus();
});
// Mobile: touchend with preventDefault to suppress iOS caret
this.canvas.addEventListener('touchend', (ev) => {
ev.preventDefault();
textarea.focus();
});
// Redirect focus from parent container to textarea
// This ensures IME composition events always go to the textarea
parent.addEventListener('mousedown', (ev) => {
if (ev.target === parent) {
ev.preventDefault();
textarea.focus();
}
});
parent.addEventListener('focus', () => {
textarea.focus();
});
// Create renderer
this.renderer = new CanvasRenderer(this.canvas, {
fontSize: this.options.fontSize,
fontFamily: this.options.fontFamily,
cursorStyle: this.options.cursorStyle,
cursorBlink: this.options.cursorBlink,
theme: this.options.theme,
});
// Size canvas to terminal dimensions (use renderer.resize for proper DPI scaling)
this.renderer.resize(this.cols, this.rows);
// Create mouse tracking configuration
const canvas = this.canvas;
const renderer = this.renderer;
const wasmTerm = this.wasmTerm;
const mouseConfig: MouseTrackingConfig = {
hasMouseTracking: () => wasmTerm?.hasMouseTracking() ?? false,
hasSgrMouseMode: () => wasmTerm?.getMode(1006, false) ?? true, // SGR extended mode
getCellDimensions: () => ({
width: renderer.charWidth,
height: renderer.charHeight,
}),
getCanvasOffset: () => {
const rect = canvas.getBoundingClientRect();
return { left: rect.left, top: rect.top };
},
};
// Create input handler
this.inputHandler = new InputHandler(
this.ghostty!,
parent,
(data: string) => {
// Check if stdin is disabled
if (this.options.disableStdin) {
return;
}
// Input handler fires data events
this.dataEmitter.fire(data);
},
() => {
// Input handler can also fire bell
this.bellEmitter.fire();
},
(keyEvent: IKeyEvent) => {
// Forward key events
this.keyEmitter.fire(keyEvent);
},
this.customKeyEventHandler,
(mode: number) => {
// Query terminal mode state (e.g., mode 1 for application cursor mode)
return this.wasmTerm?.getMode(mode, false) ?? false;
},
() => {
// Handle Cmd+C copy - returns true if there was a selection to copy
return this.copySelection();
},
this.textarea,
mouseConfig
);
// Create selection manager (pass textarea for context menu positioning)
this.selectionManager = new SelectionManager(
this,
this.renderer,
this.wasmTerm,
this.textarea
);
// Connect selection manager to renderer
this.renderer.setSelectionManager(this.selectionManager);
// Forward selection change events
this.selectionManager.onSelectionChange(() => {
this.selectionChangeEmitter.fire();
});
// Initialize link detection system
this.linkDetector = new LinkDetector(this);
// Register link providers
// OSC8 first (explicit hyperlinks take precedence)
this.linkDetector.registerProvider(new OSC8LinkProvider(this));
// URL regex second (fallback for plain text URLs)
this.linkDetector.registerProvider(new UrlRegexProvider(this));
// Setup mouse event handling for links and scrollbar
// Use capture phase to intercept scrollbar clicks before SelectionManager
parent.addEventListener('mousedown', this.handleMouseDown, { capture: true });
parent.addEventListener('mousemove', this.handleMouseMove);
parent.addEventListener('mouseleave', this.handleMouseLeave);
parent.addEventListener('click', this.handleClick);
// Setup document-level mouseup for scrollbar drag (so drag works even outside canvas)
document.addEventListener('mouseup', this.handleMouseUp);
// Setup wheel event handling for scrolling (Phase 2)
// Use capture phase to ensure we get the event before browser scrolling
parent.addEventListener('wheel', this.handleWheel, { passive: false, capture: true });
// Render initial blank screen (force full redraw)
this.renderer.render(this.wasmTerm, true, this.viewportY, this, this.scrollbarOpacity);
// Start render loop
this.startRenderLoop();
// Focus input (auto-focus so user can start typing immediately)
this.focus();
} catch (error) {
// Clean up on error
this.isOpen = false;
this.cleanupComponents();
throw new Error(`Failed to open terminal: ${error}`);
}
}
/**
* Write data to terminal
*/
write(data: string | Uint8Array, callback?: () => void): void {
this.assertOpen();
// Handle convertEol option
if (this.options.convertEol && typeof data === 'string') {
data = data.replace(/\n/g, '\r\n');
}
this.writeInternal(data, callback);
}
/**
* Internal write implementation (extracted from write())
*/
private writeInternal(data: string | Uint8Array, callback?: () => void): void {
// Note: We intentionally do NOT clear selection on write - most modern terminals
// preserve selection when new data arrives. Selection is cleared by user actions
// like clicking or typing, not by incoming data.
// Write directly to WASM terminal (handles VT parsing internally)
this.wasmTerm!.write(data);
// Process any responses generated by the terminal (e.g., DSR cursor position)
// These need to be sent back to the PTY via onData
this.processTerminalResponses();
// Check for bell character (BEL, \x07)
// WASM doesn't expose bell events, so we detect it in the data stream
if (typeof data === 'string' && data.includes('\x07')) {
this.bellEmitter.fire();
} else if (data instanceof Uint8Array && data.includes(0x07)) {
this.bellEmitter.fire();
}
// Invalidate link cache (content changed)
this.linkDetector?.invalidateCache();
// Phase 2: Auto-scroll to bottom on new output (xterm.js behavior)
if (this.viewportY !== 0) {
this.scrollToBottom();
}
// Check for title changes (OSC 0, 1, 2 sequences)
// This is a simplified implementation - Ghostty WASM may provide this
if (typeof data === 'string' && data.includes('\x1b]')) {
this.checkForTitleChange(data);
}
// Call callback if provided
if (callback) {
// Queue callback after next render
requestAnimationFrame(callback);
}
// Render will happen on next animation frame
}
/**
* Write data with newline
*/
writeln(data: string | Uint8Array, callback?: () => void): void {
if (typeof data === 'string') {
this.write(data + '\r\n', callback);
} else {
// Append \r\n to Uint8Array
const newData = new Uint8Array(data.length + 2);
newData.set(data);
newData[data.length] = 0x0d; // \r
newData[data.length + 1] = 0x0a; // \n
this.write(newData, callback);
}
}
/**
* Paste text into terminal (triggers bracketed paste if supported)
*/
paste(data: string): void {
this.assertOpen();
// Don't paste if stdin is disabled
if (this.options.disableStdin) {
return;
}
// Check if terminal has bracketed paste mode enabled
if (this.wasmTerm!.hasBracketedPaste()) {
// Wrap with bracketed paste sequences (DEC mode 2004)
this.dataEmitter.fire('\x1b[200~' + data + '\x1b[201~');
} else {
// Send data directly
this.dataEmitter.fire(data);
}
}
/**
* Input data into terminal (as if typed by user)
*
* @param data - Data to input
* @param wasUserInput - If true, triggers onData event (default: false for compat with some apps)
*/
input(data: string, wasUserInput: boolean = false): void {
this.assertOpen();
// Don't input if stdin is disabled
if (this.options.disableStdin) {
return;
}
if (wasUserInput) {
// Trigger onData event as if user typed it
this.dataEmitter.fire(data);
} else {
// Just write to terminal without triggering onData
this.write(data);
}
}
/**
* Resize terminal
*/
resize(cols: number, rows: number): void {
this.assertOpen();
if (cols === this.cols && rows === this.rows) {
return; // No change
}
// Update dimensions
this.cols = cols;
this.rows = rows;
// Resize WASM terminal
this.wasmTerm!.resize(cols, rows);
// Resize renderer
this.renderer!.resize(cols, rows);
// Update canvas dimensions
const metrics = this.renderer!.getMetrics();
this.canvas!.width = metrics.width * cols;
this.canvas!.height = metrics.height * rows;
this.canvas!.style.width = `${metrics.width * cols}px`;
this.canvas!.style.height = `${metrics.height * rows}px`;
// Fire resize event
this.resizeEmitter.fire({ cols, rows });
// Force full render
this.renderer!.render(this.wasmTerm!, true, this.viewportY, this);
}
/**
* Clear terminal screen
*/
clear(): void {
this.assertOpen();
// Send ANSI clear screen and cursor home sequences
this.wasmTerm!.write('\x1b[2J\x1b[H');
}
/**
* Reset terminal state
*/
reset(): void {
this.assertOpen();
// Free old WASM terminal and create new one
if (this.wasmTerm) {
this.wasmTerm.free();
}
const config = this.buildWasmConfig();
this.wasmTerm = this.ghostty!.createTerminal(this.cols, this.rows, config);
// Clear renderer
this.renderer!.clear();
// Reset title
this.currentTitle = '';
}
/**
* Focus terminal input
*/
focus(): void {
if (this.isOpen) {
// Focus the textarea for keyboard/IME input.
// The textarea is the actual input element that receives keyboard events
// and IME composition events. Focusing the container doesn't work for IME
// because composition events fire on the focused element.
const target = this.textarea || this.element;
if (target) {
target.focus();
// Also schedule a delayed focus as backup to ensure it sticks
// (some browsers may need this if DOM isn't fully settled)
setTimeout(() => {
target?.focus();
}, 0);
}
}
}
/**
* Blur terminal (remove focus)
*/
blur(): void {
if (this.isOpen && this.element) {
this.element.blur();
}
}
/**
* Load an addon
*/
loadAddon(addon: ITerminalAddon): void {
addon.activate(this);
this.addons.push(addon);
}
// ==========================================================================
// Selection API (xterm.js compatible)
// ==========================================================================
/**
* Get the selected text as a string
*/
public getSelection(): string {
return this.selectionManager?.getSelection() || '';
}
/**
* Check if there's an active selection
*/
public hasSelection(): boolean {
return this.selectionManager?.hasSelection() || false;
}
/**
* Clear the current selection
*/
public clearSelection(): void {
this.selectionManager?.clearSelection();
}
/**
* Copy the current selection to clipboard
* @returns true if there was text to copy, false otherwise
*/
public copySelection(): boolean {
return this.selectionManager?.copySelection() || false;
}
/**
* Select all text in the terminal
*/
public selectAll(): void {
this.selectionManager?.selectAll();
}
/**
* Select text at specific column and row with length
*/
public select(column: number, row: number, length: number): void {
this.selectionManager?.select(column, row, length);
}
/**
* Select entire lines from start to end
*/
public selectLines(start: number, end: number): void {
this.selectionManager?.selectLines(start, end);
}
/**
* Get selection position as buffer range
*/
/**
* Get the current viewport Y position.
*
* This is the number of lines scrolled back from the bottom of the
* scrollback buffer. It may be fractional during smooth scrolling.
*/
public getViewportY(): number {
return this.viewportY;
}
public getSelectionPosition(): IBufferRange | undefined {
return this.selectionManager?.getSelectionPosition();
}
// ==========================================================================
// Phase 1: Custom Event Handlers
// ==========================================================================
/**
* Attach a custom keyboard event handler
* Returns true to prevent default handling
*/
public attachCustomKeyEventHandler(
customKeyEventHandler: (event: KeyboardEvent) => boolean
): void {
this.customKeyEventHandler = customKeyEventHandler;
// Update input handler if already created
if (this.inputHandler) {
this.inputHandler.setCustomKeyEventHandler(customKeyEventHandler);
}
}
/**
* Attach a custom wheel event handler (Phase 2)
* Returns true to prevent default handling
*/
public attachCustomWheelEventHandler(
customWheelEventHandler?: (event: WheelEvent) => boolean
): void {
this.customWheelEventHandler = customWheelEventHandler;
}
// ==========================================================================
// Link Detection Methods
// ==========================================================================
/**
* Register a custom link provider
* Multiple providers can be registered to detect different types of links
*
* @example
* ```typescript
* term.registerLinkProvider({
* provideLinks(y, callback) {
* // Detect URLs, file paths, etc.
* callback(detectedLinks);
* }
* });
* ```
*/
public registerLinkProvider(provider: ILinkProvider): void {
if (!this.linkDetector) {
throw new Error('Terminal must be opened before registering link providers');
}
this.linkDetector.registerProvider(provider);
}
// ==========================================================================
// Phase 2: Scrolling Methods
// ==========================================================================
/**
* Scroll viewport by a number of lines
* @param amount Number of lines to scroll (positive = down, negative = up)
*/
public scrollLines(amount: number): void {
if (!this.wasmTerm) {
throw new Error('Terminal not open');
}
const scrollbackLength = this.getScrollbackLength();
const maxScroll = scrollbackLength;
// Calculate new viewport position
// viewportY = 0 means at bottom (no scroll)
// viewportY > 0 means scrolled up into history
// amount < 0 (scroll up) should INCREASE viewportY
// amount > 0 (scroll down) should DECREASE viewportY
// So we SUBTRACT amount (negative amount becomes positive change)
const newViewportY = Math.max(0, Math.min(maxScroll, this.viewportY - amount));
if (newViewportY !== this.viewportY) {
this.viewportY = newViewportY;
this.scrollEmitter.fire(this.viewportY);
// Show scrollbar when scrolling (with auto-hide)
if (scrollbackLength > 0) {
this.showScrollbar();
}
}
}
/**
* Scroll viewport by a number of pages
* @param amount Number of pages to scroll (positive = down, negative = up)
*/
public scrollPages(amount: number): void {
this.scrollLines(amount * this.rows);
}
/**
* Scroll viewport to the top of the scrollback buffer
*/
public scrollToTop(): void {
const scrollbackLength = this.getScrollbackLength();
if (scrollbackLength > 0 && this.viewportY !== scrollbackLength) {
this.viewportY = scrollbackLength;
this.scrollEmitter.fire(this.viewportY);
this.showScrollbar();
}
}
/**
* Scroll viewport to the bottom (current output)
*/
public scrollToBottom(): void {
if (this.viewportY !== 0) {
this.viewportY = 0;
this.scrollEmitter.fire(this.viewportY);
// Show scrollbar briefly when scrolling to bottom
if (this.getScrollbackLength() > 0) {
this.showScrollbar();
}
}
}
/**
* Scroll viewport to a specific line in the buffer
* @param line Line number (0 = top of scrollback, scrollbackLength = bottom)
*/
public scrollToLine(line: number): void {
const scrollbackLength = this.getScrollbackLength();
const newViewportY = Math.max(0, Math.min(scrollbackLength, line));
if (newViewportY !== this.viewportY) {
this.viewportY = newViewportY;
this.scrollEmitter.fire(this.viewportY);
// Show scrollbar when scrolling to specific line
if (scrollbackLength > 0) {
this.showScrollbar();
}
}
}
/**