@gkoreli/ghostty-vt-js 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -0
  3. package/THIRD_PARTY_NOTICES.md +45 -0
  4. package/dist/browser-terminal/buffer.d.ts +93 -0
  5. package/dist/browser-terminal/buffer.d.ts.map +1 -0
  6. package/dist/browser-terminal/buffer.js +337 -0
  7. package/dist/browser-terminal/buffer.js.map +1 -0
  8. package/dist/browser-terminal/encoding.d.ts +17 -0
  9. package/dist/browser-terminal/encoding.d.ts.map +1 -0
  10. package/dist/browser-terminal/encoding.js +22 -0
  11. package/dist/browser-terminal/encoding.js.map +1 -0
  12. package/dist/browser-terminal/event-emitter.d.ts +8 -0
  13. package/dist/browser-terminal/event-emitter.d.ts.map +1 -0
  14. package/dist/browser-terminal/event-emitter.js +27 -0
  15. package/dist/browser-terminal/event-emitter.js.map +1 -0
  16. package/dist/browser-terminal/frame-hold.d.ts +13 -0
  17. package/dist/browser-terminal/frame-hold.d.ts.map +1 -0
  18. package/dist/browser-terminal/frame-hold.js +17 -0
  19. package/dist/browser-terminal/frame-hold.js.map +1 -0
  20. package/dist/browser-terminal/geometry.d.ts +229 -0
  21. package/dist/browser-terminal/geometry.d.ts.map +1 -0
  22. package/dist/browser-terminal/geometry.js +299 -0
  23. package/dist/browser-terminal/geometry.js.map +1 -0
  24. package/dist/browser-terminal/ghostty.d.ts +478 -0
  25. package/dist/browser-terminal/ghostty.d.ts.map +1 -0
  26. package/dist/browser-terminal/ghostty.js +1212 -0
  27. package/dist/browser-terminal/ghostty.js.map +1 -0
  28. package/dist/browser-terminal/gpu/adapter.d.ts +70 -0
  29. package/dist/browser-terminal/gpu/adapter.d.ts.map +1 -0
  30. package/dist/browser-terminal/gpu/adapter.js +260 -0
  31. package/dist/browser-terminal/gpu/adapter.js.map +1 -0
  32. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.d.ts +33 -0
  33. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.d.ts.map +1 -0
  34. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.js +159 -0
  35. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.js.map +1 -0
  36. package/dist/browser-terminal/gpu/core/context-loss-watchdog.d.ts +35 -0
  37. package/dist/browser-terminal/gpu/core/context-loss-watchdog.d.ts.map +1 -0
  38. package/dist/browser-terminal/gpu/core/context-loss-watchdog.js +73 -0
  39. package/dist/browser-terminal/gpu/core/context-loss-watchdog.js.map +1 -0
  40. package/dist/browser-terminal/gpu/core/frame.d.ts +68 -0
  41. package/dist/browser-terminal/gpu/core/frame.d.ts.map +1 -0
  42. package/dist/browser-terminal/gpu/core/frame.js +167 -0
  43. package/dist/browser-terminal/gpu/core/frame.js.map +1 -0
  44. package/dist/browser-terminal/gpu/core/glyph-atlas.d.ts +136 -0
  45. package/dist/browser-terminal/gpu/core/glyph-atlas.d.ts.map +1 -0
  46. package/dist/browser-terminal/gpu/core/glyph-atlas.js +281 -0
  47. package/dist/browser-terminal/gpu/core/glyph-atlas.js.map +1 -0
  48. package/dist/browser-terminal/gpu/core/procedural-shapes.d.ts +24 -0
  49. package/dist/browser-terminal/gpu/core/procedural-shapes.d.ts.map +1 -0
  50. package/dist/browser-terminal/gpu/core/procedural-shapes.js +316 -0
  51. package/dist/browser-terminal/gpu/core/procedural-shapes.js.map +1 -0
  52. package/dist/browser-terminal/gpu/core/webgl2-renderer.d.ts +107 -0
  53. package/dist/browser-terminal/gpu/core/webgl2-renderer.d.ts.map +1 -0
  54. package/dist/browser-terminal/gpu/core/webgl2-renderer.js +698 -0
  55. package/dist/browser-terminal/gpu/core/webgl2-renderer.js.map +1 -0
  56. package/dist/browser-terminal/gpu/create-renderer.d.ts +15 -0
  57. package/dist/browser-terminal/gpu/create-renderer.d.ts.map +1 -0
  58. package/dist/browser-terminal/gpu/create-renderer.js +33 -0
  59. package/dist/browser-terminal/gpu/create-renderer.js.map +1 -0
  60. package/dist/browser-terminal/index.d.ts +47 -0
  61. package/dist/browser-terminal/index.d.ts.map +1 -0
  62. package/dist/browser-terminal/index.js +75 -0
  63. package/dist/browser-terminal/index.js.map +1 -0
  64. package/dist/browser-terminal/input-handler.d.ts +262 -0
  65. package/dist/browser-terminal/input-handler.d.ts.map +1 -0
  66. package/dist/browser-terminal/input-handler.js +978 -0
  67. package/dist/browser-terminal/input-handler.js.map +1 -0
  68. package/dist/browser-terminal/interfaces.d.ts +230 -0
  69. package/dist/browser-terminal/interfaces.d.ts.map +1 -0
  70. package/dist/browser-terminal/interfaces.js +5 -0
  71. package/dist/browser-terminal/interfaces.js.map +1 -0
  72. package/dist/browser-terminal/link-detector.d.ts +76 -0
  73. package/dist/browser-terminal/link-detector.d.ts.map +1 -0
  74. package/dist/browser-terminal/link-detector.js +165 -0
  75. package/dist/browser-terminal/link-detector.js.map +1 -0
  76. package/dist/browser-terminal/providers/osc8-link-provider.d.ts +56 -0
  77. package/dist/browser-terminal/providers/osc8-link-provider.d.ts.map +1 -0
  78. package/dist/browser-terminal/providers/osc8-link-provider.js +204 -0
  79. package/dist/browser-terminal/providers/osc8-link-provider.js.map +1 -0
  80. package/dist/browser-terminal/providers/url-regex-provider.d.ts +68 -0
  81. package/dist/browser-terminal/providers/url-regex-provider.d.ts.map +1 -0
  82. package/dist/browser-terminal/providers/url-regex-provider.js +107 -0
  83. package/dist/browser-terminal/providers/url-regex-provider.js.map +1 -0
  84. package/dist/browser-terminal/renderer-interface.d.ts +59 -0
  85. package/dist/browser-terminal/renderer-interface.d.ts.map +1 -0
  86. package/dist/browser-terminal/renderer-interface.js +2 -0
  87. package/dist/browser-terminal/renderer-interface.js.map +1 -0
  88. package/dist/browser-terminal/renderer.d.ts +254 -0
  89. package/dist/browser-terminal/renderer.d.ts.map +1 -0
  90. package/dist/browser-terminal/renderer.js +905 -0
  91. package/dist/browser-terminal/renderer.js.map +1 -0
  92. package/dist/browser-terminal/scrollbar-overlay.d.ts +45 -0
  93. package/dist/browser-terminal/scrollbar-overlay.d.ts.map +1 -0
  94. package/dist/browser-terminal/scrollbar-overlay.js +89 -0
  95. package/dist/browser-terminal/scrollbar-overlay.js.map +1 -0
  96. package/dist/browser-terminal/selection-manager.d.ts +180 -0
  97. package/dist/browser-terminal/selection-manager.d.ts.map +1 -0
  98. package/dist/browser-terminal/selection-manager.js +913 -0
  99. package/dist/browser-terminal/selection-manager.js.map +1 -0
  100. package/dist/browser-terminal/terminal.d.ts +423 -0
  101. package/dist/browser-terminal/terminal.d.ts.map +1 -0
  102. package/dist/browser-terminal/terminal.js +1754 -0
  103. package/dist/browser-terminal/terminal.js.map +1 -0
  104. package/dist/browser-terminal/types.d.ts +595 -0
  105. package/dist/browser-terminal/types.d.ts.map +1 -0
  106. package/dist/browser-terminal/types.js +467 -0
  107. package/dist/browser-terminal/types.js.map +1 -0
  108. package/dist/browser-terminal/viewport-scroller.d.ts +94 -0
  109. package/dist/browser-terminal/viewport-scroller.d.ts.map +1 -0
  110. package/dist/browser-terminal/viewport-scroller.js +159 -0
  111. package/dist/browser-terminal/viewport-scroller.js.map +1 -0
  112. package/dist/browser-terminal/vt/effects.d.ts +114 -0
  113. package/dist/browser-terminal/vt/effects.d.ts.map +1 -0
  114. package/dist/browser-terminal/vt/effects.js +143 -0
  115. package/dist/browser-terminal/vt/effects.js.map +1 -0
  116. package/dist/browser-terminal/vt/enums.d.ts +155 -0
  117. package/dist/browser-terminal/vt/enums.d.ts.map +1 -0
  118. package/dist/browser-terminal/vt/enums.js +161 -0
  119. package/dist/browser-terminal/vt/enums.js.map +1 -0
  120. package/dist/browser-terminal/vt/mouse.d.ts +166 -0
  121. package/dist/browser-terminal/vt/mouse.d.ts.map +1 -0
  122. package/dist/browser-terminal/vt/mouse.js +259 -0
  123. package/dist/browser-terminal/vt/mouse.js.map +1 -0
  124. package/dist/browser-terminal/vt/paste.d.ts +53 -0
  125. package/dist/browser-terminal/vt/paste.d.ts.map +1 -0
  126. package/dist/browser-terminal/vt/paste.js +89 -0
  127. package/dist/browser-terminal/vt/paste.js.map +1 -0
  128. package/dist/browser-terminal/vt/render-state.d.ts +208 -0
  129. package/dist/browser-terminal/vt/render-state.d.ts.map +1 -0
  130. package/dist/browser-terminal/vt/render-state.js +776 -0
  131. package/dist/browser-terminal/vt/render-state.js.map +1 -0
  132. package/dist/browser-terminal/vt/style.d.ts +54 -0
  133. package/dist/browser-terminal/vt/style.d.ts.map +1 -0
  134. package/dist/browser-terminal/vt/style.js +92 -0
  135. package/dist/browser-terminal/vt/style.js.map +1 -0
  136. package/dist/browser-terminal/wasm-loader.d.ts +39 -0
  137. package/dist/browser-terminal/wasm-loader.d.ts.map +1 -0
  138. package/dist/browser-terminal/wasm-loader.js +73 -0
  139. package/dist/browser-terminal/wasm-loader.js.map +1 -0
  140. package/dist/browser-terminal/write-buffer.d.ts +40 -0
  141. package/dist/browser-terminal/write-buffer.d.ts.map +1 -0
  142. package/dist/browser-terminal/write-buffer.js +144 -0
  143. package/dist/browser-terminal/write-buffer.js.map +1 -0
  144. package/dist/protocol/index.d.ts +135 -0
  145. package/dist/protocol/index.d.ts.map +1 -0
  146. package/dist/protocol/index.js +76 -0
  147. package/dist/protocol/index.js.map +1 -0
  148. package/dist/react/index.d.ts +59 -0
  149. package/dist/react/index.d.ts.map +1 -0
  150. package/dist/react/index.js +146 -0
  151. package/dist/react/index.js.map +1 -0
  152. package/dist/server/index.d.ts +130 -0
  153. package/dist/server/index.d.ts.map +1 -0
  154. package/dist/server/index.js +191 -0
  155. package/dist/server/index.js.map +1 -0
  156. package/dist/terminal-screen-emulator/emulator.d.ts +66 -0
  157. package/dist/terminal-screen-emulator/emulator.d.ts.map +1 -0
  158. package/dist/terminal-screen-emulator/emulator.js +286 -0
  159. package/dist/terminal-screen-emulator/emulator.js.map +1 -0
  160. package/dist/terminal-screen-emulator/index.d.ts +82 -0
  161. package/dist/terminal-screen-emulator/index.d.ts.map +1 -0
  162. package/dist/terminal-screen-emulator/index.js +92 -0
  163. package/dist/terminal-screen-emulator/index.js.map +1 -0
  164. package/dist/terminal-screen-emulator/types.d.ts +382 -0
  165. package/dist/terminal-screen-emulator/types.d.ts.map +1 -0
  166. package/dist/terminal-screen-emulator/types.js +91 -0
  167. package/dist/terminal-screen-emulator/types.js.map +1 -0
  168. package/dist/terminal-screen-emulator/wasm-loader.d.ts +71 -0
  169. package/dist/terminal-screen-emulator/wasm-loader.d.ts.map +1 -0
  170. package/dist/terminal-screen-emulator/wasm-loader.js +162 -0
  171. package/dist/terminal-screen-emulator/wasm-loader.js.map +1 -0
  172. package/dist/themes/index.d.ts +6 -0
  173. package/dist/themes/index.d.ts.map +1 -0
  174. package/dist/themes/index.js +51 -0
  175. package/dist/themes/index.js.map +1 -0
  176. package/dist/wasm/alloc.d.ts +170 -0
  177. package/dist/wasm/alloc.d.ts.map +1 -0
  178. package/dist/wasm/alloc.js +307 -0
  179. package/dist/wasm/alloc.js.map +1 -0
  180. package/dist/wasm/compile.d.ts +73 -0
  181. package/dist/wasm/compile.d.ts.map +1 -0
  182. package/dist/wasm/compile.js +82 -0
  183. package/dist/wasm/compile.js.map +1 -0
  184. package/dist/wasm/exports.d.ts +234 -0
  185. package/dist/wasm/exports.d.ts.map +1 -0
  186. package/dist/wasm/exports.js +15 -0
  187. package/dist/wasm/exports.js.map +1 -0
  188. package/dist/wasm/fn-table.d.ts +119 -0
  189. package/dist/wasm/fn-table.d.ts.map +1 -0
  190. package/dist/wasm/fn-table.js +168 -0
  191. package/dist/wasm/fn-table.js.map +1 -0
  192. package/dist/wasm/memory.d.ts +59 -0
  193. package/dist/wasm/memory.d.ts.map +1 -0
  194. package/dist/wasm/memory.js +89 -0
  195. package/dist/wasm/memory.js.map +1 -0
  196. package/dist/wasm/type-layouts.d.ts +61 -0
  197. package/dist/wasm/type-layouts.d.ts.map +1 -0
  198. package/dist/wasm/type-layouts.js +32 -0
  199. package/dist/wasm/type-layouts.js.map +1 -0
  200. package/package.json +94 -0
  201. package/wasm/ghostty-vt.wasm +0 -0
@@ -0,0 +1,913 @@
1
+ // Portions originally derived from coder/ghostty-web (MIT — see ./LICENSE):
2
+ // https://github.com/coder/ghostty-web/blob/6a1a50df5b4f6b34d1b1de10fad3a0fc811bfbc0/lib/selection-manager.ts
3
+ // Substantially rewritten since; this file is ours and does not track that project.
4
+ /**
5
+ * Selection Manager - Handles text selection in the terminal
6
+ *
7
+ * Features:
8
+ * - Mouse drag selection
9
+ * - Double-click word selection
10
+ * - Text extraction from terminal buffer
11
+ * - Automatic clipboard copy
12
+ * - Visual selection highlighting (integrated into CanvasRenderer cell rendering)
13
+ * - Auto-scroll during drag selection
14
+ */
15
+ import { EventEmitter } from './event-emitter.js';
16
+ // ============================================================================
17
+ // SelectionManager Class
18
+ // ============================================================================
19
+ export class SelectionManager {
20
+ terminal;
21
+ renderer;
22
+ wasmTerm;
23
+ textarea;
24
+ // Selection state - coordinates are in ABSOLUTE buffer space (viewportY + viewportRow)
25
+ // This ensures selection persists correctly when scrolling
26
+ selectionStart = null;
27
+ selectionEnd = null;
28
+ isSelecting = false;
29
+ mouseDownX = 0;
30
+ mouseDownY = 0;
31
+ dragThresholdMet = false;
32
+ mouseDownTarget = null; // Track where mousedown occurred
33
+ // Track rows that need redraw for clearing old selection
34
+ // Using a Set prevents the overwrite bug where mousemove would clobber
35
+ // the rows marked by clearSelection()
36
+ dirtySelectionRows = new Set();
37
+ // Event emitter
38
+ selectionChangedEmitter = new EventEmitter();
39
+ // Store bound event handlers for cleanup
40
+ boundMouseUpHandler = null;
41
+ boundContextMenuHandler = null;
42
+ boundClickHandler = null;
43
+ boundDocumentMouseMoveHandler = null;
44
+ // Auto-scroll state for drag selection
45
+ autoScrollInterval = null;
46
+ autoScrollDirection = 0; // -1 = up, 0 = none, 1 = down
47
+ static AUTO_SCROLL_EDGE_SIZE = 30; // pixels from edge to trigger scroll
48
+ /**
49
+ * Get current viewport Y position (how many lines scrolled into history)
50
+ */
51
+ getViewportY() {
52
+ const rawViewportY = typeof this.terminal.getViewportY === 'function'
53
+ ? this.terminal.getViewportY()
54
+ : this.terminal.viewportY || 0;
55
+ return Math.max(0, Math.floor(rawViewportY));
56
+ }
57
+ /**
58
+ * Convert viewport row to absolute buffer row
59
+ * Absolute row is an index into combined buffer: scrollback (0 to len-1) + screen (len to len+rows-1)
60
+ */
61
+ viewportRowToAbsolute(viewportRow) {
62
+ const scrollbackLength = this.wasmTerm.getScrollbackLength();
63
+ const viewportY = this.getViewportY();
64
+ return scrollbackLength + viewportRow - viewportY;
65
+ }
66
+ /**
67
+ * Convert absolute buffer row to viewport row (may be outside visible range)
68
+ */
69
+ absoluteRowToViewport(absoluteRow) {
70
+ const scrollbackLength = this.wasmTerm.getScrollbackLength();
71
+ const viewportY = this.getViewportY();
72
+ return absoluteRow - scrollbackLength + viewportY;
73
+ }
74
+ static AUTO_SCROLL_SPEED = 3; // lines per interval
75
+ static AUTO_SCROLL_INTERVAL = 50; // ms between scroll steps
76
+ constructor(terminal, renderer, wasmTerm, textarea) {
77
+ this.terminal = terminal;
78
+ this.renderer = renderer;
79
+ this.wasmTerm = wasmTerm;
80
+ this.textarea = textarea;
81
+ // Attach mouse event listeners
82
+ this.attachEventListeners();
83
+ }
84
+ // ==========================================================================
85
+ // Public API
86
+ // ==========================================================================
87
+ /**
88
+ * Get the selected text as a string
89
+ */
90
+ getSelection() {
91
+ if (!this.selectionStart || !this.selectionEnd)
92
+ return '';
93
+ // Get absolute row coordinates (not clamped to viewport)
94
+ let { col: startCol, absoluteRow: startAbsRow } = this.selectionStart;
95
+ let { col: endCol, absoluteRow: endAbsRow } = this.selectionEnd;
96
+ // Swap if selection goes backwards
97
+ if (startAbsRow > endAbsRow || (startAbsRow === endAbsRow && startCol > endCol)) {
98
+ [startCol, endCol] = [endCol, startCol];
99
+ [startAbsRow, endAbsRow] = [endAbsRow, startAbsRow];
100
+ }
101
+ const scrollbackLength = this.wasmTerm.getScrollbackLength();
102
+ let text = '';
103
+ for (let absRow = startAbsRow; absRow <= endAbsRow; absRow++) {
104
+ // Fetch line based on absolute row position
105
+ // Absolute row < scrollbackLength means it's in scrollback
106
+ // Absolute row >= scrollbackLength means it's in the screen buffer
107
+ let line = null;
108
+ if (absRow < scrollbackLength) {
109
+ // Row is in scrollback
110
+ line = this.wasmTerm.getScrollbackLine(absRow);
111
+ }
112
+ else {
113
+ // Row is in screen buffer
114
+ const screenRow = absRow - scrollbackLength;
115
+ line = this.wasmTerm.getLine(screenRow);
116
+ }
117
+ if (!line)
118
+ continue;
119
+ // Track the last non-empty column for trimming trailing spaces
120
+ let lastNonEmpty = -1;
121
+ // Determine column range for this row
122
+ const colStart = absRow === startAbsRow ? startCol : 0;
123
+ const colEnd = absRow === endAbsRow ? endCol : line.length - 1;
124
+ // Build the line text
125
+ let lineText = '';
126
+ for (let col = colStart; col <= colEnd; col++) {
127
+ const cell = line[col];
128
+ if (cell && cell.codepoint !== 0) {
129
+ // Use grapheme lookup for cells with multi-codepoint characters
130
+ let char;
131
+ if (cell.grapheme_len > 0) {
132
+ // Row is in scrollback or screen - determine which and use appropriate method
133
+ if (absRow < scrollbackLength) {
134
+ char = this.wasmTerm.getScrollbackGraphemeString(absRow, col);
135
+ }
136
+ else {
137
+ const screenRow = absRow - scrollbackLength;
138
+ char = this.wasmTerm.getGraphemeString(screenRow, col);
139
+ }
140
+ }
141
+ else {
142
+ char = String.fromCodePoint(cell.codepoint);
143
+ }
144
+ lineText += char;
145
+ if (char.trim()) {
146
+ lastNonEmpty = lineText.length;
147
+ }
148
+ }
149
+ else {
150
+ lineText += ' ';
151
+ }
152
+ }
153
+ // Trim trailing spaces from each line
154
+ if (lastNonEmpty >= 0) {
155
+ lineText = lineText.substring(0, lastNonEmpty);
156
+ }
157
+ else {
158
+ lineText = '';
159
+ }
160
+ text += lineText;
161
+ // Add newline between rows (but not after the last row)
162
+ if (absRow < endAbsRow) {
163
+ text += '\n';
164
+ }
165
+ }
166
+ return text;
167
+ }
168
+ /**
169
+ * Check if there's an active selection
170
+ */
171
+ hasSelection() {
172
+ if (!this.selectionStart || !this.selectionEnd)
173
+ return false;
174
+ // Don't report selection until drag threshold is met (prevents flash on click)
175
+ if (this.isSelecting && !this.dragThresholdMet)
176
+ return false;
177
+ return true;
178
+ }
179
+ /**
180
+ * Copy the current selection to clipboard
181
+ * @returns true if there was text to copy, false otherwise
182
+ */
183
+ copySelection() {
184
+ if (!this.hasSelection())
185
+ return false;
186
+ const text = this.getSelection();
187
+ if (text) {
188
+ this.copyToClipboard(text);
189
+ return true;
190
+ }
191
+ return false;
192
+ }
193
+ /**
194
+ * Clear the selection
195
+ */
196
+ clearSelection() {
197
+ if (!this.hasSelection())
198
+ return;
199
+ // Mark current selection rows as dirty for redraw
200
+ const coords = this.normalizeSelection();
201
+ if (coords) {
202
+ for (let row = coords.startRow; row <= coords.endRow; row++) {
203
+ this.dirtySelectionRows.add(row);
204
+ }
205
+ }
206
+ this.selectionStart = null;
207
+ this.selectionEnd = null;
208
+ this.isSelecting = false;
209
+ // Force redraw of previously selected lines to clear the overlay
210
+ this.requestRender();
211
+ }
212
+ /**
213
+ * Select all text in the terminal
214
+ */
215
+ selectAll() {
216
+ const dims = this.wasmTerm.getDimensions();
217
+ const viewportY = this.getViewportY();
218
+ this.selectionStart = { col: 0, absoluteRow: viewportY };
219
+ this.selectionEnd = { col: dims.cols - 1, absoluteRow: viewportY + dims.rows - 1 };
220
+ this.requestRender();
221
+ this.selectionChangedEmitter.fire();
222
+ }
223
+ /**
224
+ * Select text at specific column and row with length
225
+ * xterm.js compatible API
226
+ */
227
+ select(column, row, length) {
228
+ // Clamp to valid ranges
229
+ const dims = this.wasmTerm.getDimensions();
230
+ row = Math.max(0, Math.min(row, dims.rows - 1));
231
+ column = Math.max(0, Math.min(column, dims.cols - 1));
232
+ // Calculate end position
233
+ let endRow = row;
234
+ let endCol = column + length - 1;
235
+ // Handle wrapping if selection extends past end of line
236
+ while (endCol >= dims.cols) {
237
+ endCol -= dims.cols;
238
+ endRow++;
239
+ }
240
+ // Clamp end row
241
+ endRow = Math.min(endRow, dims.rows - 1);
242
+ // Convert viewport rows to absolute rows
243
+ const viewportY = this.getViewportY();
244
+ this.selectionStart = { col: column, absoluteRow: viewportY + row };
245
+ this.selectionEnd = { col: endCol, absoluteRow: viewportY + endRow };
246
+ this.requestRender();
247
+ this.selectionChangedEmitter.fire();
248
+ }
249
+ /**
250
+ * Select entire lines from start to end
251
+ * xterm.js compatible API
252
+ */
253
+ selectLines(start, end) {
254
+ const dims = this.wasmTerm.getDimensions();
255
+ // Clamp to valid row ranges
256
+ start = Math.max(0, Math.min(start, dims.rows - 1));
257
+ end = Math.max(0, Math.min(end, dims.rows - 1));
258
+ // Ensure start <= end
259
+ if (start > end) {
260
+ [start, end] = [end, start];
261
+ }
262
+ // Convert viewport rows to absolute rows
263
+ this.selectionStart = { col: 0, absoluteRow: this.viewportRowToAbsolute(start) };
264
+ this.selectionEnd = { col: dims.cols - 1, absoluteRow: this.viewportRowToAbsolute(end) };
265
+ this.requestRender();
266
+ this.selectionChangedEmitter.fire();
267
+ }
268
+ /**
269
+ * Get selection position as buffer range
270
+ * xterm.js compatible API
271
+ */
272
+ getSelectionPosition() {
273
+ const coords = this.normalizeSelection();
274
+ if (!coords)
275
+ return undefined;
276
+ return {
277
+ start: { x: coords.startCol, y: coords.startRow },
278
+ end: { x: coords.endCol, y: coords.endRow },
279
+ };
280
+ }
281
+ /**
282
+ * Deselect all text
283
+ * xterm.js compatible API
284
+ */
285
+ deselect() {
286
+ this.clearSelection();
287
+ this.selectionChangedEmitter.fire();
288
+ }
289
+ /**
290
+ * Focus the terminal (make it receive keyboard input)
291
+ */
292
+ focus() {
293
+ const canvas = this.renderer.getCanvas();
294
+ if (canvas.parentElement) {
295
+ canvas.parentElement.focus();
296
+ }
297
+ }
298
+ /**
299
+ * Get current selection coordinates (for rendering)
300
+ */
301
+ getSelectionCoords() {
302
+ return this.normalizeSelection();
303
+ }
304
+ /**
305
+ * Get dirty selection rows that need redraw (for clearing old highlight)
306
+ */
307
+ getDirtySelectionRows() {
308
+ return this.dirtySelectionRows;
309
+ }
310
+ /**
311
+ * Clear the dirty selection rows tracking (after redraw)
312
+ */
313
+ clearDirtySelectionRows() {
314
+ this.dirtySelectionRows.clear();
315
+ }
316
+ /**
317
+ * Get selection change event accessor
318
+ */
319
+ get onSelectionChange() {
320
+ return this.selectionChangedEmitter.event;
321
+ }
322
+ /**
323
+ * Cleanup resources
324
+ */
325
+ dispose() {
326
+ this.selectionChangedEmitter.dispose();
327
+ // Stop auto-scroll if active
328
+ this.stopAutoScroll();
329
+ // Clean up document event listener
330
+ if (this.boundMouseUpHandler) {
331
+ document.removeEventListener('mouseup', this.boundMouseUpHandler);
332
+ this.boundMouseUpHandler = null;
333
+ }
334
+ // Clean up document mousemove listener
335
+ if (this.boundDocumentMouseMoveHandler) {
336
+ document.removeEventListener('mousemove', this.boundDocumentMouseMoveHandler);
337
+ this.boundDocumentMouseMoveHandler = null;
338
+ }
339
+ // Clean up context menu event listener
340
+ if (this.boundContextMenuHandler) {
341
+ const canvas = this.renderer.getCanvas();
342
+ canvas.removeEventListener('contextmenu', this.boundContextMenuHandler);
343
+ this.boundContextMenuHandler = null;
344
+ }
345
+ // Clean up document click listener
346
+ if (this.boundClickHandler) {
347
+ document.removeEventListener('click', this.boundClickHandler);
348
+ this.boundClickHandler = null;
349
+ }
350
+ // Canvas event listeners will be cleaned up when canvas is removed from DOM
351
+ }
352
+ // ==========================================================================
353
+ // Private Methods
354
+ // ==========================================================================
355
+ /**
356
+ * Attach mouse event listeners to canvas
357
+ */
358
+ attachEventListeners() {
359
+ const canvas = this.renderer.getCanvas();
360
+ // Mouse down - start selection or clear existing
361
+ canvas.addEventListener('mousedown', (e) => {
362
+ if (e.button === 0) {
363
+ // Left click only
364
+ // CRITICAL: Focus the terminal so it can receive keyboard input
365
+ // The canvas doesn't have tabindex, but the parent container does
366
+ if (canvas.parentElement) {
367
+ canvas.parentElement.focus();
368
+ }
369
+ const cell = this.pixelToCell(e.offsetX, e.offsetY);
370
+ // Always clear previous selection on new click
371
+ const hadSelection = this.hasSelection();
372
+ if (hadSelection) {
373
+ this.clearSelection();
374
+ }
375
+ // Start new selection (convert to absolute coordinates)
376
+ const absoluteRow = this.viewportRowToAbsolute(cell.row);
377
+ this.selectionStart = { col: cell.col, absoluteRow };
378
+ this.selectionEnd = { col: cell.col, absoluteRow };
379
+ this.isSelecting = true;
380
+ this.mouseDownX = e.offsetX;
381
+ this.mouseDownY = e.offsetY;
382
+ this.dragThresholdMet = false;
383
+ }
384
+ });
385
+ // Mouse move on canvas - update selection
386
+ canvas.addEventListener('mousemove', (e) => {
387
+ if (this.isSelecting) {
388
+ // Check if drag threshold has been met
389
+ if (!this.dragThresholdMet) {
390
+ const dx = e.offsetX - this.mouseDownX;
391
+ const dy = e.offsetY - this.mouseDownY;
392
+ // Use 50% of cell width as threshold to scale with font size
393
+ const threshold = this.renderer.getMetrics().width * 0.5;
394
+ if (dx * dx + dy * dy < threshold * threshold) {
395
+ return; // Below threshold, ignore
396
+ }
397
+ this.dragThresholdMet = true;
398
+ }
399
+ // Mark current selection rows as dirty before updating
400
+ this.markCurrentSelectionDirty();
401
+ const cell = this.pixelToCell(e.offsetX, e.offsetY);
402
+ const absoluteRow = this.viewportRowToAbsolute(cell.row);
403
+ this.selectionEnd = { col: cell.col, absoluteRow };
404
+ this.requestRender();
405
+ // Check if near edges for auto-scroll
406
+ this.updateAutoScroll(e.offsetY, canvas.clientHeight);
407
+ }
408
+ });
409
+ // Mouse leave - check for auto-scroll when leaving canvas during drag
410
+ canvas.addEventListener('mouseleave', (e) => {
411
+ if (this.isSelecting) {
412
+ // Determine scroll direction based on where mouse left
413
+ const rect = canvas.getBoundingClientRect();
414
+ if (e.clientY < rect.top) {
415
+ this.startAutoScroll(-1); // Scroll up
416
+ }
417
+ else if (e.clientY > rect.bottom) {
418
+ this.startAutoScroll(1); // Scroll down
419
+ }
420
+ }
421
+ });
422
+ // Mouse enter - stop auto-scroll when mouse returns to canvas
423
+ canvas.addEventListener('mouseenter', () => {
424
+ if (this.isSelecting) {
425
+ this.stopAutoScroll();
426
+ }
427
+ });
428
+ // Document-level mousemove for tracking mouse position during drag outside canvas
429
+ this.boundDocumentMouseMoveHandler = (e) => {
430
+ if (this.isSelecting) {
431
+ // Check drag threshold (same as canvas mousemove)
432
+ if (!this.dragThresholdMet) {
433
+ const dx = e.clientX - (canvas.getBoundingClientRect().left + this.mouseDownX);
434
+ const dy = e.clientY - (canvas.getBoundingClientRect().top + this.mouseDownY);
435
+ const threshold = this.renderer.getMetrics().width * 0.5;
436
+ if (dx * dx + dy * dy < threshold * threshold) {
437
+ return;
438
+ }
439
+ this.dragThresholdMet = true;
440
+ }
441
+ const rect = canvas.getBoundingClientRect();
442
+ // Update selection based on clamped position
443
+ const clampedX = Math.max(rect.left, Math.min(e.clientX, rect.right));
444
+ const clampedY = Math.max(rect.top, Math.min(e.clientY, rect.bottom));
445
+ // Convert to canvas-relative coordinates
446
+ const offsetX = clampedX - rect.left;
447
+ const offsetY = clampedY - rect.top;
448
+ // Only update if mouse is outside the canvas
449
+ if (e.clientX < rect.left ||
450
+ e.clientX > rect.right ||
451
+ e.clientY < rect.top ||
452
+ e.clientY > rect.bottom) {
453
+ // Update auto-scroll direction based on mouse position
454
+ if (e.clientY < rect.top) {
455
+ this.startAutoScroll(-1);
456
+ }
457
+ else if (e.clientY > rect.bottom) {
458
+ this.startAutoScroll(1);
459
+ }
460
+ else {
461
+ this.stopAutoScroll();
462
+ }
463
+ // Only update selection position if NOT auto-scrolling
464
+ // During auto-scroll, the scroll handler extends the selection
465
+ if (this.autoScrollDirection === 0) {
466
+ // Mark current selection rows as dirty before updating
467
+ this.markCurrentSelectionDirty();
468
+ const cell = this.pixelToCell(offsetX, offsetY);
469
+ const absoluteRow = this.viewportRowToAbsolute(cell.row);
470
+ this.selectionEnd = { col: cell.col, absoluteRow };
471
+ this.requestRender();
472
+ }
473
+ }
474
+ }
475
+ };
476
+ document.addEventListener('mousemove', this.boundDocumentMouseMoveHandler);
477
+ // Track mousedown on document to know if a click started inside the canvas
478
+ document.addEventListener('mousedown', (e) => {
479
+ this.mouseDownTarget = e.target;
480
+ });
481
+ // CRITICAL FIX: Listen for mouseup on DOCUMENT, not just canvas
482
+ // This catches mouseup events that happen outside the canvas (common during drag)
483
+ this.boundMouseUpHandler = (e) => {
484
+ if (this.isSelecting) {
485
+ this.isSelecting = false;
486
+ this.stopAutoScroll();
487
+ // Check if this was a click without drag (threshold never met).
488
+ if (!this.dragThresholdMet) {
489
+ this.clearSelection();
490
+ return;
491
+ }
492
+ if (this.hasSelection()) {
493
+ const text = this.getSelection();
494
+ if (text) {
495
+ this.copyToClipboard(text);
496
+ this.selectionChangedEmitter.fire();
497
+ }
498
+ }
499
+ }
500
+ };
501
+ document.addEventListener('mouseup', this.boundMouseUpHandler);
502
+ // Handle click events for double-click (word) and triple-click (line) selection
503
+ // Use event.detail which browsers set to click count (1, 2, 3, etc.)
504
+ canvas.addEventListener('click', (e) => {
505
+ // event.detail: 1 = single, 2 = double, 3 = triple click
506
+ if (e.detail === 2) {
507
+ // Double-click - select word
508
+ const cell = this.pixelToCell(e.offsetX, e.offsetY);
509
+ const word = this.getWordAtCell(cell.col, cell.row);
510
+ if (word) {
511
+ const absoluteRow = this.viewportRowToAbsolute(cell.row);
512
+ this.selectionStart = { col: word.startCol, absoluteRow };
513
+ this.selectionEnd = { col: word.endCol, absoluteRow };
514
+ this.requestRender();
515
+ const text = this.getSelection();
516
+ if (text) {
517
+ this.copyToClipboard(text);
518
+ this.selectionChangedEmitter.fire();
519
+ }
520
+ }
521
+ }
522
+ else if (e.detail >= 3) {
523
+ // Triple-click (or more) - select line content (like native Ghostty)
524
+ const cell = this.pixelToCell(e.offsetX, e.offsetY);
525
+ const absoluteRow = this.viewportRowToAbsolute(cell.row);
526
+ // Find actual line length (exclude trailing empty cells)
527
+ // Use scrollback-aware line retrieval (like getSelection does)
528
+ const scrollbackLength = this.wasmTerm.getScrollbackLength();
529
+ let line = null;
530
+ if (absoluteRow < scrollbackLength) {
531
+ // Row is in scrollback
532
+ line = this.wasmTerm.getScrollbackLine(absoluteRow);
533
+ }
534
+ else {
535
+ // Row is in screen buffer
536
+ const screenRow = absoluteRow - scrollbackLength;
537
+ line = this.wasmTerm.getLine(screenRow);
538
+ }
539
+ // Find last non-empty cell (-1 means empty line)
540
+ let endCol = -1;
541
+ if (line) {
542
+ for (let i = line.length - 1; i >= 0; i--) {
543
+ if (line[i] && line[i].codepoint !== 0 && line[i].codepoint !== 32) {
544
+ endCol = i;
545
+ break;
546
+ }
547
+ }
548
+ }
549
+ // Only select if line has content (endCol >= 0)
550
+ if (endCol >= 0) {
551
+ // Select line content only (not trailing whitespace)
552
+ this.selectionStart = { col: 0, absoluteRow };
553
+ this.selectionEnd = { col: endCol, absoluteRow };
554
+ this.requestRender();
555
+ const text = this.getSelection();
556
+ if (text) {
557
+ this.copyToClipboard(text);
558
+ this.selectionChangedEmitter.fire();
559
+ }
560
+ }
561
+ }
562
+ });
563
+ // Right-click (context menu) - position textarea to show browser's native menu
564
+ // This allows Copy/Paste options to appear in the context menu
565
+ this.boundContextMenuHandler = (e) => {
566
+ // Position textarea at mouse cursor
567
+ const canvas = this.renderer.getCanvas();
568
+ const rect = canvas.getBoundingClientRect();
569
+ this.textarea.style.position = 'fixed';
570
+ this.textarea.style.left = `${e.clientX}px`;
571
+ this.textarea.style.top = `${e.clientY}px`;
572
+ this.textarea.style.width = '1px';
573
+ this.textarea.style.height = '1px';
574
+ this.textarea.style.zIndex = '1000';
575
+ this.textarea.style.opacity = '0';
576
+ // Enable pointer events temporarily so context menu targets the textarea
577
+ this.textarea.style.pointerEvents = 'auto';
578
+ // If there's a selection, populate textarea with it and select the text
579
+ if (this.hasSelection()) {
580
+ const text = this.getSelection();
581
+ this.textarea.value = text;
582
+ this.textarea.select();
583
+ this.textarea.setSelectionRange(0, text.length);
584
+ }
585
+ else {
586
+ // No selection - clear textarea but still show menu (for paste)
587
+ this.textarea.value = '';
588
+ }
589
+ // Focus the textarea so the context menu appears on it
590
+ this.textarea.focus();
591
+ // After a short delay, restore the textarea to its hidden state
592
+ // This allows the context menu to appear first
593
+ setTimeout(() => {
594
+ // Listen for when the context menu closes (user clicks away or selects an option)
595
+ const resetTextarea = () => {
596
+ this.textarea.style.pointerEvents = 'none';
597
+ this.textarea.style.zIndex = '-10';
598
+ this.textarea.style.width = '0';
599
+ this.textarea.style.height = '0';
600
+ this.textarea.style.left = '0';
601
+ this.textarea.style.top = '0';
602
+ this.textarea.value = '';
603
+ // Remove the one-time listeners
604
+ document.removeEventListener('click', resetTextarea);
605
+ document.removeEventListener('contextmenu', resetTextarea);
606
+ this.textarea.removeEventListener('blur', resetTextarea);
607
+ };
608
+ // Reset on any of these events (menu closed)
609
+ document.addEventListener('click', resetTextarea, { once: true });
610
+ document.addEventListener('contextmenu', resetTextarea, { once: true });
611
+ this.textarea.addEventListener('blur', resetTextarea, { once: true });
612
+ }, 10);
613
+ // Don't prevent default - let browser show the context menu on the textarea
614
+ };
615
+ canvas.addEventListener('contextmenu', this.boundContextMenuHandler);
616
+ // Click outside canvas - clear selection
617
+ // This allows users to deselect by clicking anywhere outside the terminal
618
+ this.boundClickHandler = (e) => {
619
+ // Don't clear selection if we're actively selecting
620
+ if (this.isSelecting) {
621
+ return;
622
+ }
623
+ // A click is only valid for clearing selection if BOTH mousedown and mouseup
624
+ // happened outside the canvas. If mousedown was inside (drag selection),
625
+ // don't clear even if mouseup/click is outside.
626
+ const mouseDownWasInCanvas = this.mouseDownTarget && canvas.contains(this.mouseDownTarget);
627
+ if (mouseDownWasInCanvas) {
628
+ return;
629
+ }
630
+ // Check if the click is outside the canvas
631
+ const target = e.target;
632
+ if (!canvas.contains(target)) {
633
+ // Clicked outside the canvas - clear selection
634
+ if (this.hasSelection()) {
635
+ this.clearSelection();
636
+ }
637
+ }
638
+ };
639
+ document.addEventListener('click', this.boundClickHandler);
640
+ }
641
+ /**
642
+ * Mark current selection rows as dirty for redraw
643
+ */
644
+ markCurrentSelectionDirty() {
645
+ const coords = this.normalizeSelection();
646
+ if (coords) {
647
+ for (let row = coords.startRow; row <= coords.endRow; row++) {
648
+ this.dirtySelectionRows.add(row);
649
+ }
650
+ }
651
+ }
652
+ /**
653
+ * Update auto-scroll based on mouse Y position within canvas
654
+ */
655
+ updateAutoScroll(offsetY, canvasHeight) {
656
+ const edgeSize = SelectionManager.AUTO_SCROLL_EDGE_SIZE;
657
+ if (offsetY < edgeSize) {
658
+ // Near top edge - scroll up
659
+ this.startAutoScroll(-1);
660
+ }
661
+ else if (offsetY > canvasHeight - edgeSize) {
662
+ // Near bottom edge - scroll down
663
+ this.startAutoScroll(1);
664
+ }
665
+ else {
666
+ // In middle - stop scrolling
667
+ this.stopAutoScroll();
668
+ }
669
+ }
670
+ /**
671
+ * Start auto-scrolling in the given direction
672
+ */
673
+ startAutoScroll(direction) {
674
+ // Don't restart if already scrolling in same direction
675
+ if (this.autoScrollInterval !== null && this.autoScrollDirection === direction) {
676
+ return;
677
+ }
678
+ // Stop any existing scroll
679
+ this.stopAutoScroll();
680
+ this.autoScrollDirection = direction;
681
+ // Start scrolling interval
682
+ this.autoScrollInterval = setInterval(() => {
683
+ if (!this.isSelecting) {
684
+ this.stopAutoScroll();
685
+ return;
686
+ }
687
+ // Scroll the terminal to reveal more content in the direction user is dragging
688
+ // autoScrollDirection: -1 = dragging up (wants to see history), 1 = dragging down (wants to see newer)
689
+ // scrollLines convention: negative = scroll up into history, positive = scroll down to newer
690
+ // So direction maps directly to scrollLines sign
691
+ const scrollAmount = SelectionManager.AUTO_SCROLL_SPEED * this.autoScrollDirection;
692
+ this.terminal.scrollLines(scrollAmount);
693
+ // Extend selection in the scroll direction
694
+ // Key insight: we need to EXTEND the selection, not reset it to viewport edge
695
+ if (this.selectionEnd) {
696
+ const dims = this.wasmTerm.getDimensions();
697
+ if (this.autoScrollDirection < 0) {
698
+ // Scrolling up - extend selection upward (decrease absoluteRow)
699
+ // Set to top of viewport, but only if it extends the selection
700
+ const topAbsoluteRow = this.viewportRowToAbsolute(0);
701
+ if (topAbsoluteRow < this.selectionEnd.absoluteRow) {
702
+ this.selectionEnd = { col: 0, absoluteRow: topAbsoluteRow };
703
+ }
704
+ }
705
+ else {
706
+ // Scrolling down - extend selection downward (increase absoluteRow)
707
+ // Set to bottom of viewport, but only if it extends the selection
708
+ const bottomAbsoluteRow = this.viewportRowToAbsolute(dims.rows - 1);
709
+ if (bottomAbsoluteRow > this.selectionEnd.absoluteRow) {
710
+ this.selectionEnd = { col: dims.cols - 1, absoluteRow: bottomAbsoluteRow };
711
+ }
712
+ }
713
+ }
714
+ this.requestRender();
715
+ }, SelectionManager.AUTO_SCROLL_INTERVAL);
716
+ }
717
+ /**
718
+ * Stop auto-scrolling
719
+ */
720
+ stopAutoScroll() {
721
+ if (this.autoScrollInterval !== null) {
722
+ clearInterval(this.autoScrollInterval);
723
+ this.autoScrollInterval = null;
724
+ }
725
+ this.autoScrollDirection = 0;
726
+ }
727
+ /**
728
+ * Convert surface pixels to a cell via the geometry authority — the mouse
729
+ * has coordinates, the grid model knows where cells are. Local division by
730
+ * cell size would ignore the grid's inset on the surface.
731
+ */
732
+ pixelToCell(x, y) {
733
+ return this.terminal.geometryAuthority.cellAt(x, y);
734
+ }
735
+ /**
736
+ * Normalize selection coordinates (handle backward selection)
737
+ * Returns coordinates in VIEWPORT space for rendering, clamped to visible area
738
+ */
739
+ normalizeSelection() {
740
+ if (!this.selectionStart || !this.selectionEnd)
741
+ return null;
742
+ let { col: startCol, absoluteRow: startAbsRow } = this.selectionStart;
743
+ let { col: endCol, absoluteRow: endAbsRow } = this.selectionEnd;
744
+ // Swap if selection goes backwards
745
+ if (startAbsRow > endAbsRow || (startAbsRow === endAbsRow && startCol > endCol)) {
746
+ [startCol, endCol] = [endCol, startCol];
747
+ [startAbsRow, endAbsRow] = [endAbsRow, startAbsRow];
748
+ }
749
+ // Convert to viewport coordinates
750
+ let startRow = this.absoluteRowToViewport(startAbsRow);
751
+ let endRow = this.absoluteRowToViewport(endAbsRow);
752
+ // Clamp to visible viewport range
753
+ const dims = this.wasmTerm.getDimensions();
754
+ const maxRow = dims.rows - 1;
755
+ // If entire selection is outside viewport, return null
756
+ if (endRow < 0 || startRow > maxRow) {
757
+ return null;
758
+ }
759
+ // Clamp rows to visible range, adjusting columns for partial rows
760
+ if (startRow < 0) {
761
+ startRow = 0;
762
+ startCol = 0; // Selection starts from beginning of first visible row
763
+ }
764
+ if (endRow > maxRow) {
765
+ endRow = maxRow;
766
+ endCol = dims.cols - 1; // Selection extends to end of last visible row
767
+ }
768
+ return { startCol, startRow, endCol, endRow };
769
+ }
770
+ /**
771
+ * Get word boundaries at a cell position
772
+ */
773
+ getWordAtCell(col, row) {
774
+ const absoluteRow = this.viewportRowToAbsolute(row);
775
+ const scrollbackLength = this.wasmTerm.getScrollbackLength();
776
+ let line;
777
+ if (absoluteRow < scrollbackLength) {
778
+ line = this.wasmTerm.getScrollbackLine(absoluteRow);
779
+ }
780
+ else {
781
+ const screenRow = absoluteRow - scrollbackLength;
782
+ line = this.wasmTerm.getLine(screenRow);
783
+ }
784
+ if (!line)
785
+ return null;
786
+ // Word characters: letters, numbers, and common path/URL characters
787
+ // Matches native Ghostty behavior where double-click selects entire paths
788
+ // Includes: / (path sep), . (extensions), ~ (home), @ (emails), + (encodings)
789
+ const isWordChar = (cell) => {
790
+ if (!cell || cell.codepoint === 0)
791
+ return false;
792
+ const char = String.fromCodePoint(cell.codepoint);
793
+ return /[\w\-./~@+]/.test(char);
794
+ };
795
+ // Only return if we're actually on a word character
796
+ if (!isWordChar(line[col]))
797
+ return null;
798
+ // Find start of word
799
+ let startCol = col;
800
+ while (startCol > 0 && isWordChar(line[startCol - 1])) {
801
+ startCol--;
802
+ }
803
+ // Find end of word
804
+ let endCol = col;
805
+ while (endCol < line.length - 1 && isWordChar(line[endCol + 1])) {
806
+ endCol++;
807
+ }
808
+ return { startCol, endCol };
809
+ }
810
+ /**
811
+ * Copy text to clipboard
812
+ *
813
+ * Strategy (modern APIs first):
814
+ * 1. Try ClipboardItem API (works in Safari and modern browsers)
815
+ * - Safari requires the ClipboardItem to be created synchronously within user gesture
816
+ * 2. Try navigator.clipboard.writeText (modern async API, may fail in Safari)
817
+ * 3. Fall back to execCommand (legacy, for older browsers)
818
+ */
819
+ copyToClipboard(text) {
820
+ // First try: ClipboardItem API (modern, Safari-compatible)
821
+ // Safari allows this because we create the ClipboardItem synchronously
822
+ // within the user gesture, even though the write is async
823
+ if (navigator.clipboard && typeof ClipboardItem !== 'undefined') {
824
+ try {
825
+ const blob = new Blob([text], { type: 'text/plain' });
826
+ const clipboardItem = new ClipboardItem({
827
+ 'text/plain': blob,
828
+ });
829
+ navigator.clipboard.write([clipboardItem]).catch((err) => {
830
+ console.warn('ClipboardItem write failed, trying writeText:', err);
831
+ // Try writeText as fallback
832
+ this.copyWithWriteText(text);
833
+ });
834
+ return;
835
+ }
836
+ catch (err) {
837
+ // ClipboardItem not supported or failed, fall through
838
+ }
839
+ }
840
+ // Second try: basic async writeText (works in Chrome, may fail in Safari)
841
+ if (navigator.clipboard && navigator.clipboard.writeText) {
842
+ navigator.clipboard.writeText(text).catch((err) => {
843
+ console.warn('Clipboard writeText failed, trying execCommand:', err);
844
+ // Fall back to execCommand
845
+ this.copyWithExecCommand(text);
846
+ });
847
+ return;
848
+ }
849
+ // Third try: legacy execCommand fallback
850
+ this.copyWithExecCommand(text);
851
+ }
852
+ /**
853
+ * Copy using navigator.clipboard.writeText
854
+ */
855
+ copyWithWriteText(text) {
856
+ if (navigator.clipboard && navigator.clipboard.writeText) {
857
+ navigator.clipboard.writeText(text).catch((err) => {
858
+ console.warn('Clipboard writeText failed, trying execCommand:', err);
859
+ this.copyWithExecCommand(text);
860
+ });
861
+ }
862
+ else {
863
+ this.copyWithExecCommand(text);
864
+ }
865
+ }
866
+ /**
867
+ * Copy using legacy execCommand (fallback for older browsers)
868
+ */
869
+ copyWithExecCommand(text) {
870
+ const previouslyFocused = document.activeElement;
871
+ try {
872
+ // Position textarea offscreen but in a way that allows selection
873
+ const textarea = this.textarea;
874
+ textarea.value = text;
875
+ textarea.style.position = 'fixed';
876
+ textarea.style.left = '-9999px';
877
+ textarea.style.top = '0';
878
+ textarea.style.width = '1px';
879
+ textarea.style.height = '1px';
880
+ textarea.style.opacity = '0';
881
+ // Select all text and copy
882
+ textarea.focus();
883
+ textarea.select();
884
+ textarea.setSelectionRange(0, text.length);
885
+ const success = document.execCommand('copy');
886
+ // Restore focus
887
+ if (previouslyFocused) {
888
+ previouslyFocused.focus();
889
+ }
890
+ if (!success) {
891
+ console.warn('execCommand copy failed');
892
+ }
893
+ }
894
+ catch (err) {
895
+ console.warn('execCommand copy threw:', err);
896
+ // Restore focus on error
897
+ if (previouslyFocused) {
898
+ previouslyFocused.focus();
899
+ }
900
+ }
901
+ }
902
+ /**
903
+ * Request a render update (triggers selection overlay redraw)
904
+ */
905
+ requestRender() {
906
+ // The render loop will automatically pick up the new selection state
907
+ // and redraw the affected lines. This happens at 60fps.
908
+ //
909
+ // Note: When clearSelection() is called, it adds dirty rows to dirtySelectionRows
910
+ // which the renderer can use to know which lines to redraw.
911
+ }
912
+ }
913
+ //# sourceMappingURL=selection-manager.js.map