-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTerminalPanel.tsx
More file actions
executable file
·3039 lines (2658 loc) · 107 KB
/
Copy pathTerminalPanel.tsx
File metadata and controls
executable file
·3039 lines (2658 loc) · 107 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
import { Show, For, createSignal, createEffect, onMount, onCleanup, createMemo } from "solid-js";
import { createStore, produce } from "solid-js/store";
import { Icon } from "./ui/Icon";
import { useTerminals, TerminalInfo, CreateTerminalOptions } from "@/context/TerminalsContext";
import { useEditor } from "@/context/EditorContext";
import { useSettings } from "@/context/SettingsContext";
import { useAccessibility } from "@/context/AccessibilityContext";
import { getTerminalTheme, getTerminalThemeFromCSS } from "@/lib/terminalThemes";
import { tokens } from '@/design-system/tokens';
import { Terminal as XTerm, IMarker, IDecoration } from "@xterm/xterm";
import type { ILinkProvider, ILink, IBufferRange } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { WebLinksAddon } from "@xterm/addon-web-links";
import { SearchAddon } from "@xterm/addon-search";
import { Unicode11Addon } from "@xterm/addon-unicode11";
import "@xterm/xterm/css/xterm.css";
import "@/styles/terminal.css";
import { TerminalSuggest, useTerminalSuggestions, Suggestion } from "./TerminalSuggest";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { TerminalQuickFix as _TerminalQuickFix } from "./TerminalQuickFix";
import {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
TerminalStickyScroll as _TerminalStickyScroll,
useTerminalCommandTracker,
StickyScrollSettings,
CommandTrackerResult
} from "./TerminalStickyScroll";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { TerminalFind as _TerminalFind, getPersistedSearchQuery } from "./TerminalFind";
import {
TerminalDecorations,
useTerminalDecorations,
type CommandDecoration,
type DecorationAction,
} from "./terminal/TerminalDecorations";
import { TerminalRenameDialog } from "./terminal/TerminalRenameDialog";
import { TerminalColorPicker } from "./terminal/TerminalColorPicker";
/**
* Command marker for tracking command execution status in the terminal gutter
*/
interface CommandMarker {
/** Line number where the command starts */
line: number;
/** Current status of the command */
status: 'running' | 'success' | 'error';
/** Exit code (available when command completes) */
exitCode?: number;
/** The command that was executed */
command?: string;
/** Unix timestamp when command started */
startTime?: number;
/** Unix timestamp when command ended */
endTime?: number;
/** Xterm marker reference */
marker?: IMarker;
/** Xterm decoration reference */
decoration?: IDecoration;
}
/**
* State for managing command markers per terminal
*/
interface CommandMarkerState {
markers: CommandMarker[];
/** Currently running command marker (if any) */
currentMarker?: CommandMarker;
}
/**
* Terminal Panel - Optimized for performance
*
* Performance optimizations:
* - WebGL renderer for GPU-accelerated rendering (when available)
* - Lazy loading of terminal addons
* - Disabled accessibility for better performance
* - Debounced window resize handling
* - Proper memory cleanup on terminal disposal
* - Limited scrollback buffer (10000 lines)
* - Chunked output processing
*/
const MIN_PANEL_HEIGHT = 120;
const MAX_PANEL_HEIGHT = 800;
const DEFAULT_PANEL_HEIGHT = 280;
const MIN_SPLIT_SIZE = 100;
// Performance constants
const SCROLLBACK_LINES = 10000;
const WINDOW_RESIZE_DEBOUNCE_MS = 150;
const OUTPUT_CHUNK_SIZE = 16384; // 16KB chunks for better throughput with large outputs
const OUTPUT_FLUSH_DEBOUNCE_MS = 8; // Faster flush for responsiveness
const ACK_BATCH_SIZE = 32768; // Batch acknowledgments to reduce IPC overhead
// WebGL addon loaded dynamically
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let webglAddonModule: { WebglAddon: new () => any } | null = null;
let webglLoadAttempted = false;
const loadWebglAddon = async (): Promise<boolean> => {
if (webglLoadAttempted) return webglAddonModule !== null;
webglLoadAttempted = true;
try {
// Dynamic import - module may not be installed
const modulePath = "@xterm/addon-webgl";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
webglAddonModule = await (import(/* @vite-ignore */ modulePath) as Promise<any>);
return true;
} catch {
console.warn("[Terminal] WebGL addon not available, using canvas renderer");
return false;
}
};
// Shell type detection for icons
type ShellType = "powershell" | "bash" | "zsh" | "cmd" | "fish" | "sh" | "unknown";
interface TerminalInstance {
terminal: XTerm;
fitAddon: FitAddon;
searchAddon: SearchAddon;
webglAddon: unknown | null;
unsubscribe: () => void;
outputBuffer: string[];
/** Command markers state for gutter decorations */
commandMarkers: CommandMarkerState;
/** Scroll event handler for cleanup */
scrollHandler?: (() => void) | null;
/** Viewport element reference for cleanup */
viewportElement?: HTMLElement | null;
/** ResizeObserver for auto-fitting terminal on container resize */
resizeObserver?: ResizeObserver | null;
/** Container element reference for cleanup */
containerElement?: HTMLElement | null;
/** Decorations state manager for command status indicators */
decorations?: ReturnType<typeof useTerminalDecorations>;
/** Current running decoration ID */
currentDecorationId?: string | null;
}
// Terminal group for split views
interface TerminalGroup {
id: string;
terminalIds: string[];
splitDirection: "horizontal" | "vertical" | null;
splitRatio: number;
}
// Context menu state
interface ContextMenuState {
visible: boolean;
x: number;
y: number;
terminalId: string | null;
}
// Shell profile for dropdown
interface ShellProfile {
name: string;
shell: string;
icon: ShellType;
args?: string[];
}
/**
* Safely format duration from start and end timestamps
* Handles undefined/null values gracefully for robust Tauri integration
* @param startTime - Start timestamp (ms)
* @param endTime - End timestamp (ms)
* @returns Formatted duration string or null if times are invalid
*/
function formatCommandDuration(startTime: number | undefined, endTime: number | undefined): string | null {
if (startTime === undefined || endTime === undefined) return null;
if (startTime <= 0 || endTime <= 0) return null;
const duration = endTime - startTime;
if (duration < 0) return null;
if (duration < 1000) {
return `${duration}ms`;
} else if (duration < 60000) {
return `${(duration / 1000).toFixed(1)}s`;
} else {
const minutes = Math.floor(duration / 60000);
const seconds = ((duration % 60000) / 1000).toFixed(0);
return `${minutes}m ${seconds}s`;
}
}
/**
* Check if a terminal instance is in a valid state for writing
* Provides defensive checks to prevent crashes when terminal is closing
* @param terminal - XTerm terminal instance
* @param terminalId - Terminal ID for debug logging
* @returns true if terminal is valid for writing
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function isTerminalWritable(terminal: XTerm | null | undefined, terminalId: string): boolean {
try {
if (!terminal) {
console.debug(`[Terminal] Terminal ${terminalId} is null`);
return false;
}
if (!terminal.element) {
console.debug(`[Terminal] Terminal ${terminalId} element is null`);
return false;
}
if (terminal.element.classList.contains('disposed')) {
console.debug(`[Terminal] Terminal ${terminalId} has disposed class`);
return false;
}
return true;
} catch {
return false;
}
}
// Get shell type from shell path/name
function getShellType(shell: string): ShellType {
const shellLower = shell.toLowerCase();
if (shellLower.includes("powershell") || shellLower.includes("pwsh")) return "powershell";
if (shellLower.includes("bash")) return "bash";
if (shellLower.includes("zsh")) return "zsh";
if (shellLower.includes("cmd") || shellLower.includes("command")) return "cmd";
if (shellLower.includes("fish")) return "fish";
if (shellLower.includes("/sh") || shellLower.endsWith("sh")) return "sh";
return "unknown";
}
// Terminal icon component based on shell type
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function _TerminalIcon(props: { shell: string; status: string; class?: string }) {
const shellType = () => getShellType(props.shell);
const color = () => props.status === "running" ? tokens.colors.semantic.success : tokens.colors.text.muted;
return (
<div class={props.class} style={{ color: color() }}>
<Show when={shellType() === "powershell"}>
<svg viewBox="0 0 24 24" fill="currentColor" class="w-3.5 h-3.5">
<path d="M23.181 2.974c.568 0 .923.463.792 1.035l-3.659 16.026c-.13.572-.697 1.035-1.265 1.035H.819c-.568 0-.923-.463-.792-1.035L3.686 3.009c.13-.572.697-1.035 1.265-1.035h18.23zM8.402 16.728l.833-.696-4.461-3.883 4.461-3.883-.833-.696-5.121 4.579 5.121 4.579zm2.218-.328h6.96l.416-1.852h-6.96l-.416 1.852z"/>
</svg>
</Show>
<Show when={shellType() === "bash" || shellType() === "zsh" || shellType() === "sh" || shellType() === "fish"}>
<svg viewBox="0 0 24 24" fill="currentColor" class="w-3.5 h-3.5">
<path d="M4 20q-.825 0-1.412-.587Q2 18.825 2 18V6q0-.825.588-1.412Q3.175 4 4 4h16q.825 0 1.413.588Q22 5.175 22 6v12q0 .825-.587 1.413Q20.825 20 20 20zm0-2h16V8H4v10zm2-2h2v-2H6v2zm4 0h8v-2h-8v2zm-4-4h12v-2H6v2z"/>
</svg>
</Show>
<Show when={shellType() === "cmd"}>
<svg viewBox="0 0 24 24" fill="currentColor" class="w-3.5 h-3.5">
<path d="M2 4h20v16H2V4zm2 2v12h16V6H4zm2 2l4 3-4 3v-6zm5 5h7v2h-7v-2z"/>
</svg>
</Show>
<Show when={shellType() === "unknown"}>
<Icon name="terminal" class="w-3.5 h-3.5" />
</Show>
</div>
);
}
// Generate unique ID
function generateId(): string {
return `group-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
}
/**
* Create debounced function for window resize handling
*/
function createDebouncedResize(
callback: () => void,
delay: number
): { call: () => void; cancel: () => void } {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return {
call: () => {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback();
timeoutId = null;
}, delay);
},
cancel: () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
}
};
}
/**
* Output stream processor for chunked processing with debounced flushing
* Optimized for high-throughput terminal output
*
* Performance optimizations:
* - Pre-allocated buffer array to reduce GC pressure
* - Uses TextDecoder for efficient string handling of large data
* - Batched acknowledgments to reduce IPC overhead
*/
class OutputStreamProcessor {
private bufferChunks: string[] = [];
private bufferLength = 0;
private readonly chunkSize: number;
private flushTimeoutId: ReturnType<typeof setTimeout> | null = null;
private pendingCallback: ((chunk: string) => void) | null = null;
private pendingAckBytes = 0;
private ackCallback: ((bytes: number) => void) | null = null;
constructor(chunkSize: number = OUTPUT_CHUNK_SIZE) {
this.chunkSize = chunkSize;
}
/**
* Set acknowledgment callback for flow control
*/
setAckCallback(callback: (bytes: number) => void): void {
this.ackCallback = callback;
}
/**
* Process data in chunks with optimized string handling
* Uses array-based buffer to avoid repeated string concatenation
*/
processChunked(data: string, callback: (chunk: string) => void): void {
this.bufferChunks.push(data);
this.bufferLength += data.length;
this.pendingCallback = callback;
// Track bytes for batched acknowledgment
this.pendingAckBytes += data.length;
// Process full chunks immediately when buffer exceeds chunk size
while (this.bufferLength >= this.chunkSize) {
// Join all chunks and split at chunk size
const fullBuffer = this.bufferChunks.join('');
const chunk = fullBuffer.substring(0, this.chunkSize);
const remainder = fullBuffer.substring(this.chunkSize);
// Reset buffer with remainder
this.bufferChunks = remainder.length > 0 ? [remainder] : [];
this.bufferLength = remainder.length;
callback(chunk);
}
// Batch acknowledgments to reduce IPC overhead
if (this.pendingAckBytes >= ACK_BATCH_SIZE && this.ackCallback) {
this.ackCallback(this.pendingAckBytes);
this.pendingAckBytes = 0;
}
// Schedule debounced flush for remaining data
if (this.bufferLength > 0 && !this.flushTimeoutId) {
this.flushTimeoutId = setTimeout(() => {
this.flushImmediate();
}, OUTPUT_FLUSH_DEBOUNCE_MS);
}
}
/**
* Internal immediate flush without timeout handling
*/
private flushImmediate(): void {
if (this.bufferLength > 0 && this.pendingCallback) {
const data = this.bufferChunks.join('');
this.bufferChunks = [];
this.bufferLength = 0;
this.pendingCallback(data);
}
this.flushTimeoutId = null;
// Flush any remaining ack bytes
if (this.pendingAckBytes > 0 && this.ackCallback) {
this.ackCallback(this.pendingAckBytes);
this.pendingAckBytes = 0;
}
}
/**
* Force flush the buffer immediately
*/
flush(callback: (chunk: string) => void): void {
if (this.flushTimeoutId) {
clearTimeout(this.flushTimeoutId);
this.flushTimeoutId = null;
}
if (this.bufferLength > 0) {
const data = this.bufferChunks.join('');
this.bufferChunks = [];
this.bufferLength = 0;
callback(data);
}
// Flush any remaining ack bytes
if (this.pendingAckBytes > 0 && this.ackCallback) {
this.ackCallback(this.pendingAckBytes);
this.pendingAckBytes = 0;
}
}
/**
* Cancel any pending flush timeout and clear buffers
*/
cancel(): void {
if (this.flushTimeoutId) {
clearTimeout(this.flushTimeoutId);
this.flushTimeoutId = null;
}
this.bufferChunks = [];
this.bufferLength = 0;
this.pendingCallback = null;
this.pendingAckBytes = 0;
}
/**
* Dispose and release all resources to prevent memory leaks
* Should be called when the terminal is being destroyed
*/
dispose(): void {
this.cancel();
// Clear callbacks to prevent memory leaks from closures holding references
this.ackCallback = null;
this.pendingCallback = null;
}
/**
* Check if the processor has been disposed
*/
isDisposed(): boolean {
return this.ackCallback === null && this.pendingCallback === null && this.bufferChunks.length === 0;
}
}
/**
* File path link provider for terminal
* Detects local file paths in terminal output and makes them clickable
*/
class FilePathLinkProvider implements ILinkProvider {
private terminal: XTerm;
private onOpenFile: (path: string, line?: number, column?: number) => void;
private hoverTooltip: HTMLDivElement | null = null;
constructor(
terminal: XTerm,
onOpenFile: (path: string, line?: number, column?: number) => void
) {
this.terminal = terminal;
this.onOpenFile = onOpenFile;
}
provideLinks(
bufferLineNumber: number,
callback: (links: ILink[] | undefined) => void
): void {
const buffer = this.terminal.buffer.active;
const line = buffer.getLine(bufferLineNumber);
if (!line) {
callback(undefined);
return;
}
const lineText = line.translateToString();
if (!lineText || lineText.trim().length === 0) {
callback(undefined);
return;
}
const links: ILink[] = [];
// Regex patterns for file paths with optional line:column
const patterns = [
// Unix absolute paths: /path/to/file.ts:10:5 or /path/to/file.ts(10,5)
/(?<path>\/(?:[\w\-.]|\/)+\.[\w]+)(?::(?<line>\d+)(?::(?<col>\d+))?|\((?<pline>\d+)(?:,(?<pcol>\d+))?\))?/g,
// Windows paths: C:\path\to\file.ts:10:5 or C:\path\to\file.ts(10,5)
/(?<path>[A-Za-z]:\\(?:[\w\-.]|\\)+\.[\w]+)(?::(?<line>\d+)(?::(?<col>\d+))?|\((?<pline>\d+)(?:,(?<pcol>\d+))?\))?/g,
// Relative paths: ./src/file.ts:10 or ../file.ts:10:5
/(?<path>\.\.?\/(?:[\w\-.]|\/)+\.[\w]+)(?::(?<line>\d+)(?::(?<col>\d+))?|\((?<pline>\d+)(?:,(?<pcol>\d+))?\))?/g,
];
for (const pattern of patterns) {
// Reset lastIndex for each pattern
pattern.lastIndex = 0;
let match;
while ((match = pattern.exec(lineText)) !== null) {
const matchText = match[0];
const groups = match.groups;
if (!groups?.path) continue;
const filePath = groups.path;
// Support both :line:col and (line,col) formats
const lineNum = groups.line || groups.pline;
const colNum = groups.col || groups.pcol;
const startX = match.index + 1; // 1-based
const endX = match.index + matchText.length + 1; // 1-based, exclusive
const range: IBufferRange = {
start: { x: startX, y: bufferLineNumber + 1 }, // 1-based line number
end: { x: endX, y: bufferLineNumber + 1 },
};
links.push({
range,
text: matchText,
activate: (_event: MouseEvent, _text: string) => {
this.onOpenFile(
filePath,
lineNum ? parseInt(lineNum, 10) : undefined,
colNum ? parseInt(colNum, 10) : undefined
);
},
hover: (event: MouseEvent, _text: string) => {
this.showHoverTooltip(event, filePath, lineNum, colNum);
},
leave: (_event: MouseEvent, _text: string) => {
this.hideHoverTooltip();
},
dispose: () => {
this.hideHoverTooltip();
},
});
}
}
callback(links.length > 0 ? links : undefined);
}
private showHoverTooltip(
event: MouseEvent,
filePath: string,
line?: string,
column?: string
): void {
this.hideHoverTooltip();
const tooltip = document.createElement("div");
tooltip.className = "xterm-hover terminal-file-link-tooltip";
tooltip.style.cssText = `
position: fixed;
z-index: 1000;
padding: ${tokens.spacing.sm} ${tokens.spacing.md};
background: var(--jb-popup);
border: 1px solid ${tokens.colors.border.divider};
border-radius: ${tokens.radius.sm};
font-size: var(--jb-text-muted-size);
color: ${tokens.colors.text.primary};
pointer-events: none;
white-space: nowrap;
box-shadow: var(--jb-shadow-popup);
`;
let tooltipText = "Click to open file";
if (line) {
tooltipText += ` at line ${line}`;
if (column) {
tooltipText += `:${column}`;
}
}
// Show file path in tooltip as well
const pathSpan = document.createElement("div");
pathSpan.style.cssText = `
font-size: var(--jb-text-header-size);
color: ${tokens.colors.text.muted};
margin-top: 2px;
max-width: 400px;
overflow: hidden;
text-overflow: ellipsis;
`;
pathSpan.textContent = filePath;
const actionSpan = document.createElement("div");
actionSpan.textContent = tooltipText;
tooltip.appendChild(actionSpan);
tooltip.appendChild(pathSpan);
// Position tooltip near the cursor
const x = event.clientX + 10;
const y = event.clientY + 10;
tooltip.style.left = `${x}px`;
tooltip.style.top = `${y}px`;
// Add to terminal element to prevent mouse events from falling through
const terminalElement = this.terminal.element;
if (terminalElement) {
terminalElement.appendChild(tooltip);
this.hoverTooltip = tooltip;
// Adjust position if tooltip goes off screen
requestAnimationFrame(() => {
const rect = tooltip.getBoundingClientRect();
if (rect.right > window.innerWidth) {
tooltip.style.left = `${event.clientX - rect.width - 10}px`;
}
if (rect.bottom > window.innerHeight) {
tooltip.style.top = `${event.clientY - rect.height - 10}px`;
}
});
}
}
private hideHoverTooltip(): void {
if (this.hoverTooltip) {
this.hoverTooltip.remove();
this.hoverTooltip = null;
}
}
}
export function TerminalPanel() {
const {
state,
closePanel,
setActiveTerminal,
createTerminal,
closeTerminal,
writeToTerminal,
updateTerminalInfo,
resizeTerminal,
sendInterrupt,
subscribeToOutput,
renameTerminal,
setTerminalColor,
getTerminalName,
getTerminalColor,
} = useTerminals();
// Editor context for opening files from terminal links
const editor = useEditor();
// Settings context for terminal appearance
const settings = useSettings();
const terminalSettings = () => settings.effectiveSettings().terminal;
// Accessibility context for screen reader announcements
const accessibility = useAccessibility();
// ARIA live region reference for terminal announcements
let ariaLiveRegion: HTMLDivElement | undefined;
const [panelHeight, setPanelHeight] = createSignal(DEFAULT_PANEL_HEIGHT);
const [_isResizing, setIsResizing] = createSignal(false);
const [isMaximized, setIsMaximized] = createSignal(false);
const [_hoveredTabId, _setHoveredTabId] = createSignal<string | null>(null);
const [isFocused, setIsFocused] = createSignal(false);
const [editingTabId, setEditingTabId] = createSignal<string | null>(null);
const [editingName, setEditingName] = createSignal("");
const [showNewTerminalDropdown, setShowNewTerminalDropdown] = createSignal(false);
const [_shellProfiles, setShellProfiles] = createSignal<ShellProfile[]>([]);
const [draggedTabId, setDraggedTabId] = createSignal<string | null>(null);
const [_dragOverTabId, setDragOverTabId] = createSignal<string | null>(null);
const [tabOrder, setTabOrder] = createSignal<string[]>([]);
// Context menu state
const [contextMenu, setContextMenu] = createStore<ContextMenuState>({
visible: false,
x: 0,
y: 0,
terminalId: null,
});
// Terminal groups state for split views
const [groups, setGroups] = createStore<TerminalGroup[]>([]);
// Custom terminal names
const [_terminalNames, setTerminalNames] = createStore<Record<string, string>>({});
// Terminal suggestions integration
const suggestions = useTerminalSuggestions({ enabled: true, debounceMs: 50 });
const [inputBuffer, setInputBuffer] = createStore<Record<string, string>>({});
// Terminal quick fix integration for error detection
const [_terminalOutputs, setTerminalOutputs] = createStore<Record<string, string>>({});
const [quickFixEnabled] = createSignal(true);
// Scroll lock state - when locked, don't auto-scroll on new output
const [scrollLocked, setScrollLocked] = createSignal(false);
// Find widget visibility state
const [showFindWidget, setShowFindWidget] = createSignal(false);
// Rename and color picker dialog state
const [showRenameDialog, setShowRenameDialog] = createSignal(false);
const [showColorPicker, setShowColorPicker] = createSignal(false);
const [dialogTerminalId, setDialogTerminalId] = createSignal<string | null>(null);
// Sticky scroll state - tracks commands per terminal for sticky headers
const [stickyScrollSettings] = createStore<StickyScrollSettings>({
enabled: true,
maxCommands: 5,
});
const [_terminalScrollLines, setTerminalScrollLines] = createStore<Record<string, number>>({});
const [_terminalTotalLines, setTerminalTotalLines] = createStore<Record<string, number>>({});
const stickyScrollTrackers = new Map<string, CommandTrackerResult>();
// Output stream processors per terminal
const outputProcessors = new Map<string, OutputStreamProcessor>();
// Terminal decorations state per terminal
const terminalDecorations = new Map<string, ReturnType<typeof useTerminalDecorations>>();
// Decoration settings accessor
const decorationSettings = () => {
const ts = terminalSettings();
return ts.decorations ?? { enabled: true, showDuration: true, showExitCode: true };
};
// Embedded mode - renders into bottom panel instead of floating
const [isEmbedded, setIsEmbedded] = createSignal(false);
let _panelRef: HTMLDivElement | undefined;
let terminalContainerRef: HTMLDivElement | undefined;
let dropdownRef: HTMLDivElement | undefined;
let editInputRef: HTMLInputElement | undefined;
let previousHeight = DEFAULT_PANEL_HEIGHT;
let windowResizeDebouncer: ReturnType<typeof createDebouncedResize> | null = null;
// Map of terminal instances keyed by terminal ID
const terminalInstances = new Map<string, TerminalInstance>();
const activeTerminal = createMemo(() =>
state.terminals.find(t => t.id === state.activeTerminalId)
);
/**
* Announce a message to screen readers via ARIA live region
* Only announces if screen reader announcements are enabled in terminal settings
*/
const announceToScreenReader = (message: string, assertive: boolean = false) => {
const ts = terminalSettings();
if (!ts.screenReaderAnnounce) return;
// Use global accessibility context announcement if screen reader mode is on
if (accessibility.screenReaderMode()) {
accessibility.announceToScreenReader(message, assertive ? "assertive" : "polite");
return;
}
// Fall back to local ARIA live region
if (ariaLiveRegion) {
ariaLiveRegion.setAttribute("aria-live", assertive ? "assertive" : "polite");
ariaLiveRegion.textContent = "";
requestAnimationFrame(() => {
if (ariaLiveRegion) {
ariaLiveRegion.textContent = message;
}
});
}
};
/**
* Track command history per terminal for keyboard navigation
*/
const [commandHistory, setCommandHistory] = createStore<Record<string, { commands: string[]; index: number }>>({});
/**
* Navigate through command history with keyboard (Up/Down arrows)
*/
const _navigateHistory = (terminalId: string, direction: "up" | "down") => {
const history = commandHistory[terminalId];
if (!history || history.commands.length === 0) return;
const instance = terminalInstances.get(terminalId);
if (!instance) return;
const currentBuffer = inputBuffer[terminalId] || "";
let newIndex = history.index;
if (direction === "up") {
// Going back in history
if (newIndex === -1) {
// First time going up, save current input
newIndex = history.commands.length - 1;
} else if (newIndex > 0) {
newIndex--;
}
} else {
// Going forward in history
if (newIndex < history.commands.length - 1) {
newIndex++;
} else {
// At the end, clear to allow new input
newIndex = -1;
}
}
setCommandHistory(terminalId, "index", newIndex);
// Get the command to display
const command = newIndex >= 0 && newIndex < history.commands.length
? history.commands[newIndex]
: "";
// Clear current line and write the history command
if (currentBuffer.length > 0) {
const backspaces = "\b".repeat(currentBuffer.length);
const clearChars = " ".repeat(currentBuffer.length);
const backspaces2 = "\b".repeat(currentBuffer.length);
writeToTerminal(terminalId, backspaces + clearChars + backspaces2).catch(console.error);
}
if (command) {
writeToTerminal(terminalId, command).catch(console.error);
setInputBuffer(terminalId, command);
// Announce for screen reader
if (terminalSettings()?.accessibleViewEnabled) {
announceToScreenReader(`History: ${command}`);
}
} else {
setInputBuffer(terminalId, "");
}
};
/**
* Add a command to history for a terminal
*/
const _addToHistory = (terminalId: string, command: string) => {
if (!command.trim()) return;
setCommandHistory(terminalId, (prev) => {
const existing = prev || { commands: [], index: -1 };
// Avoid duplicates at the end
const lastCommand = existing.commands[existing.commands.length - 1];
if (lastCommand === command) {
return { ...existing, index: -1 };
}
// Keep last 100 commands
const newCommands = [...existing.commands, command].slice(-100);
return { commands: newCommands, index: -1 };
});
};
// Update cursor position for suggestions dropdown
const updateCursorPosition = (terminalId: string) => {
const instance = terminalInstances.get(terminalId);
if (!instance || !terminalContainerRef) return;
const terminal = instance.terminal;
const cursorX = terminal.buffer.active.cursorX;
const cursorY = terminal.buffer.active.cursorY;
// Get terminal container position
const container = terminalContainerRef.querySelector(`[data-terminal-id="${terminalId}"]`) as HTMLElement;
if (!container) return;
const rect = container.getBoundingClientRect();
const cellWidth = terminal.options.fontSize ? terminal.options.fontSize * 0.6 : 8;
const cellHeight = terminal.options.fontSize ? terminal.options.fontSize * 1.2 : 16;
const x = rect.left + cursorX * cellWidth + 8;
const y = rect.top + cursorY * cellHeight + 8;
suggestions.setCursorPosition({ x, y });
};
// Handle suggestion selection - write to terminal
const handleSuggestionSelect = (suggestion: Suggestion) => {
const active = activeTerminal();
if (!active) return;
const currentBuffer = inputBuffer[active.id] || "";
const insertText = suggestion.insertText || suggestion.text;
let deleteCount = 0;
let textToInsert = "";
if (suggestion.type === "history") {
deleteCount = currentBuffer.length;
textToInsert = insertText;
} else if (suggestion.type === "arg" || suggestion.type === "file" || suggestion.type === "directory") {
const parts = currentBuffer.split(/\s+/);
const lastArg = parts[parts.length - 1] || "";
deleteCount = lastArg.length;
textToInsert = insertText;
} else if (suggestion.type === "git" && insertText.startsWith("git ")) {
deleteCount = currentBuffer.length;
textToInsert = insertText;
} else if (currentBuffer.includes(" ")) {
const lastSpaceIdx = currentBuffer.lastIndexOf(" ");
const lastArg = currentBuffer.slice(lastSpaceIdx + 1);
deleteCount = lastArg.length;
textToInsert = insertText;
} else {
deleteCount = currentBuffer.length;
textToInsert = insertText;
}
const backspaces = "\b".repeat(deleteCount);
const clearChars = " ".repeat(deleteCount);
const backspaces2 = "\b".repeat(deleteCount);
writeToTerminal(active.id, backspaces + clearChars + backspaces2 + textToInsert).catch(console.error);
let newBuffer: string;
if (suggestion.type === "history" || (suggestion.type === "git" && insertText.startsWith("git "))) {
newBuffer = insertText;
} else if (currentBuffer.includes(" ")) {
const lastSpaceIdx = currentBuffer.lastIndexOf(" ");
newBuffer = currentBuffer.slice(0, lastSpaceIdx + 1) + insertText;
} else {
newBuffer = insertText;
}
setInputBuffer(active.id, newBuffer);
suggestions.closeSuggestions();
};
// Handle quick fix application - write the fix command to terminal
const _handleQuickFixApply = (command: string) => {
const active = activeTerminal();
if (!active) return;
const currentBuffer = inputBuffer[active.id] || "";
if (currentBuffer.length > 0) {
const backspaces = "\b".repeat(currentBuffer.length);
const clearChars = " ".repeat(currentBuffer.length);
const backspaces2 = "\b".repeat(currentBuffer.length);
writeToTerminal(active.id, backspaces + clearChars + backspaces2).catch(console.error);
}
writeToTerminal(active.id, command + "\r").catch(console.error);
setInputBuffer(active.id, "");
setTerminalOutputs(active.id, "");
};
// Get or create sticky scroll tracker for a terminal
const getStickyScrollTracker = (terminalId: string): CommandTrackerResult => {
let tracker = stickyScrollTrackers.get(terminalId);
if (!tracker) {
tracker = useTerminalCommandTracker({
maxCommands: 50,
enabled: stickyScrollSettings.enabled,
});
stickyScrollTrackers.set(terminalId, tracker);
}
return tracker;
};
// Process terminal output line for sticky scroll command detection
const processStickyScrollLine = (terminalId: string, lineNumber: number, lineContent: string) => {
if (!stickyScrollSettings.enabled) return;
const tracker = getStickyScrollTracker(terminalId);
tracker.processLine(lineNumber, lineContent);
};
// Update terminal scroll position for sticky scroll
const updateTerminalScrollPosition = (terminalId: string, scrollLine: number, totalLines: number) => {
setTerminalScrollLines(terminalId, scrollLine);
setTerminalTotalLines(terminalId, totalLines);
};
// Scroll terminal to a specific line
const _scrollTerminalToLine = (terminalId: string, line: number) => {
const instance = terminalInstances.get(terminalId);
if (instance) {
instance.terminal.scrollToLine(line);
}
};
// Clear sticky scroll tracker for a terminal
const clearStickyScrollTracker = (terminalId: string) => {
const tracker = stickyScrollTrackers.get(terminalId);
if (tracker) {
tracker.clear();
}
setTerminalScrollLines(terminalId, undefined!);
setTerminalTotalLines(terminalId, undefined!);
};
// Get display name for terminal (custom name or default)
// Uses context's getTerminalName which handles localStorage persistence
const getTerminalDisplayName = (terminal: TerminalInfo): string => {
return getTerminalName(terminal.id) || terminal.name;
};
// Order terminals based on tab order, with new terminals added at end
const _orderedTerminals = createMemo(() => {
const order = tabOrder();
const terminals = [...state.terminals];
return terminals.sort((a, b) => {
const aIndex = order.indexOf(a.id);
const bIndex = order.indexOf(b.id);
if (aIndex === -1 && bIndex === -1) return 0;
if (aIndex === -1) return 1;
if (bIndex === -1) return -1;
return aIndex - bIndex;
});
});
// Update tab order when terminals change
createEffect(() => {
const terminalIds = state.terminals.map(t => t.id);
const currentOrder = tabOrder();
const newIds = terminalIds.filter(id => !currentOrder.includes(id));