@bramburn/qi-tui 0.0.0-stage → 0.85.1

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