@dsh-cc/pi-tui 0.5.0

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 (164) hide show
  1. package/LICENSE +21 -0
  2. package/PORTING.md +18 -0
  3. package/README.md +7 -0
  4. package/lib/alt-screen-search.d.ts +26 -0
  5. package/lib/alt-screen-search.d.ts.map +1 -0
  6. package/lib/alt-screen-search.js +122 -0
  7. package/lib/alt-screen-search.js.map +1 -0
  8. package/lib/autocomplete.d.ts +56 -0
  9. package/lib/autocomplete.d.ts.map +1 -0
  10. package/lib/autocomplete.js +632 -0
  11. package/lib/autocomplete.js.map +1 -0
  12. package/lib/components/alt-screen-flash.d.ts +13 -0
  13. package/lib/components/alt-screen-flash.d.ts.map +1 -0
  14. package/lib/components/alt-screen-flash.js +37 -0
  15. package/lib/components/alt-screen-flash.js.map +1 -0
  16. package/lib/components/box.d.ts +22 -0
  17. package/lib/components/box.d.ts.map +1 -0
  18. package/lib/components/box.js +104 -0
  19. package/lib/components/box.js.map +1 -0
  20. package/lib/components/cancellable-loader.d.ts +22 -0
  21. package/lib/components/cancellable-loader.d.ts.map +1 -0
  22. package/lib/components/cancellable-loader.js +35 -0
  23. package/lib/components/cancellable-loader.js.map +1 -0
  24. package/lib/components/editor.d.ts +255 -0
  25. package/lib/components/editor.d.ts.map +1 -0
  26. package/lib/components/editor.js +1961 -0
  27. package/lib/components/editor.js.map +1 -0
  28. package/lib/components/h-stack.d.ts +7 -0
  29. package/lib/components/h-stack.d.ts.map +1 -0
  30. package/lib/components/h-stack.js +43 -0
  31. package/lib/components/h-stack.js.map +1 -0
  32. package/lib/components/image.d.ts +28 -0
  33. package/lib/components/image.d.ts.map +1 -0
  34. package/lib/components/image.js +90 -0
  35. package/lib/components/image.js.map +1 -0
  36. package/lib/components/input.d.ts +37 -0
  37. package/lib/components/input.d.ts.map +1 -0
  38. package/lib/components/input.js +378 -0
  39. package/lib/components/input.js.map +1 -0
  40. package/lib/components/loader.d.ts +31 -0
  41. package/lib/components/loader.d.ts.map +1 -0
  42. package/lib/components/loader.js +69 -0
  43. package/lib/components/loader.js.map +1 -0
  44. package/lib/components/markdown.d.ts +103 -0
  45. package/lib/components/markdown.d.ts.map +1 -0
  46. package/lib/components/markdown.js +811 -0
  47. package/lib/components/markdown.js.map +1 -0
  48. package/lib/components/scroll-view.d.ts +56 -0
  49. package/lib/components/scroll-view.d.ts.map +1 -0
  50. package/lib/components/scroll-view.js +189 -0
  51. package/lib/components/scroll-view.js.map +1 -0
  52. package/lib/components/select-list.d.ts +50 -0
  53. package/lib/components/select-list.d.ts.map +1 -0
  54. package/lib/components/select-list.js +159 -0
  55. package/lib/components/select-list.js.map +1 -0
  56. package/lib/components/settings-list.d.ts +56 -0
  57. package/lib/components/settings-list.d.ts.map +1 -0
  58. package/lib/components/settings-list.js +202 -0
  59. package/lib/components/settings-list.js.map +1 -0
  60. package/lib/components/spacer.d.ts +12 -0
  61. package/lib/components/spacer.d.ts.map +1 -0
  62. package/lib/components/spacer.js +23 -0
  63. package/lib/components/spacer.js.map +1 -0
  64. package/lib/components/stack.d.ts +32 -0
  65. package/lib/components/stack.d.ts.map +1 -0
  66. package/lib/components/stack.js +111 -0
  67. package/lib/components/stack.js.map +1 -0
  68. package/lib/components/text.d.ts +19 -0
  69. package/lib/components/text.d.ts.map +1 -0
  70. package/lib/components/text.js +90 -0
  71. package/lib/components/text.js.map +1 -0
  72. package/lib/components/truncated-text.d.ts +13 -0
  73. package/lib/components/truncated-text.d.ts.map +1 -0
  74. package/lib/components/truncated-text.js +51 -0
  75. package/lib/components/truncated-text.js.map +1 -0
  76. package/lib/components/v-stack.d.ts +8 -0
  77. package/lib/components/v-stack.d.ts.map +1 -0
  78. package/lib/components/v-stack.js +26 -0
  79. package/lib/components/v-stack.js.map +1 -0
  80. package/lib/editor-component.d.ts +39 -0
  81. package/lib/editor-component.d.ts.map +1 -0
  82. package/lib/editor-component.js +2 -0
  83. package/lib/editor-component.js.map +1 -0
  84. package/lib/fuzzy.d.ts +16 -0
  85. package/lib/fuzzy.d.ts.map +1 -0
  86. package/lib/fuzzy.js +110 -0
  87. package/lib/fuzzy.js.map +1 -0
  88. package/lib/index.d.ts +31 -0
  89. package/lib/index.d.ts.map +1 -0
  90. package/lib/index.js +42 -0
  91. package/lib/index.js.map +1 -0
  92. package/lib/keybindings.d.ts +273 -0
  93. package/lib/keybindings.d.ts.map +1 -0
  94. package/lib/keybindings.js +233 -0
  95. package/lib/keybindings.js.map +1 -0
  96. package/lib/keys.d.ts +184 -0
  97. package/lib/keys.d.ts.map +1 -0
  98. package/lib/keys.js +1174 -0
  99. package/lib/keys.js.map +1 -0
  100. package/lib/kill-ring.d.ts +28 -0
  101. package/lib/kill-ring.d.ts.map +1 -0
  102. package/lib/kill-ring.js +44 -0
  103. package/lib/kill-ring.js.map +1 -0
  104. package/lib/latex.d.ts +10 -0
  105. package/lib/latex.d.ts.map +1 -0
  106. package/lib/latex.js +1271 -0
  107. package/lib/latex.js.map +1 -0
  108. package/lib/layout-node.d.ts +40 -0
  109. package/lib/layout-node.d.ts.map +1 -0
  110. package/lib/layout-node.js +6 -0
  111. package/lib/layout-node.js.map +1 -0
  112. package/lib/layout.d.ts +40 -0
  113. package/lib/layout.d.ts.map +1 -0
  114. package/lib/layout.js +321 -0
  115. package/lib/layout.js.map +1 -0
  116. package/lib/native-modifiers.d.ts +3 -0
  117. package/lib/native-modifiers.d.ts.map +1 -0
  118. package/lib/native-modifiers.js +54 -0
  119. package/lib/native-modifiers.js.map +1 -0
  120. package/lib/native-module-path.d.ts +7 -0
  121. package/lib/native-module-path.d.ts.map +1 -0
  122. package/lib/native-module-path.js +19 -0
  123. package/lib/native-module-path.js.map +1 -0
  124. package/lib/stdin-buffer.d.ts +56 -0
  125. package/lib/stdin-buffer.d.ts.map +1 -0
  126. package/lib/stdin-buffer.js +366 -0
  127. package/lib/stdin-buffer.js.map +1 -0
  128. package/lib/terminal-colors.d.ts +10 -0
  129. package/lib/terminal-colors.d.ts.map +1 -0
  130. package/lib/terminal-colors.js +59 -0
  131. package/lib/terminal-colors.js.map +1 -0
  132. package/lib/terminal-image.d.ts +116 -0
  133. package/lib/terminal-image.d.ts.map +1 -0
  134. package/lib/terminal-image.js +518 -0
  135. package/lib/terminal-image.js.map +1 -0
  136. package/lib/terminal.d.ts +117 -0
  137. package/lib/terminal.d.ts.map +1 -0
  138. package/lib/terminal.js +447 -0
  139. package/lib/terminal.js.map +1 -0
  140. package/lib/tui-alt-screen.d.ts +118 -0
  141. package/lib/tui-alt-screen.d.ts.map +1 -0
  142. package/lib/tui-alt-screen.js +1148 -0
  143. package/lib/tui-alt-screen.js.map +1 -0
  144. package/lib/tui-main-screen.d.ts +39 -0
  145. package/lib/tui-main-screen.d.ts.map +1 -0
  146. package/lib/tui-main-screen.js +533 -0
  147. package/lib/tui-main-screen.js.map +1 -0
  148. package/lib/tui.d.ts +308 -0
  149. package/lib/tui.d.ts.map +1 -0
  150. package/lib/tui.js +941 -0
  151. package/lib/tui.js.map +1 -0
  152. package/lib/undo-stack.d.ts +17 -0
  153. package/lib/undo-stack.d.ts.map +1 -0
  154. package/lib/undo-stack.js +25 -0
  155. package/lib/undo-stack.js.map +1 -0
  156. package/lib/utils.d.ts +96 -0
  157. package/lib/utils.d.ts.map +1 -0
  158. package/lib/utils.js +1191 -0
  159. package/lib/utils.js.map +1 -0
  160. package/lib/word-navigation.d.ts +25 -0
  161. package/lib/word-navigation.d.ts.map +1 -0
  162. package/lib/word-navigation.js +96 -0
  163. package/lib/word-navigation.js.map +1 -0
  164. package/package.json +42 -0
@@ -0,0 +1,1148 @@
1
+ import { AltScreenSearchComponent, findAltScreenSearchMatches, getAltScreenSearchMatchKey, } from "./alt-screen-search.js";
2
+ import { AltScreenFlashContainer } from "./components/alt-screen-flash.js";
3
+ import { ScrollView } from "./components/scroll-view.js";
4
+ import { getKeybindings } from "./keybindings.js";
5
+ import { isKeyRelease } from "./keys.js";
6
+ import { getScrollbarGeometry, getScrollViewBox, getScrollViewsAt, renderLayoutFrame, } from "./layout.js";
7
+ import { deleteAllKittyImages, deleteAllKittyPlacements, deleteKittyImage, getCapabilities, getKittyImagePlacement, isImageLine, setCapabilities, } from "./terminal-image.js";
8
+ import { CURSOR_MARKER, compositeTuiLine, TuiBase, VIEWPORT_TUI, } from "./tui.js";
9
+ import { extractAnsiCode, getGraphemeCellRange, getOsc8LinkAtColumn, getWordSegmenter, sliceByColumn, stripTerminalSequences, visibleWidth, } from "./utils.js";
10
+ const ENTER_ALT_SCREEN = "\x1b[?1049h";
11
+ const EXIT_ALT_SCREEN = "\x1b[?1049l";
12
+ const DISABLE_AUTOWRAP = "\x1b[?7l";
13
+ const ENABLE_AUTOWRAP = "\x1b[?7h";
14
+ const ENABLE_BUTTON_MOTION_MOUSE = "\x1b[?1000h\x1b[?1002h\x1b[?1004h\x1b[?1006h";
15
+ const ENABLE_ALL_MOTION_MOUSE = "\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1004h\x1b[?1006h";
16
+ const DISABLE_MOUSE = "\x1b[?1006l\x1b[?1004l\x1b[?1003l\x1b[?1002l\x1b[?1000l";
17
+ const FOCUS_IN = "\x1b[I";
18
+ const FOCUS_OUT = "\x1b[O";
19
+ const BEGIN_SYNCHRONIZED_OUTPUT = "\x1b[?2026h";
20
+ const END_SYNCHRONIZED_OUTPUT = "\x1b[?2026l";
21
+ const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
22
+ const OSC133_PROMPT_START = /^\x1b\]133;A(?:\x07|\x1b\\)/;
23
+ const PAGE_SCROLL_OVERLAP = 4;
24
+ const MAX_CACHED_OFFSCREEN_KITTY_IMAGES = 16;
25
+ const MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES = 32 * 1024 * 1024;
26
+ const MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES = 64 * 1024 * 1024;
27
+ const DOUBLE_CLICK_INTERVAL_MS = 500;
28
+ const wordSegmenter = getWordSegmenter();
29
+ /** Alternate-screen TUI with a scrollable, application-owned viewport. */
30
+ export class TuiAltScreen extends TuiBase {
31
+ mode = "fullscreen";
32
+ [VIEWPORT_TUI] = true;
33
+ previousScreen = [];
34
+ lastDocument = [];
35
+ previousScreenWidth = 0;
36
+ previousScreenHeight = 0;
37
+ layoutRoot;
38
+ currentLayout;
39
+ implicitDocument;
40
+ implicitScrollView;
41
+ flashes;
42
+ altScreenActive = false;
43
+ imageProtocol = null;
44
+ savedCapabilities;
45
+ uploadedKittyImages = new Map();
46
+ selectionAnchor;
47
+ selectionFocus;
48
+ selectionGranularity = "character";
49
+ selectionInitialRange;
50
+ lastClick;
51
+ selectionDragPointer;
52
+ selectionAutoScrollDirection = 0;
53
+ selectionAutoScrollTimer;
54
+ selectionPressActive = false;
55
+ scrollbarDrag;
56
+ scrollbarHover;
57
+ activeSearch;
58
+ pressedUrl;
59
+ selectionDragged = false;
60
+ wheelScrollLines;
61
+ mouseEnabled;
62
+ searchMatchStyle;
63
+ searchCurrentMatchStyle;
64
+ openUrl;
65
+ onRightClickPaste;
66
+ copySelection;
67
+ constructor(terminal, showHardwareCursor, logDirectory, options = {}) {
68
+ super(terminal, showHardwareCursor, logDirectory);
69
+ this.implicitDocument = {
70
+ render: (width) => super.render(width),
71
+ invalidate: () => {
72
+ for (const child of this.children)
73
+ child.invalidate();
74
+ },
75
+ };
76
+ this.implicitScrollView = new ScrollView(this.implicitDocument, { follow: "end", primary: true });
77
+ this.flashes = new AltScreenFlashContainer(() => this.requestRender());
78
+ this.wheelScrollLines = Math.max(1, Math.floor(options.wheelScrollLines ?? 1));
79
+ this.mouseEnabled = options.mouse ?? true;
80
+ this.searchMatchStyle = options.searchMatchStyle ?? ((text) => `\x1b[4m${text}\x1b[24m`);
81
+ this.searchCurrentMatchStyle = options.searchCurrentMatchStyle ?? ((text) => `\x1b[1;7m${text}\x1b[22;27m`);
82
+ this.openUrl = options.openUrl;
83
+ this.onRightClickPaste = options.onRightClickPaste;
84
+ this.copySelection = options.copySelection;
85
+ this.addInputListener((data) => this.handleViewportInput(data));
86
+ }
87
+ get viewportTop() {
88
+ return this.getPrimaryScrollView().scrollTop;
89
+ }
90
+ get isFollowingOutput() {
91
+ return this.getPrimaryScrollView().isFollowingEnd;
92
+ }
93
+ setLayoutRoot(component) {
94
+ if (this.layoutRoot === component)
95
+ return;
96
+ this.layoutRoot = component;
97
+ this.currentLayout = undefined;
98
+ this.requestRender();
99
+ }
100
+ render(width) {
101
+ return this.layoutRoot?.render(width) ?? super.render(width);
102
+ }
103
+ getMountedRoots() {
104
+ return this.layoutRoot ? [this.layoutRoot] : this.children;
105
+ }
106
+ getPrimaryScrollView() {
107
+ return this.currentLayout?.primaryScrollView ?? this.implicitScrollView;
108
+ }
109
+ beforeTerminalStart() {
110
+ this.stopSelectionAutoScroll();
111
+ this.selectionPressActive = false;
112
+ this.stopScrollbarHover();
113
+ this.stopScrollbarDrag();
114
+ this.flashes.dispose();
115
+ this.altScreenActive = true;
116
+ const capabilities = getCapabilities();
117
+ this.imageProtocol = capabilities.images;
118
+ this.uploadedKittyImages.clear();
119
+ if (capabilities.images === "iterm2") {
120
+ this.savedCapabilities = capabilities;
121
+ setCapabilities({ ...capabilities, images: null });
122
+ this.invalidate();
123
+ }
124
+ this.lastDocument = [];
125
+ this.selectionAnchor = undefined;
126
+ this.selectionFocus = undefined;
127
+ this.selectionGranularity = "character";
128
+ this.selectionInitialRange = undefined;
129
+ this.lastClick = undefined;
130
+ this.pressedUrl = undefined;
131
+ this.selectionDragged = false;
132
+ this.resetRenderState();
133
+ const term = process.env.TERM?.toLowerCase() ?? "";
134
+ // Multiplexers can lag when every pointer movement is forwarded. Button-motion
135
+ // tracking preserves clicks, wheel events, selections, and scrollbar dragging.
136
+ const mouseSequence = process.env.TMUX !== undefined ||
137
+ process.env.ZELLIJ !== undefined ||
138
+ process.env.STY !== undefined ||
139
+ term.startsWith("tmux") ||
140
+ term.startsWith("screen")
141
+ ? ENABLE_BUTTON_MOTION_MOUSE
142
+ : ENABLE_ALL_MOTION_MOUSE;
143
+ this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled ? mouseSequence : ""}\x1b[2J\x1b[H\x1b[?25l`);
144
+ }
145
+ beforeTerminalStop(_options) {
146
+ this.closeSearch();
147
+ this.stopSelectionAutoScroll();
148
+ this.selectionPressActive = false;
149
+ this.stopScrollbarHover();
150
+ this.stopScrollbarDrag();
151
+ this.flashes.dispose();
152
+ if (!this.altScreenActive)
153
+ return;
154
+ this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled ? DISABLE_MOUSE : ""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`);
155
+ this.uploadedKittyImages.clear();
156
+ }
157
+ afterTerminalStop(options) {
158
+ if (!this.altScreenActive)
159
+ return;
160
+ this.altScreenActive = false;
161
+ if (options.preserveScreen) {
162
+ this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1b[?25h${END_SYNCHRONIZED_OUTPUT}`);
163
+ }
164
+ else {
165
+ const width = Math.max(1, this.terminal.columns);
166
+ const documentLines = this.render(width).map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
167
+ this.lastDocument = this.applyLineResets(documentLines.map((line) => line.replaceAll(CURSOR_MARKER, ""))).map((line) => (isImageLine(line) || visibleWidth(line) <= width ? line : sliceByColumn(line, 0, width, true)));
168
+ let buffer = `${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;
169
+ for (let row = 0; row < this.lastDocument.length; row++) {
170
+ if (row > 0)
171
+ buffer += "\r\n";
172
+ buffer += `\r\x1b[2K${this.lastDocument[row] ?? ""}`;
173
+ }
174
+ buffer += `\x1b[0m${ENABLE_AUTOWRAP}\r\n\x1b[?25h${END_SYNCHRONIZED_OUTPUT}`;
175
+ this.terminal.write(buffer);
176
+ }
177
+ if (this.savedCapabilities) {
178
+ setCapabilities(this.savedCapabilities);
179
+ this.savedCapabilities = undefined;
180
+ }
181
+ }
182
+ deleteKittyImages() {
183
+ return this.imageProtocol === "kitty" ? deleteAllKittyImages() : "";
184
+ }
185
+ prepareKittyScreen(screen) {
186
+ const visibleImageIds = new Set();
187
+ const lines = screen.map((line) => {
188
+ const placement = getKittyImagePlacement(line);
189
+ if (!placement)
190
+ return line;
191
+ visibleImageIds.add(placement.imageId);
192
+ const cachedImage = this.uploadedKittyImages.get(placement.imageId);
193
+ const nextCachedImage = {
194
+ transmissionGeneration: placement.transmissionGeneration,
195
+ transmissionBytes: placement.transmissionBytes,
196
+ estimatedDecodedBytes: placement.estimatedDecodedBytes,
197
+ };
198
+ if (cachedImage)
199
+ this.uploadedKittyImages.delete(placement.imageId);
200
+ this.uploadedKittyImages.set(placement.imageId, nextCachedImage);
201
+ return cachedImage?.transmissionGeneration === placement.transmissionGeneration
202
+ ? placement.replacementLine
203
+ : line;
204
+ });
205
+ let cachedOffscreenImageCount = 0;
206
+ let cachedOffscreenTransmissionBytes = 0;
207
+ let cachedOffscreenDecodedBytes = 0;
208
+ for (const [imageId, cachedImage] of this.uploadedKittyImages) {
209
+ if (visibleImageIds.has(imageId))
210
+ continue;
211
+ cachedOffscreenImageCount += 1;
212
+ cachedOffscreenTransmissionBytes += cachedImage.transmissionBytes;
213
+ cachedOffscreenDecodedBytes += cachedImage.estimatedDecodedBytes;
214
+ }
215
+ let evictedImageDeletion = "";
216
+ for (const [imageId, cachedImage] of this.uploadedKittyImages) {
217
+ if (cachedOffscreenImageCount <= MAX_CACHED_OFFSCREEN_KITTY_IMAGES &&
218
+ cachedOffscreenTransmissionBytes <= MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES &&
219
+ cachedOffscreenDecodedBytes <= MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES) {
220
+ break;
221
+ }
222
+ if (visibleImageIds.has(imageId))
223
+ continue;
224
+ evictedImageDeletion += deleteKittyImage(imageId);
225
+ this.uploadedKittyImages.delete(imageId);
226
+ cachedOffscreenImageCount -= 1;
227
+ cachedOffscreenTransmissionBytes -= cachedImage.transmissionBytes;
228
+ cachedOffscreenDecodedBytes -= cachedImage.estimatedDecodedBytes;
229
+ }
230
+ return { lines, evictedImageDeletion };
231
+ }
232
+ resetRenderState() {
233
+ this.previousScreen = [];
234
+ this.previousScreenWidth = 0;
235
+ this.previousScreenHeight = 0;
236
+ this.currentLayout = undefined;
237
+ }
238
+ scrollBy(lines) {
239
+ this.getPrimaryScrollView().scrollBy(lines);
240
+ this.requestRender();
241
+ }
242
+ scrollToTop() {
243
+ this.getPrimaryScrollView().scrollToStart();
244
+ this.requestRender();
245
+ }
246
+ scrollToBottom() {
247
+ this.getPrimaryScrollView().scrollToEnd();
248
+ this.requestRender();
249
+ }
250
+ scrollToPrompt(direction) {
251
+ if (!this.currentLayout)
252
+ return;
253
+ const scrollView = this.getPrimaryScrollView();
254
+ const lines = getScrollViewBox(this.currentLayout, scrollView)?.scrollContentLines;
255
+ if (!lines)
256
+ return;
257
+ for (let row = scrollView.scrollTop + direction; row >= 0 && row < lines.length; row += direction) {
258
+ if (!OSC133_PROMPT_START.test(lines[row] ?? ""))
259
+ continue;
260
+ scrollView.scrollTo(row);
261
+ this.requestRender();
262
+ return;
263
+ }
264
+ }
265
+ openSearch() {
266
+ if (this.activeSearch) {
267
+ this.activeSearch.overlay?.focus();
268
+ return;
269
+ }
270
+ const component = new AltScreenSearchComponent((query) => this.updateSearchQuery(query));
271
+ const search = {
272
+ component,
273
+ query: "",
274
+ matches: [],
275
+ selectedIndex: -1,
276
+ anchorRow: this.getPrimaryScrollView().scrollTop,
277
+ selectionMode: "query",
278
+ };
279
+ this.activeSearch = search;
280
+ search.overlay = this.showOverlay(component, {
281
+ anchor: "top-right",
282
+ width: "40%",
283
+ minWidth: 24,
284
+ margin: 1,
285
+ });
286
+ }
287
+ closeSearch() {
288
+ const search = this.activeSearch;
289
+ if (!search)
290
+ return;
291
+ this.activeSearch = undefined;
292
+ search.overlay?.hide();
293
+ this.requestRender();
294
+ }
295
+ updateSearchQuery(query) {
296
+ const search = this.activeSearch;
297
+ if (!search || query === search.query)
298
+ return;
299
+ const selected = search.matches[search.selectedIndex];
300
+ search.anchorRow = selected?.segments[0]?.row ?? this.getPrimaryScrollView().scrollTop;
301
+ search.query = query;
302
+ search.selectionMode = "query";
303
+ search.component.setResult(-1, 0);
304
+ this.requestRender();
305
+ }
306
+ navigateSearch(direction) {
307
+ const search = this.activeSearch;
308
+ if (!search?.query)
309
+ return;
310
+ search.selectionMode = direction < 0 ? "previous" : "next";
311
+ this.requestRender();
312
+ }
313
+ refreshSearch(layout) {
314
+ const search = this.activeSearch;
315
+ if (!search)
316
+ return false;
317
+ const scrollView = layout.primaryScrollView ?? this.implicitScrollView;
318
+ const box = getScrollViewBox(layout, scrollView);
319
+ const lines = box?.scrollContentLines;
320
+ if (!lines || !search.query.trim()) {
321
+ search.matches = [];
322
+ search.selectedIndex = -1;
323
+ search.selectedKey = undefined;
324
+ search.selectionMode = "retain";
325
+ search.component.setResult(-1, 0);
326
+ return false;
327
+ }
328
+ const shouldRevealSelection = search.selectionMode !== "retain";
329
+ const matches = findAltScreenSearchMatches(lines, search.query);
330
+ const exactIndex = search.selectedKey
331
+ ? matches.findIndex((match) => getAltScreenSearchMatchKey(match) === search.selectedKey)
332
+ : -1;
333
+ let selectedIndex = -1;
334
+ if (matches.length > 0) {
335
+ if (search.selectionMode === "query") {
336
+ selectedIndex = matches.findIndex((match) => (match.segments[0]?.row ?? 0) >= search.anchorRow);
337
+ if (selectedIndex < 0)
338
+ selectedIndex = 0;
339
+ }
340
+ else if (search.selectionMode === "next") {
341
+ const baseIndex = exactIndex >= 0 ? exactIndex : Math.min(search.selectedIndex, matches.length - 1);
342
+ selectedIndex = baseIndex < 0 ? 0 : (baseIndex + 1) % matches.length;
343
+ }
344
+ else if (search.selectionMode === "previous") {
345
+ const baseIndex = exactIndex >= 0 ? exactIndex : Math.min(search.selectedIndex, matches.length - 1);
346
+ selectedIndex = baseIndex < 0 ? matches.length - 1 : (baseIndex - 1 + matches.length) % matches.length;
347
+ }
348
+ else {
349
+ selectedIndex =
350
+ exactIndex >= 0 ? exactIndex : Math.min(Math.max(0, search.selectedIndex), matches.length - 1);
351
+ }
352
+ }
353
+ search.matches = matches;
354
+ search.selectedIndex = selectedIndex;
355
+ search.selectedKey = selectedIndex >= 0 ? getAltScreenSearchMatchKey(matches[selectedIndex]) : undefined;
356
+ search.selectionMode = "retain";
357
+ search.component.setResult(selectedIndex, matches.length);
358
+ if (!shouldRevealSelection)
359
+ return false;
360
+ const selected = matches[selectedIndex];
361
+ const firstSegment = selected?.segments[0];
362
+ const lastSegment = selected?.segments[selected.segments.length - 1];
363
+ if (!box || !firstSegment || !lastSegment || scrollView.viewportHeight <= 0)
364
+ return false;
365
+ const before = scrollView.scrollTop;
366
+ const visibleBottom = before + scrollView.viewportHeight - 1;
367
+ let target = before;
368
+ if (firstSegment.row < before || lastSegment.row > visibleBottom) {
369
+ target = firstSegment.row - Math.floor(scrollView.viewportHeight / 3);
370
+ }
371
+ scrollView.scrollTo(target, { disableFollow: true });
372
+ return scrollView.scrollTop !== before;
373
+ }
374
+ /** Show a transient message in the alternate-screen flash stack. */
375
+ flash(message, durationMs) {
376
+ this.flashes.flash(message, durationMs);
377
+ }
378
+ shouldDeferViewportInputToOverlay() {
379
+ return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true;
380
+ }
381
+ handleViewportInput(data) {
382
+ if (data === FOCUS_OUT) {
383
+ const hadActiveSelection = this.selectionPressActive;
384
+ const hadNonEmptyActiveSelection = hadActiveSelection && this.getSelectionBounds() !== undefined;
385
+ this.selectionPressActive = false;
386
+ this.stopSelectionAutoScroll();
387
+ this.stopScrollbarHover();
388
+ this.stopScrollbarDrag();
389
+ this.pressedUrl = undefined;
390
+ this.selectionDragged = false;
391
+ if (hadActiveSelection) {
392
+ this.selectionAnchor = undefined;
393
+ this.selectionFocus = undefined;
394
+ this.selectionGranularity = "character";
395
+ this.selectionInitialRange = undefined;
396
+ if (hadNonEmptyActiveSelection)
397
+ this.requestRender();
398
+ }
399
+ this.lastClick = undefined;
400
+ return { consume: true };
401
+ }
402
+ if (data === FOCUS_IN)
403
+ return { consume: true };
404
+ const wheelEvent = this.parseWheelEvent(data);
405
+ if (wheelEvent) {
406
+ if (this.shouldDeferViewportInputToOverlay())
407
+ return undefined;
408
+ this.routeWheel(wheelEvent);
409
+ return { consume: true };
410
+ }
411
+ const mouseEvent = this.parseSgrMouseEvent(data);
412
+ if (mouseEvent) {
413
+ if (this.handleRightClickPaste(mouseEvent))
414
+ return { consume: true };
415
+ const handled = this.handleScrollbarMouseEvent(mouseEvent);
416
+ if (!this.scrollbarDrag)
417
+ this.updateScrollbarHover(mouseEvent.x, mouseEvent.y);
418
+ if (!handled)
419
+ this.handleSelectionMouseEvent(mouseEvent);
420
+ return { consume: true };
421
+ }
422
+ if (this.isMouseSequence(data))
423
+ return { consume: true };
424
+ const keybindings = getKeybindings();
425
+ const isRelease = isKeyRelease(data);
426
+ if (keybindings.matches(data, "tui.altScreen.search")) {
427
+ if (!isRelease)
428
+ this.openSearch();
429
+ return { consume: true };
430
+ }
431
+ if (this.activeSearch?.overlay?.isFocused()) {
432
+ if (keybindings.matches(data, "tui.altScreen.searchNext")) {
433
+ if (!isRelease)
434
+ this.navigateSearch(1);
435
+ return { consume: true };
436
+ }
437
+ if (keybindings.matches(data, "tui.altScreen.searchPrevious")) {
438
+ if (!isRelease)
439
+ this.navigateSearch(-1);
440
+ return { consume: true };
441
+ }
442
+ if (keybindings.matches(data, "tui.altScreen.searchClose")) {
443
+ if (!isRelease)
444
+ this.closeSearch();
445
+ return { consume: true };
446
+ }
447
+ }
448
+ if (this.shouldDeferViewportInputToOverlay())
449
+ return undefined;
450
+ if (keybindings.matches(data, "tui.altScreen.pageUp")) {
451
+ if (!isRelease) {
452
+ this.scrollBy(-Math.max(1, this.getPrimaryScrollView().viewportHeight - PAGE_SCROLL_OVERLAP));
453
+ }
454
+ return { consume: true };
455
+ }
456
+ if (keybindings.matches(data, "tui.altScreen.pageDown")) {
457
+ if (!isRelease) {
458
+ this.scrollBy(Math.max(1, this.getPrimaryScrollView().viewportHeight - PAGE_SCROLL_OVERLAP));
459
+ }
460
+ return { consume: true };
461
+ }
462
+ if (keybindings.matches(data, "tui.altScreen.halfPageUp")) {
463
+ if (!isRelease)
464
+ this.scrollBy(-Math.max(1, Math.floor(this.getPrimaryScrollView().viewportHeight / 2)));
465
+ return { consume: true };
466
+ }
467
+ if (keybindings.matches(data, "tui.altScreen.halfPageDown")) {
468
+ if (!isRelease)
469
+ this.scrollBy(Math.max(1, Math.floor(this.getPrimaryScrollView().viewportHeight / 2)));
470
+ return { consume: true };
471
+ }
472
+ if (keybindings.matches(data, "tui.altScreen.lineUp")) {
473
+ if (!isRelease)
474
+ this.scrollBy(-1);
475
+ return { consume: true };
476
+ }
477
+ if (keybindings.matches(data, "tui.altScreen.lineDown")) {
478
+ if (!isRelease)
479
+ this.scrollBy(1);
480
+ return { consume: true };
481
+ }
482
+ if (keybindings.matches(data, "tui.altScreen.previousPrompt")) {
483
+ if (!isRelease)
484
+ this.scrollToPrompt(-1);
485
+ return { consume: true };
486
+ }
487
+ if (keybindings.matches(data, "tui.altScreen.nextPrompt")) {
488
+ if (!isRelease)
489
+ this.scrollToPrompt(1);
490
+ return { consume: true };
491
+ }
492
+ if (keybindings.matches(data, "tui.altScreen.top")) {
493
+ if (!isRelease)
494
+ this.scrollToTop();
495
+ return { consume: true };
496
+ }
497
+ if (keybindings.matches(data, "tui.altScreen.bottom")) {
498
+ if (!isRelease)
499
+ this.scrollToBottom();
500
+ return { consume: true };
501
+ }
502
+ return undefined;
503
+ }
504
+ parseWheelEvent(data) {
505
+ const sgr = /^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);
506
+ if (sgr) {
507
+ const button = Number.parseInt(sgr[1], 10);
508
+ if ((button & 64) === 0)
509
+ return undefined;
510
+ const direction = button & 3;
511
+ if (direction !== 0 && direction !== 1)
512
+ return undefined;
513
+ return {
514
+ direction: direction === 0 ? -1 : 1,
515
+ x: Number.parseInt(sgr[2], 10) - 1,
516
+ y: Number.parseInt(sgr[3], 10) - 1,
517
+ };
518
+ }
519
+ if (data.length === 6 && data.startsWith("\x1b[M")) {
520
+ const button = data.charCodeAt(3) - 32;
521
+ if ((button & 64) === 0)
522
+ return undefined;
523
+ const direction = button & 3;
524
+ if (direction !== 0 && direction !== 1)
525
+ return undefined;
526
+ return {
527
+ direction: direction === 0 ? -1 : 1,
528
+ x: data.charCodeAt(4) - 33,
529
+ y: data.charCodeAt(5) - 33,
530
+ };
531
+ }
532
+ return undefined;
533
+ }
534
+ routeWheel(event) {
535
+ let remaining = event.direction * this.wheelScrollLines;
536
+ const seen = new Set();
537
+ for (const scrollView of this.currentLayout ? getScrollViewsAt(this.currentLayout, event.x, event.y) : []) {
538
+ seen.add(scrollView);
539
+ remaining = scrollView.scrollBy(remaining);
540
+ if (remaining === 0 || scrollView.overscroll === "contain")
541
+ break;
542
+ }
543
+ const primary = this.getPrimaryScrollView();
544
+ if (remaining !== 0 && !seen.has(primary))
545
+ primary.scrollBy(remaining);
546
+ this.updateScrollbarHover(event.x, event.y);
547
+ this.requestRender();
548
+ }
549
+ parseSgrMouseEvent(data) {
550
+ const match = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
551
+ if (!match)
552
+ return undefined;
553
+ return {
554
+ button: Number.parseInt(match[1], 10),
555
+ x: Number.parseInt(match[2], 10) - 1,
556
+ y: Number.parseInt(match[3], 10) - 1,
557
+ release: match[4] === "m",
558
+ };
559
+ }
560
+ handleRightClickPaste(event) {
561
+ if (!this.onRightClickPaste ||
562
+ process.platform !== "win32" ||
563
+ process.env.TERM_PROGRAM?.toLowerCase() === "vscode" ||
564
+ event.release ||
565
+ event.button !== 2) {
566
+ return false;
567
+ }
568
+ try {
569
+ this.onRightClickPaste();
570
+ }
571
+ catch {
572
+ // Clipboard paste is best-effort.
573
+ }
574
+ return true;
575
+ }
576
+ getScrollbarTargetAt(x, y) {
577
+ if (this.hasOverlay() || !this.currentLayout)
578
+ return undefined;
579
+ for (const scrollView of getScrollViewsAt(this.currentLayout, x, y)) {
580
+ const box = getScrollViewBox(this.currentLayout, scrollView);
581
+ const geometry = box ? getScrollbarGeometry(box) : undefined;
582
+ if (geometry &&
583
+ x === geometry.column &&
584
+ y >= geometry.thumbTop &&
585
+ y < geometry.thumbTop + geometry.thumbHeight) {
586
+ return { scrollView, geometry };
587
+ }
588
+ }
589
+ return undefined;
590
+ }
591
+ setScrollbarHover(scrollView) {
592
+ if (scrollView === this.scrollbarHover)
593
+ return;
594
+ this.scrollbarHover?.setScrollbarActive(false);
595
+ this.scrollbarHover = scrollView;
596
+ this.scrollbarHover?.setScrollbarActive(true);
597
+ }
598
+ updateScrollbarHover(x, y) {
599
+ this.setScrollbarHover(this.getScrollbarTargetAt(x, y)?.scrollView);
600
+ }
601
+ stopScrollbarHover() {
602
+ this.setScrollbarHover(undefined);
603
+ }
604
+ handleScrollbarMouseEvent(event) {
605
+ if (this.scrollbarDrag) {
606
+ if (event.release) {
607
+ this.stopScrollbarDrag();
608
+ return true;
609
+ }
610
+ const box = this.currentLayout
611
+ ? getScrollViewBox(this.currentLayout, this.scrollbarDrag.scrollView)
612
+ : undefined;
613
+ const geometry = box ? getScrollbarGeometry(box) : undefined;
614
+ if (geometry) {
615
+ const maxThumbOffset = geometry.trackHeight - geometry.thumbHeight;
616
+ const thumbOffset = Math.max(0, Math.min(maxThumbOffset, event.y - geometry.trackTop - this.scrollbarDrag.grabOffset));
617
+ const scrollTop = maxThumbOffset === 0 ? 0 : Math.round((thumbOffset / maxThumbOffset) * geometry.maxScrollTop);
618
+ this.scrollbarDrag.scrollView.scrollTo(scrollTop);
619
+ }
620
+ return true;
621
+ }
622
+ if (event.release || (event.button & 32) !== 0 || (event.button & 3) !== 0)
623
+ return false;
624
+ const target = this.getScrollbarTargetAt(event.x, event.y);
625
+ if (!target)
626
+ return false;
627
+ this.stopSelectionAutoScroll();
628
+ this.selectionPressActive = false;
629
+ this.selectionAnchor = undefined;
630
+ this.selectionFocus = undefined;
631
+ this.selectionGranularity = "character";
632
+ this.selectionInitialRange = undefined;
633
+ this.lastClick = undefined;
634
+ this.pressedUrl = undefined;
635
+ this.selectionDragged = false;
636
+ this.setScrollbarHover(target.scrollView);
637
+ this.scrollbarDrag = {
638
+ scrollView: target.scrollView,
639
+ grabOffset: event.y - target.geometry.thumbTop,
640
+ };
641
+ return true;
642
+ }
643
+ stopScrollbarDrag() {
644
+ this.scrollbarDrag = undefined;
645
+ }
646
+ getScrollSelectionPoint(scrollView, x, y) {
647
+ if (!this.currentLayout)
648
+ return undefined;
649
+ const box = getScrollViewBox(this.currentLayout, scrollView);
650
+ if (!box || box.rect.height <= 0 || box.clip.height <= 0)
651
+ return undefined;
652
+ const visibleTop = Math.max(0, box.rect.y, box.clip.y);
653
+ const visibleBottom = Math.min(this.terminal.rows - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
654
+ if (visibleBottom < visibleTop)
655
+ return undefined;
656
+ const pointerRow = Math.max(visibleTop, Math.min(visibleBottom, y));
657
+ const maxContentRow = Math.max(0, (box.scrollContentLines?.length ?? 1) - 1);
658
+ return {
659
+ row: Math.max(0, Math.min(maxContentRow, scrollView.scrollTop + pointerRow - box.rect.y)),
660
+ col: Math.max(0, Math.min(box.rect.width - 1, x - box.rect.x)),
661
+ scrollView,
662
+ };
663
+ }
664
+ getSelectionPoint(event, scrollView) {
665
+ if (scrollView) {
666
+ const point = this.getScrollSelectionPoint(scrollView, event.x, event.y);
667
+ if (point)
668
+ return point;
669
+ }
670
+ return {
671
+ row: Math.max(0, Math.min(this.terminal.rows - 1, event.y)),
672
+ col: Math.max(0, Math.min(this.terminal.columns - 1, event.x)),
673
+ };
674
+ }
675
+ getSelectionSourceLine(point) {
676
+ if (point.scrollView && this.currentLayout) {
677
+ const lines = getScrollViewBox(this.currentLayout, point.scrollView)?.scrollContentLines;
678
+ if (lines)
679
+ return lines[point.row] ?? "";
680
+ }
681
+ return this.previousScreen[point.row] ?? "";
682
+ }
683
+ getWordSelection(point) {
684
+ const line = stripTerminalSequences(this.getSelectionSourceLine(point));
685
+ let start = 0;
686
+ for (const segment of wordSegmenter.segment(line)) {
687
+ const end = start + visibleWidth(segment.segment);
688
+ if (point.col >= start && point.col < end) {
689
+ return {
690
+ start: { ...point, col: start },
691
+ end: { ...point, col: end, boundary: true },
692
+ };
693
+ }
694
+ start = end;
695
+ }
696
+ return undefined;
697
+ }
698
+ getLineSelection(point) {
699
+ return {
700
+ start: { ...point, col: 0 },
701
+ end: { ...point, col: visibleWidth(this.getSelectionSourceLine(point)), boundary: true },
702
+ };
703
+ }
704
+ updateSelectionFocus(point) {
705
+ if (this.selectionGranularity === "character" || !this.selectionInitialRange) {
706
+ this.selectionFocus = point;
707
+ return;
708
+ }
709
+ const range = this.selectionGranularity === "word" ? this.getWordSelection(point) : this.getLineSelection(point);
710
+ if (!range)
711
+ return;
712
+ const initial = this.selectionInitialRange;
713
+ const targetBeforeInitial = range.start.row < initial.start.row ||
714
+ (range.start.row === initial.start.row && range.start.col < initial.start.col);
715
+ if (targetBeforeInitial) {
716
+ this.selectionAnchor = initial.end;
717
+ this.selectionFocus = range.start;
718
+ }
719
+ else {
720
+ this.selectionAnchor = initial.start;
721
+ this.selectionFocus = range.end;
722
+ }
723
+ }
724
+ getClickCount(point, word) {
725
+ const now = Date.now();
726
+ const previous = this.lastClick;
727
+ const count = word &&
728
+ previous &&
729
+ now - previous.timestamp <= DOUBLE_CLICK_INTERVAL_MS &&
730
+ previous.row === point.row &&
731
+ previous.scrollView === point.scrollView &&
732
+ previous.wordStart === word.start.col &&
733
+ previous.wordEnd === word.end.col
734
+ ? (previous.count % 3) + 1
735
+ : 1;
736
+ this.lastClick = word
737
+ ? {
738
+ timestamp: now,
739
+ count,
740
+ row: point.row,
741
+ scrollView: point.scrollView,
742
+ wordStart: word.start.col,
743
+ wordEnd: word.end.col,
744
+ }
745
+ : undefined;
746
+ return count;
747
+ }
748
+ updateSelectionAutoScroll(event) {
749
+ const scrollView = this.selectionAnchor?.scrollView;
750
+ if (!scrollView || !this.currentLayout) {
751
+ this.stopSelectionAutoScroll();
752
+ return;
753
+ }
754
+ const box = getScrollViewBox(this.currentLayout, scrollView);
755
+ if (!box || box.rect.height <= 0 || box.clip.height <= 0) {
756
+ this.stopSelectionAutoScroll();
757
+ return;
758
+ }
759
+ const visibleTop = Math.max(0, box.rect.y, box.clip.y);
760
+ const visibleBottom = Math.min(this.terminal.rows - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
761
+ this.selectionDragPointer = { x: event.x, y: event.y };
762
+ this.selectionAutoScrollDirection = event.y <= visibleTop ? -1 : event.y >= visibleBottom ? 1 : 0;
763
+ if (this.selectionAutoScrollDirection === 0) {
764
+ this.stopSelectionAutoScroll();
765
+ return;
766
+ }
767
+ if (this.selectionAutoScrollTimer)
768
+ return;
769
+ this.selectionAutoScrollTimer = setInterval(() => this.autoScrollSelection(), 50);
770
+ this.selectionAutoScrollTimer.unref();
771
+ }
772
+ autoScrollSelection() {
773
+ const scrollView = this.selectionAnchor?.scrollView;
774
+ const pointer = this.selectionDragPointer;
775
+ const direction = this.selectionAutoScrollDirection;
776
+ if (!scrollView || !pointer || direction === 0) {
777
+ this.stopSelectionAutoScroll();
778
+ return;
779
+ }
780
+ const remaining = scrollView.scrollBy(direction);
781
+ if (remaining === direction) {
782
+ this.stopSelectionAutoScroll();
783
+ return;
784
+ }
785
+ const point = this.getScrollSelectionPoint(scrollView, pointer.x, pointer.y);
786
+ if (point)
787
+ this.updateSelectionFocus(point);
788
+ this.requestRender();
789
+ }
790
+ stopSelectionAutoScroll() {
791
+ if (this.selectionAutoScrollTimer) {
792
+ clearInterval(this.selectionAutoScrollTimer);
793
+ this.selectionAutoScrollTimer = undefined;
794
+ }
795
+ this.selectionAutoScrollDirection = 0;
796
+ this.selectionDragPointer = undefined;
797
+ }
798
+ handleSelectionMouseEvent(event) {
799
+ const button = event.button & 3;
800
+ if (button !== 0 && !(event.release && button === 3))
801
+ return;
802
+ const anchorScrollView = this.selectionAnchor?.scrollView;
803
+ const point = this.getSelectionPoint(event, anchorScrollView);
804
+ if (event.release) {
805
+ if (!this.selectionPressActive)
806
+ return;
807
+ this.selectionPressActive = false;
808
+ this.stopSelectionAutoScroll();
809
+ if (!this.selectionAnchor)
810
+ return;
811
+ this.updateSelectionFocus(point);
812
+ const clickedUrl = !this.selectionDragged &&
813
+ this.selectionAnchor.scrollView === point.scrollView &&
814
+ this.selectionAnchor.row === point.row &&
815
+ this.selectionAnchor.col === point.col
816
+ ? this.pressedUrl
817
+ : undefined;
818
+ this.pressedUrl = undefined;
819
+ if (clickedUrl && this.openUrl) {
820
+ this.selectionAnchor = undefined;
821
+ this.selectionFocus = undefined;
822
+ try {
823
+ this.openUrl(clickedUrl);
824
+ }
825
+ catch {
826
+ // URL activation is best-effort.
827
+ }
828
+ this.requestRender();
829
+ return;
830
+ }
831
+ void this.copySelectionToClipboard();
832
+ this.requestRender();
833
+ return;
834
+ }
835
+ if ((event.button & 32) !== 0) {
836
+ if (!this.selectionPressActive || !this.selectionAnchor)
837
+ return;
838
+ this.selectionDragged = true;
839
+ this.lastClick = undefined;
840
+ this.pressedUrl = undefined;
841
+ this.updateSelectionFocus(point);
842
+ this.updateSelectionAutoScroll(event);
843
+ this.requestRender();
844
+ return;
845
+ }
846
+ this.stopSelectionAutoScroll();
847
+ this.selectionPressActive = true;
848
+ const scrollView = !this.hasOverlay() && this.currentLayout
849
+ ? getScrollViewsAt(this.currentLayout, event.x, event.y)[0]
850
+ : undefined;
851
+ const anchor = this.getSelectionPoint(event, scrollView);
852
+ const word = this.getWordSelection(anchor);
853
+ const clickCount = this.getClickCount(anchor, word);
854
+ const range = clickCount === 2 ? word : clickCount === 3 ? this.getLineSelection(anchor) : undefined;
855
+ this.selectionGranularity = range ? (clickCount === 2 ? "word" : "line") : "character";
856
+ this.selectionInitialRange = range;
857
+ this.selectionAnchor = range?.start ?? anchor;
858
+ this.selectionFocus = range?.end ?? anchor;
859
+ this.selectionDragged = false;
860
+ this.pressedUrl = range
861
+ ? undefined
862
+ : getOsc8LinkAtColumn(this.previousScreen[Math.max(0, Math.min(this.terminal.rows - 1, event.y))] ?? "", Math.max(0, Math.min(this.terminal.columns - 1, event.x)));
863
+ this.requestRender();
864
+ }
865
+ getSelectionBounds() {
866
+ if (!this.selectionAnchor || !this.selectionFocus)
867
+ return undefined;
868
+ if (this.selectionAnchor.scrollView !== this.selectionFocus.scrollView)
869
+ return undefined;
870
+ const anchorBeforeFocus = this.selectionAnchor.row < this.selectionFocus.row ||
871
+ (this.selectionAnchor.row === this.selectionFocus.row && this.selectionAnchor.col < this.selectionFocus.col);
872
+ if (this.selectionAnchor.row === this.selectionFocus.row &&
873
+ this.selectionAnchor.col === this.selectionFocus.col) {
874
+ return undefined;
875
+ }
876
+ return anchorBeforeFocus
877
+ ? { start: this.selectionAnchor, end: this.selectionFocus }
878
+ : { start: this.selectionFocus, end: this.selectionAnchor };
879
+ }
880
+ getSelectionColumns(line, row, selection, minColumn = 0, maxColumn = visibleWidth(line)) {
881
+ const lineWidth = visibleWidth(line);
882
+ let start = Math.max(0, minColumn);
883
+ let end = Math.min(lineWidth, maxColumn);
884
+ if (row === selection.start.row) {
885
+ start = getGraphemeCellRange(line, selection.start.col)?.start ?? Math.min(selection.start.col, lineWidth);
886
+ }
887
+ if (row === selection.end.row) {
888
+ end = selection.end.boundary
889
+ ? Math.min(selection.end.col, lineWidth)
890
+ : (getGraphemeCellRange(line, selection.end.col)?.end ?? Math.min(selection.end.col + 1, lineWidth));
891
+ }
892
+ return { start: Math.max(minColumn, start), end: Math.min(maxColumn, end) };
893
+ }
894
+ async copySelectionToClipboard() {
895
+ const selection = this.getSelectionBounds();
896
+ if (!selection)
897
+ return;
898
+ let sourceLines = this.previousScreen;
899
+ if (selection.start.scrollView) {
900
+ if (!this.currentLayout)
901
+ return;
902
+ const box = getScrollViewBox(this.currentLayout, selection.start.scrollView);
903
+ if (!box?.scrollContentLines)
904
+ return;
905
+ sourceLines = box.scrollContentLines;
906
+ }
907
+ const lines = [];
908
+ for (let row = selection.start.row; row <= selection.end.row; row++) {
909
+ const line = sourceLines[row] ?? "";
910
+ const columns = this.getSelectionColumns(line, row, selection);
911
+ lines.push(stripTerminalSequences(sliceByColumn(line, columns.start, Math.max(0, columns.end - columns.start), true)).trimEnd());
912
+ }
913
+ const text = lines.join("\n");
914
+ if (text.length === 0)
915
+ return;
916
+ // Prefer an injected clipboard implementation (native clipboard + platform tools with a
917
+ // verified success path) when the host app provides one. A bare OSC 52 write can show
918
+ // "Copied!" while leaving the system clipboard untouched (e.g. macOS Terminal.app, tmux
919
+ // without OSC 52 clipboard passthrough), so only report success when it actually copies.
920
+ if (this.copySelection) {
921
+ const ok = await this.copySelection(text);
922
+ this.flash(ok ? "Copied!" : "Copy failed");
923
+ return;
924
+ }
925
+ this.terminal.write(`\x1b]52;c;${Buffer.from(text).toString("base64")}\x07`);
926
+ this.flash("Copied!");
927
+ }
928
+ applySearchTextHighlight(text, current) {
929
+ const style = current ? this.searchCurrentMatchStyle : this.searchMatchStyle;
930
+ let result = "";
931
+ let plainStart = 0;
932
+ let index = 0;
933
+ while (index < text.length) {
934
+ const ansi = extractAnsiCode(text, index);
935
+ if (!ansi) {
936
+ index += 1;
937
+ continue;
938
+ }
939
+ if (index > plainStart)
940
+ result += style(text.slice(plainStart, index));
941
+ result += ansi.code;
942
+ index += ansi.length;
943
+ plainStart = index;
944
+ }
945
+ if (plainStart < text.length)
946
+ result += style(text.slice(plainStart));
947
+ return result;
948
+ }
949
+ applySearchHighlights(screen, layout) {
950
+ const search = this.activeSearch;
951
+ if (!search || search.selectedIndex < 0 || search.matches.length === 0)
952
+ return screen;
953
+ const scrollView = layout.primaryScrollView ?? this.implicitScrollView;
954
+ const box = getScrollViewBox(layout, scrollView);
955
+ if (!box)
956
+ return screen;
957
+ const rangesByRow = new Map();
958
+ const scrollbarColumn = getScrollbarGeometry(box)?.column;
959
+ const minRow = Math.max(0, box.rect.y, box.clip.y);
960
+ const maxRow = Math.min(screen.length, box.rect.y + box.rect.height, box.clip.y + box.clip.height);
961
+ const minColumn = Math.max(0, box.rect.x, box.clip.x);
962
+ const maxColumn = Math.min(this.terminal.columns, box.rect.x + box.rect.width, box.clip.x + box.clip.width, scrollbarColumn ?? Number.POSITIVE_INFINITY);
963
+ for (let matchIndex = 0; matchIndex < search.matches.length; matchIndex++) {
964
+ for (const segment of search.matches[matchIndex].segments) {
965
+ const row = box.rect.y + segment.row - scrollView.scrollTop;
966
+ if (row < minRow || row >= maxRow)
967
+ continue;
968
+ const startCol = Math.max(minColumn, box.rect.x + segment.startCol);
969
+ const endCol = Math.min(maxColumn, box.rect.x + segment.endCol);
970
+ if (endCol <= startCol)
971
+ continue;
972
+ const ranges = rangesByRow.get(row) ?? [];
973
+ ranges.push({ startCol, endCol, current: matchIndex === search.selectedIndex });
974
+ rangesByRow.set(row, ranges);
975
+ }
976
+ }
977
+ const result = [...screen];
978
+ for (const [row, ranges] of rangesByRow) {
979
+ let line = result[row] ?? "";
980
+ if (isImageLine(line))
981
+ continue;
982
+ const lineWidth = visibleWidth(line);
983
+ for (const range of ranges.sort((a, b) => b.startCol - a.startCol)) {
984
+ const startCol = Math.min(range.startCol, lineWidth);
985
+ const endCol = Math.min(range.endCol, lineWidth);
986
+ if (endCol <= startCol)
987
+ continue;
988
+ const before = sliceByColumn(line, 0, startCol, true);
989
+ const highlighted = sliceByColumn(line, startCol, endCol - startCol, true);
990
+ const after = sliceByColumn(line, endCol, Math.max(0, lineWidth - endCol), true);
991
+ line = `${before}${this.applySearchTextHighlight(highlighted, range.current)}${after}`;
992
+ }
993
+ result[row] = line;
994
+ }
995
+ return result;
996
+ }
997
+ applySelectionHighlight(text) {
998
+ let result = "\x1b[7m";
999
+ let index = 0;
1000
+ while (index < text.length) {
1001
+ const ansi = extractAnsiCode(text, index);
1002
+ if (!ansi) {
1003
+ result += text[index];
1004
+ index += 1;
1005
+ continue;
1006
+ }
1007
+ result += ansi.code;
1008
+ if (ansi.code.endsWith("m"))
1009
+ result += "\x1b[7m";
1010
+ index += ansi.length;
1011
+ }
1012
+ return `${result}\x1b[27m`;
1013
+ }
1014
+ applySelection(screen, layout = this.currentLayout) {
1015
+ const selection = this.getSelectionBounds();
1016
+ if (!selection)
1017
+ return screen;
1018
+ let screenSelection = selection;
1019
+ let minRow = 0;
1020
+ let maxRow = screen.length - 1;
1021
+ let minColumn = 0;
1022
+ let maxColumn = this.terminal.columns;
1023
+ if (selection.start.scrollView) {
1024
+ if (!layout)
1025
+ return screen;
1026
+ const box = getScrollViewBox(layout, selection.start.scrollView);
1027
+ if (!box)
1028
+ return screen;
1029
+ minRow = Math.max(0, box.rect.y, box.clip.y);
1030
+ maxRow = Math.min(screen.length - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
1031
+ minColumn = Math.max(0, box.rect.x, box.clip.x);
1032
+ maxColumn = Math.min(this.terminal.columns, box.rect.x + box.rect.width, box.clip.x + box.clip.width);
1033
+ screenSelection = {
1034
+ start: {
1035
+ ...selection.start,
1036
+ row: box.rect.y + selection.start.row - selection.start.scrollView.scrollTop,
1037
+ col: box.rect.x + selection.start.col,
1038
+ },
1039
+ end: {
1040
+ ...selection.end,
1041
+ row: box.rect.y + selection.end.row - selection.start.scrollView.scrollTop,
1042
+ col: box.rect.x + selection.end.col,
1043
+ },
1044
+ };
1045
+ }
1046
+ return screen.map((line, row) => {
1047
+ if (row < minRow ||
1048
+ row > maxRow ||
1049
+ row < screenSelection.start.row ||
1050
+ row > screenSelection.end.row ||
1051
+ isImageLine(line)) {
1052
+ return line;
1053
+ }
1054
+ const lineWidth = visibleWidth(line);
1055
+ const columns = this.getSelectionColumns(line, row, screenSelection, minColumn, maxColumn);
1056
+ if (columns.end <= columns.start)
1057
+ return line;
1058
+ const before = sliceByColumn(line, 0, columns.start, true);
1059
+ const selected = sliceByColumn(line, columns.start, columns.end - columns.start, true);
1060
+ const after = sliceByColumn(line, columns.end, Math.max(0, lineWidth - columns.end), true);
1061
+ return `${before}${this.applySelectionHighlight(selected)}${after}`;
1062
+ });
1063
+ }
1064
+ isMouseSequence(data) {
1065
+ return /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data) || (data.length === 6 && data.startsWith("\x1b[M"));
1066
+ }
1067
+ compositeFlashes(screen, width, height) {
1068
+ const flashLines = this.flashes.render(width).slice(-height);
1069
+ if (flashLines.length === 0)
1070
+ return screen;
1071
+ const result = [...screen];
1072
+ while (result.length < height)
1073
+ result.push("");
1074
+ for (let row = 0; row < flashLines.length; row++) {
1075
+ const line = flashLines[row];
1076
+ const flashWidth = visibleWidth(line);
1077
+ if (flashWidth === 0)
1078
+ continue;
1079
+ result[row] = compositeTuiLine(result[row] ?? "", line, width - flashWidth, flashWidth, width);
1080
+ }
1081
+ return result;
1082
+ }
1083
+ doRender() {
1084
+ if (this.stopped || !this.altScreenActive)
1085
+ return;
1086
+ const width = Math.max(1, this.terminal.columns);
1087
+ const height = Math.max(1, this.terminal.rows);
1088
+ const root = this.layoutRoot ?? this.implicitScrollView;
1089
+ let nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender());
1090
+ if (this.refreshSearch(nextLayout)) {
1091
+ nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender());
1092
+ }
1093
+ let screen = nextLayout.lines.map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
1094
+ screen = this.applySearchHighlights(screen, nextLayout);
1095
+ screen = this.compositeOverlays(screen, width, height);
1096
+ if (screen.length > height)
1097
+ screen = screen.slice(screen.length - height);
1098
+ screen = this.applySelection(screen, nextLayout);
1099
+ screen = this.compositeFlashes(screen, width, height);
1100
+ const cursorPos = this.extractCursorPosition(screen, height);
1101
+ screen = this.applyLineResets(screen).map((line) => {
1102
+ if (isImageLine(line) || visibleWidth(line) <= width)
1103
+ return line;
1104
+ return sliceByColumn(line, 0, width, true);
1105
+ });
1106
+ const fullRedraw = this.previousScreen.length === 0 || this.previousScreenWidth !== width || this.previousScreenHeight !== height;
1107
+ const imagesNeedRedraw = screen.some((line, row) => line !== this.previousScreen[row] && (isImageLine(line) || isImageLine(this.previousScreen[row] ?? "")));
1108
+ const redrawImages = fullRedraw || imagesNeedRedraw;
1109
+ const hadUploadedKittyImages = this.uploadedKittyImages.size > 0;
1110
+ const preparedKittyScreen = redrawImages && this.imageProtocol === "kitty"
1111
+ ? this.prepareKittyScreen(screen)
1112
+ : { lines: screen, evictedImageDeletion: "" };
1113
+ let buffer = BEGIN_SYNCHRONIZED_OUTPUT;
1114
+ if (fullRedraw) {
1115
+ this.fullRedrawCount += 1;
1116
+ const clearImages = this.imageProtocol === "kitty" && hadUploadedKittyImages
1117
+ ? deleteAllKittyPlacements()
1118
+ : this.deleteKittyImages();
1119
+ buffer += `${clearImages}\x1b[2J`;
1120
+ }
1121
+ else if (imagesNeedRedraw) {
1122
+ if (this.imageProtocol === "iterm2")
1123
+ buffer += "\x1b[2J";
1124
+ else if (this.imageProtocol === "kitty")
1125
+ buffer += deleteAllKittyPlacements();
1126
+ }
1127
+ buffer += preparedKittyScreen.evictedImageDeletion;
1128
+ for (let row = 0; row < height; row++) {
1129
+ if (!fullRedraw && !imagesNeedRedraw && screen[row] === this.previousScreen[row])
1130
+ continue;
1131
+ buffer += `\x1b[${row + 1};1H\x1b[2K${preparedKittyScreen.lines[row] ?? ""}`;
1132
+ }
1133
+ if (cursorPos) {
1134
+ buffer += `\x1b[${cursorPos.row + 1};${Math.min(width, cursorPos.col) + 1}H`;
1135
+ buffer += this.getShowHardwareCursor() ? "\x1b[?25h" : "\x1b[?25l";
1136
+ }
1137
+ else {
1138
+ buffer += "\x1b[?25l";
1139
+ }
1140
+ buffer += END_SYNCHRONIZED_OUTPUT;
1141
+ this.terminal.write(buffer);
1142
+ this.previousScreen = screen;
1143
+ this.previousScreenWidth = width;
1144
+ this.previousScreenHeight = height;
1145
+ this.currentLayout = nextLayout;
1146
+ }
1147
+ }
1148
+ //# sourceMappingURL=tui-alt-screen.js.map