forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathterminalTouchSelection.js
More file actions
1510 lines (1289 loc) · 38.8 KB
/
terminalTouchSelection.js
File metadata and controls
1510 lines (1289 loc) · 38.8 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
/**
* Touch Selection for Terminal
*/
import select from "dialogs/select";
import "./terminalTouchSelection.css";
const DEFAULT_MORE_OPTION_ID = "__acode_terminal_select_all__";
const terminalMoreOptions = new Map();
let terminalMoreOptionCounter = 0;
function ensureDefaultMoreOption() {
if (terminalMoreOptions.has(DEFAULT_MORE_OPTION_ID)) return;
terminalMoreOptions.set(DEFAULT_MORE_OPTION_ID, {
id: DEFAULT_MORE_OPTION_ID,
label: () => strings["select all"] || "Select all",
icon: "text_format",
action: ({ touchSelection }) => touchSelection.selectAllText(),
});
}
function normalizeMoreOption(option) {
if (!option || typeof option !== "object" || Array.isArray(option)) {
console.warn(
"[TerminalTouchSelection] addMoreOption expects an option object.",
);
return null;
}
const id =
option.id != null && option.id !== ""
? String(option.id)
: `terminal_more_option_${++terminalMoreOptionCounter}`;
const label = option.label ?? option.text ?? option.title;
const action = option.action || option.onselect || option.onclick;
if (!label) {
console.warn(
`[TerminalTouchSelection] More option '${id}' must provide a label/text/title.`,
);
return null;
}
if (typeof action !== "function") {
console.warn(
`[TerminalTouchSelection] More option '${id}' must provide an action function.`,
);
return null;
}
return {
id,
label,
icon: option.icon || null,
enabled: option.enabled,
action,
};
}
function resolveMoreOptionLabel(option, context) {
try {
const value =
typeof option.label === "function" ? option.label(context) : option.label;
return value == null ? "" : String(value);
} catch (error) {
console.warn(
`[TerminalTouchSelection] Failed to resolve label for option '${option.id}'.`,
error,
);
return "";
}
}
function isMoreOptionEnabled(option, context) {
try {
if (typeof option.enabled === "function") {
return option.enabled(context) !== false;
}
if (option.enabled === undefined) return true;
return option.enabled !== false;
} catch (error) {
console.warn(
`[TerminalTouchSelection] Failed to resolve enabled state for option '${option.id}'.`,
error,
);
return true;
}
}
export default class TerminalTouchSelection {
/**
* Register an option for the "More" menu in touch selection.
* @param {{
* id?: string,
* label?: string|function(object):string,
* text?: string,
* title?: string,
* icon?: string,
* enabled?: boolean|function(object):boolean,
* action?: function(object):void|Promise<void>,
* onselect?: function(object):void|Promise<void>,
* onclick?: function(object):void|Promise<void>
* }} option
* @returns {string|null}
*/
static addMoreOption(option) {
ensureDefaultMoreOption();
const normalized = normalizeMoreOption(option);
if (!normalized) return null;
terminalMoreOptions.set(normalized.id, normalized);
return normalized.id;
}
/**
* Remove a registered "More" menu option by id.
* @param {string} id
* @returns {boolean}
*/
static removeMoreOption(id) {
ensureDefaultMoreOption();
if (id == null || id === "") return false;
return terminalMoreOptions.delete(String(id));
}
/**
* List all registered "More" menu options.
* @returns {Array<object>}
*/
static getMoreOptions() {
ensureDefaultMoreOption();
return [...terminalMoreOptions.values()].map((option) => ({ ...option }));
}
constructor(terminal, container, options = {}) {
ensureDefaultMoreOption();
this.terminal = terminal;
this.container = container;
this.options = {
tapHoldDuration: 600,
moveThreshold: 8,
handleSize: 24,
hapticFeedback: true,
showContextMenu: true,
fingerOffset: 40, // Offset in pixels to position selection above finger during drag
...options,
};
// Selection state
this.isSelecting = false;
this.isHandleDragging = false;
this.selectionStart = null;
this.selectionEnd = null;
this.currentSelection = null;
// Touch tracking
this.touchStartTime = 0;
this.touchStartPos = { x: 0, y: 0 };
this.initialTouchPos = { x: 0, y: 0 };
this.tapHoldTimeout = null;
this.dragHandle = null;
this.isSelectionTouchActive = false;
this.pendingSelectionClearTouch = null;
// Zoom tracking
this.pinchStartDistance = 0;
this.lastPinchDistance = 0;
this.isPinching = false;
this.initialFontSize = 0;
this.lastZoomTime = 0;
this.zoomThrottle = 50; // ms
// DOM elements
this.selectionOverlay = null;
this.startHandle = null;
this.endHandle = null;
this.contextMenu = null;
// Cell dimensions cache
this.cellDimensions = { width: 0, height: 0 };
// Event handlers
this.boundHandlers = {};
// Focus tracking
this.wasFocusedBeforeSelection = false;
this.contextMenuShouldStayVisible = false;
// Selection protection during keyboard events
this.selectionProtected = false;
this.protectionTimeout = null;
// Scroll tracking
this.scrollElement = null;
this.isTerminalScrolling = false;
this.scrollEndTimeout = null;
this.scrollEndDelay = 100;
this.init();
}
init() {
this.createSelectionOverlay();
this.createHandles();
this.attachEventListeners();
this.updateCellDimensions();
}
createSelectionOverlay() {
this.selectionOverlay = document.createElement("div");
this.selectionOverlay.className = "terminal-selection-overlay";
this.selectionOverlay.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 100;
overflow: hidden;
`;
this.container.appendChild(this.selectionOverlay);
}
createHandles() {
this.startHandle = this.createHandle("start");
this.startHandle.style.cssText += `
transform: rotate(180deg) translateX(87%);
border-radius: 50% 50% 50% 0;
`;
this.endHandle = this.createHandle("end");
this.endHandle.style.cssText += `
transform: rotate(90deg) translateY(-13%);
border-radius: 50% 50% 50% 0;
`;
this.selectionOverlay.appendChild(this.startHandle);
this.selectionOverlay.appendChild(this.endHandle);
}
createHandle(type) {
const handle = document.createElement("div");
handle.className = `terminal-selection-handle terminal-selection-handle-${type}`;
handle.style.cssText = `
position: absolute;
width: ${this.options.handleSize}px;
height: ${this.options.handleSize}px;
background: #2196F3;
border: 2px solid #fff;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
display: none;
pointer-events: auto;
touch-action: none;
z-index: 101;
cursor: grab;
`;
// Ensure dataset is properly set
handle.dataset.handleType = type;
return handle;
}
attachEventListeners() {
// Terminal touch events
this.boundHandlers.terminalTouchStart =
this.onTerminalTouchStart.bind(this);
this.boundHandlers.terminalTouchMove = this.onTerminalTouchMove.bind(this);
this.boundHandlers.terminalTouchEnd = this.onTerminalTouchEnd.bind(this);
this.terminal.element.addEventListener(
"touchstart",
this.boundHandlers.terminalTouchStart,
{ passive: false },
);
this.terminal.element.addEventListener(
"touchmove",
this.boundHandlers.terminalTouchMove,
{ passive: false },
);
this.terminal.element.addEventListener(
"touchend",
this.boundHandlers.terminalTouchEnd,
{ passive: false },
);
// Handle touch events
this.boundHandlers.handleTouchStart = this.onHandleTouchStart.bind(this);
this.boundHandlers.handleTouchMove = this.onHandleTouchMove.bind(this);
this.boundHandlers.handleTouchEnd = this.onHandleTouchEnd.bind(this);
this.startHandle.addEventListener(
"touchstart",
this.boundHandlers.handleTouchStart,
{ passive: false },
);
this.startHandle.addEventListener(
"touchmove",
this.boundHandlers.handleTouchMove,
{ passive: false },
);
this.startHandle.addEventListener(
"touchend",
this.boundHandlers.handleTouchEnd,
{ passive: false },
);
this.endHandle.addEventListener(
"touchstart",
this.boundHandlers.handleTouchStart,
{ passive: false },
);
this.endHandle.addEventListener(
"touchmove",
this.boundHandlers.handleTouchMove,
{ passive: false },
);
this.endHandle.addEventListener(
"touchend",
this.boundHandlers.handleTouchEnd,
{ passive: false },
);
// Selection change listener
this.boundHandlers.selectionChange = this.onSelectionChange.bind(this);
this.terminal.onSelectionChange(this.boundHandlers.selectionChange);
// Orientation change
this.boundHandlers.orientationChange = this.onOrientationChange.bind(this);
window.addEventListener(
"orientationchange",
this.boundHandlers.orientationChange,
);
window.addEventListener("resize", this.boundHandlers.orientationChange);
// Terminal scroll listener
this.boundHandlers.terminalScroll = this.onTerminalScroll.bind(this);
this.scrollElement =
this.terminal.element.querySelector(".xterm-viewport") ||
this.terminal.element;
this.scrollElement.addEventListener(
"scroll",
this.boundHandlers.terminalScroll,
{ passive: true },
);
// Terminal resize listener (for keyboard events)
this.boundHandlers.terminalResize = this.onTerminalResize.bind(this);
this.terminal.onResize(this.boundHandlers.terminalResize);
}
onTerminalTouchStart(event) {
// Handle pinch zoom
if (event.touches.length === 2) {
event.preventDefault();
this.startPinchZoom(event);
return;
}
// Only handle single touch for selection
if (event.touches.length !== 1) return;
const touch = event.touches[0];
this.touchStartTime = Date.now();
this.touchStartPos = { x: touch.clientX, y: touch.clientY };
this.initialTouchPos = { x: touch.clientX, y: touch.clientY };
// If already selecting, don't start new selection
if (this.isSelecting) {
this.isSelectionTouchActive = false;
this.pendingSelectionClearTouch = {
x: touch.clientX,
y: touch.clientY,
moved: false,
};
// Hide menu while user scrolls or repositions, then restore on touch end.
this.hideContextMenu(true);
return;
}
// Check if touch is near screen edge (likely Android back gesture)
if (this.isEdgeGesture(touch)) {
return;
}
// Clear any existing tap-hold timeout
if (this.tapHoldTimeout) {
clearTimeout(this.tapHoldTimeout);
}
// Start tap-hold timer
this.pendingSelectionClearTouch = null;
this.isSelectionTouchActive = false;
this.tapHoldTimeout = setTimeout(() => {
if (!this.isSelecting && !this.isPinching) {
this.startSelection(touch);
}
}, this.options.tapHoldDuration);
}
onTerminalTouchMove(event) {
// Handle pinch zoom
if (event.touches.length === 2) {
event.preventDefault();
this.handlePinchZoom(event);
return;
}
if (event.touches.length !== 1) return;
// Don't handle single touch if we're pinching
if (this.isPinching) return;
const touch = event.touches[0];
const deltaX = Math.abs(touch.clientX - this.touchStartPos.x);
const deltaY = Math.abs(touch.clientY - this.touchStartPos.y);
const horizontalDelta = touch.clientX - this.touchStartPos.x;
const clearTouch = this.pendingSelectionClearTouch;
if (clearTouch) {
const clearDeltaX = Math.abs(touch.clientX - clearTouch.x);
const clearDeltaY = Math.abs(touch.clientY - clearTouch.y);
if (
clearDeltaX > this.options.moveThreshold ||
clearDeltaY > this.options.moveThreshold
) {
clearTouch.moved = true;
}
}
// Check if this looks like a back gesture (started near edge and moving horizontally inward)
if (
this.isEdgeGesture(this.initialTouchPos) &&
Math.abs(horizontalDelta) > deltaY &&
deltaX > this.options.moveThreshold
) {
// This looks like a back gesture, cancel selection
if (this.tapHoldTimeout) {
clearTimeout(this.tapHoldTimeout);
this.tapHoldTimeout = null;
}
return;
}
// If significant movement, cancel tap-hold
if (
deltaX > this.options.moveThreshold ||
deltaY > this.options.moveThreshold
) {
if (this.tapHoldTimeout) {
clearTimeout(this.tapHoldTimeout);
this.tapHoldTimeout = null;
}
// If we're selecting, extend selection
if (
this.isSelecting &&
!this.isHandleDragging &&
this.isSelectionTouchActive
) {
event.preventDefault();
this.extendSelection(touch);
}
}
}
onTerminalTouchEnd(event) {
// Handle end of pinch zoom
if (this.isPinching) {
this.endPinchZoom();
return;
}
if (this.tapHoldTimeout) {
clearTimeout(this.tapHoldTimeout);
this.tapHoldTimeout = null;
}
const shouldClearSelectionByTap =
this.isSelecting &&
!this.isHandleDragging &&
this.pendingSelectionClearTouch &&
!this.pendingSelectionClearTouch.moved &&
!this.isTerminalScrolling &&
!this.selectionProtected;
this.pendingSelectionClearTouch = null;
this.isSelectionTouchActive = false;
if (shouldClearSelectionByTap) {
this.clearSelection();
return;
}
// If we were selecting and not dragging handles, finalize selection
if (this.isSelecting && !this.isHandleDragging) {
if (this.isTerminalScrolling) return;
this.finalizeSelection();
} else if (!this.isSelecting) {
// Only focus terminal on touch end if not selecting and terminal was already focused
// This prevents keyboard popup when just starting selection
const currentlyFocused = this.isTerminalFocused();
if (currentlyFocused) {
// Terminal is already focused, maintain focus
this.terminal.focus();
}
// If terminal wasn't focused, don't focus it (prevents keyboard popup)
}
}
onHandleTouchStart(event) {
event.preventDefault();
event.stopPropagation();
if (event.touches.length !== 1) return;
// Ensure we have the correct handle type
let handleType = event.target.dataset.handleType;
if (!handleType) {
// Fallback to checking which handle was touched
if (
event.target === this.startHandle ||
this.startHandle.contains(event.target)
) {
handleType = "start";
} else if (
event.target === this.endHandle ||
this.endHandle.contains(event.target)
) {
handleType = "end";
}
}
if (!handleType) {
console.warn("Could not determine handle type for drag");
return;
}
this.isHandleDragging = true;
this.dragHandle = handleType;
this.isSelectionTouchActive = false;
this.pendingSelectionClearTouch = null;
// Store the initial touch position for delta calculations
const touch = event.touches[0];
this.initialTouchPos = { x: touch.clientX, y: touch.clientY };
// Update handle appearance - ensure we're updating the correct handle
const targetHandle =
handleType === "start" ? this.startHandle : this.endHandle;
targetHandle.style.cursor = "grabbing";
if (!targetHandle.style.transform.includes("scale")) {
targetHandle.style.transform += " scale(1.2)";
}
}
onHandleTouchMove(event) {
if (!this.isHandleDragging || event.touches.length !== 1) return;
event.preventDefault();
event.stopPropagation();
const touch = event.touches[0];
// Check if there's significant movement before updating selection
const deltaX = Math.abs(touch.clientX - this.initialTouchPos.x);
const deltaY = Math.abs(touch.clientY - this.initialTouchPos.y);
// Only update selection if there's significant movement (prevents micro-movements)
if (
deltaX < this.options.moveThreshold &&
deltaY < this.options.moveThreshold
) {
return;
}
// Apply finger offset for better visibility during drag
const adjustedTouch = {
clientX: touch.clientX,
clientY: touch.clientY - this.options.fingerOffset,
};
const coords = this.touchToTerminalCoords(adjustedTouch);
if (coords) {
// Allow handle swapping but manage it properly
if (this.dragHandle === "start") {
this.selectionStart = coords;
// If start goes past end, swap the handles logically
if (
this.selectionEnd &&
(coords.row > this.selectionEnd.row ||
(coords.row === this.selectionEnd.row &&
coords.col > this.selectionEnd.col))
) {
// Swap internally but keep drag handle reference
const temp = this.selectionStart;
this.selectionStart = this.selectionEnd;
this.selectionEnd = temp;
this.dragHandle = "end"; // Continue dragging as end handle
}
} else {
this.selectionEnd = coords;
// If end goes before start, swap the handles logically
if (
this.selectionStart &&
(coords.row < this.selectionStart.row ||
(coords.row === this.selectionStart.row &&
coords.col < this.selectionStart.col))
) {
// Swap internally but keep drag handle reference
const temp = this.selectionEnd;
this.selectionEnd = this.selectionStart;
this.selectionStart = temp;
this.dragHandle = "start"; // Continue dragging as start handle
}
}
this.updateSelection();
}
}
onHandleTouchEnd(event) {
if (!this.isHandleDragging) return;
event.preventDefault();
event.stopPropagation();
this.isHandleDragging = false;
this.dragHandle = null;
// Reset handle appearance - reset both handles to be safe
const handles = [this.startHandle, this.endHandle];
handles.forEach((handle) => {
handle.style.cursor = "grab";
// More robust transform cleanup
handle.style.transform = handle.style.transform
.replace(/\s*scale\([^)]*\)/g, "")
.trim();
});
this.finalizeSelection();
}
onSelectionChange() {
if (!this.isSelecting) return;
const selection = this.terminal.getSelection();
if (selection && selection.length > 0) {
this.currentSelection = selection;
this.updateHandlePositions();
}
}
onOrientationChange() {
// Update cell dimensions and handle positions after orientation change
setTimeout(() => {
this.updateCellDimensions();
if (this.isSelecting) {
this.updateHandlePositions();
}
}, 100);
}
onTerminalScroll() {
if (!this.isSelecting || this.isHandleDragging) return;
this.isTerminalScrolling = true;
this.hideHandles();
this.hideContextMenu(true);
if (this.scrollEndTimeout) {
clearTimeout(this.scrollEndTimeout);
}
this.scrollEndTimeout = setTimeout(() => {
this.onTerminalScrollEnd();
}, this.scrollEndDelay);
}
onTerminalScrollEnd() {
this.scrollEndTimeout = null;
this.isTerminalScrolling = false;
if (!this.isSelecting || this.isHandleDragging) return;
this.updateHandlePositions();
if (this.contextMenuShouldStayVisible && this.options.showContextMenu) {
this.showContextMenu();
}
}
onTerminalResize(size) {
// Handle terminal resize (keyboard open/close on Android)
setTimeout(() => {
this.updateCellDimensions();
if (this.isSelecting) {
// Don't clear selection if it's protected (during keyboard events)
if (this.selectionProtected) {
// Just update handle positions during protected period
this.updateHandlePositions();
return;
}
// Only clear selection if it becomes invalid due to actual content resize
// Don't clear selection for keyboard-related resizes
if (
this.selectionStart &&
this.selectionEnd &&
(this.selectionStart.row >= size.rows ||
this.selectionEnd.row >= size.rows)
) {
this.clearSelection();
} else if (this.isSelecting) {
// Maintain selection and update handle positions
this.updateHandlePositions();
// Temporarily hide context menu during resize but keep selection
if (this.contextMenu && this.contextMenu.style.display === "flex") {
this.hideContextMenu(true);
}
// Re-show context menu after resize if selection is still active
setTimeout(() => {
if (this.isSelecting && this.options.showContextMenu) {
this.showContextMenu();
}
}, 100);
}
}
}, 50);
}
startSelection(touch) {
const coords = this.touchToTerminalCoords(touch);
if (!coords) return;
// Store initial focus state
this.wasFocusedBeforeSelection = this.isTerminalFocused();
// Protect selection from being cancelled by keyboard events
this.selectionProtected = true;
if (this.protectionTimeout) {
clearTimeout(this.protectionTimeout);
}
// Remove protection after keyboard events have settled
this.protectionTimeout = setTimeout(() => {
this.selectionProtected = false;
}, 1000);
this.isSelecting = true;
this.isSelectionTouchActive = true;
this.pendingSelectionClearTouch = null;
// Try to auto-select word at touch position
const wordBounds = this.getWordBoundsAt(coords);
if (wordBounds) {
// Select the entire word
this.selectionStart = wordBounds.start;
this.selectionEnd = wordBounds.end;
} else {
// Fallback to single character selection
this.selectionStart = coords;
this.selectionEnd = coords;
}
// Clear any existing selection
this.terminal.clearSelection();
// Apply the selection
this.updateSelection();
// Store current selection for immediate access
this.currentSelection = this.terminal.getSelection();
// Show handles
this.showHandles();
if (this.options.showContextMenu) {
this.showContextMenu();
}
// Haptic feedback
if (this.options.hapticFeedback && navigator.vibrate) {
navigator.vibrate(50);
}
// Don't change focus state during selection
// Terminal should maintain its current focus state
}
extendSelection(touch) {
const coords = this.touchToTerminalCoords(touch);
if (!coords) return;
this.selectionEnd = coords;
this.updateSelection();
}
updateSelection() {
if (!this.selectionStart || !this.selectionEnd) return;
const start = this.selectionStart;
const end = this.selectionEnd;
// Ensure start is before end
let startRow = start.row;
let startCol = start.col;
let endRow = end.row;
let endCol = end.col;
if (startRow > endRow || (startRow === endRow && startCol > endCol)) {
[startRow, startCol, endRow, endCol] = [
endRow,
endCol,
startRow,
startCol,
];
}
// Calculate selection length
const length = this.calculateSelectionLength(
startRow,
startCol,
endRow,
endCol,
);
// Clear and set new selection
this.terminal.clearSelection();
this.terminal.select(startCol, startRow, length);
this.updateHandlePositions();
// Ensure context menu stays visible if it should be
if (this.contextMenuShouldStayVisible && this.options.showContextMenu) {
this.showContextMenu();
}
}
calculateSelectionLength(startRow, startCol, endRow, endCol) {
if (startRow === endRow) {
return endCol - startCol + 1;
}
const cols = this.terminal.cols;
let length = cols - startCol; // First row
length += (endRow - startRow - 1) * cols; // Middle rows
length += endCol + 1; // Last row
return length;
}
finalizeSelection() {
if (this.options.showContextMenu && this.currentSelection) {
this.showContextMenu();
}
}
showHandles() {
this.startHandle.style.display = "block";
this.endHandle.style.display = "block";
this.updateHandlePositions();
}
hideHandles() {
this.startHandle.style.display = "none";
this.endHandle.style.display = "none";
}
updateHandlePositions() {
if (!this.selectionStart || !this.selectionEnd) return;
let logicalStart, logicalEnd;
if (
this.selectionStart.row < this.selectionEnd.row ||
(this.selectionStart.row === this.selectionEnd.row &&
this.selectionStart.col <= this.selectionEnd.col)
) {
logicalStart = this.selectionStart;
logicalEnd = this.selectionEnd;
} else {
logicalStart = this.selectionEnd;
logicalEnd = this.selectionStart;
}
const startPos = this.terminalCoordsToPixels(logicalStart);
const endPos = this.terminalCoordsToPixels(logicalEnd);
// Show/hide start handle at logical start position
if (startPos) {
this.startHandle.style.display = "block";
this.startHandle.style.left = `${startPos.x}px`;
this.startHandle.style.top = `${startPos.y + this.cellDimensions.height + 4}px`;
} else {
this.startHandle.style.display = "none";
}
// Show/hide end handle at logical end position
if (endPos) {
this.endHandle.style.display = "block";
this.endHandle.style.left = `${endPos.x + this.cellDimensions.width}px`;
this.endHandle.style.top = `${endPos.y + this.cellDimensions.height + 4}px`;
} else {
this.endHandle.style.display = "none";
}
}
showContextMenu() {
if (!this.contextMenu) {
this.createContextMenu();
}
// Mark that context menu should stay visible
this.contextMenuShouldStayVisible = true;
// Position context menu - center it on selection (or fallback to center).
const startPos = this.selectionStart
? this.terminalCoordsToPixels(this.selectionStart)
: null;
const endPos = this.selectionEnd
? this.terminalCoordsToPixels(this.selectionEnd)
: null;
const menuWidth = this.contextMenu.offsetWidth || 200;
const menuHeight = this.contextMenu.offsetHeight || 50;
const containerRect = this.container.getBoundingClientRect();
let menuX;
let menuY;
if (startPos || endPos) {
let centerX;
let baseY;
if (startPos && endPos) {
centerX = (startPos.x + endPos.x) / 2;
baseY = Math.max(startPos.y, endPos.y);
} else if (startPos) {
centerX = startPos.x;
baseY = startPos.y;
} else {
centerX = endPos.x;
baseY = endPos.y;
}
menuX = centerX - menuWidth / 2;
menuY = baseY + this.cellDimensions.height + 40;
// If menu would overflow below, prefer placing it above selection.
const maxY = containerRect.height - menuHeight - 10;
if (menuY > maxY) {
const topY =
startPos && endPos ? Math.min(startPos.y, endPos.y) : baseY;
menuY = topY - menuHeight - 10;
}
} else {
menuX = (containerRect.width - menuWidth) / 2;
menuY = containerRect.height - menuHeight - 20;
}
const minX = 10;
const maxX = containerRect.width - menuWidth - 10;
menuX = Math.max(minX, Math.min(menuX, maxX));
const minY = 10;
const maxY = containerRect.height - menuHeight - 10;
menuY = Math.max(minY, Math.min(menuY, maxY));
this.contextMenu.style.left = `${menuX}px`;
this.contextMenu.style.top = `${menuY}px`;
this.contextMenu.style.display = "flex";
}
createContextMenu() {
this.contextMenu = document.createElement("div");
this.contextMenu.className = "terminal-context-menu";
// Add menu items
const menuItems = [
{ label: strings["copy"], action: this.copySelection.bind(this) },
{ label: strings["paste"], action: this.pasteFromClipboard.bind(this) },
{
label: `${strings["more"] || "More"}...`,
action: this.showMoreOptions.bind(this),
},
];
menuItems.forEach((item) => {
const button = document.createElement("button");
button.textContent = item.label;
// Flag to prevent multiple activations
let actionExecuted = false;
// Handle touch interactions
button.addEventListener("touchstart", (e) => {
e.preventDefault();
e.stopPropagation();
actionExecuted = false;
});